]> git.cworth.org Git - sup/blob - lib/sup/message.rb
moved evertying to devel
[sup] / lib / sup / message.rb
1 require 'tempfile'
2 require 'time'
3
4 module Redwood
5
6 class MessageFormatError < StandardError; end
7
8 ## a Message is what's threaded.
9 ##
10 ## it is also where the parsing for quotes and signatures is done, but
11 ## that should be moved out to a separate class at some point (because
12 ## i would like, for example, to be able to add in a ruby-talk
13 ## specific module that would detect and link to /ruby-talk:\d+/
14 ## sequences in the text of an email. (how sweet would that be?)
15 ##
16 ## TODO: integrate with user's addressbook to render names
17 ## appropriately.
18 class Message
19   SNIPPET_LEN = 80
20   RE_PATTERN = /^((re|re[\[\(]\d[\]\)]):\s*)+/i
21     
22   ## some utility methods
23   class << self
24     def normalize_subj s; s.gsub(RE_PATTERN, ""); end
25     def subj_is_reply? s; s =~ RE_PATTERN; end
26     def reify_subj s; subj_is_reply?(s) ? s : "Re: " + s; end
27   end
28
29   class Attachment
30     attr_reader :content_type, :desc
31     def initialize content_type, desc, part
32       @content_type = content_type
33       @desc = desc
34       @part = part
35       @file = nil
36     end
37
38     def view!
39       unless @file
40         @file = Tempfile.new "redwood.attachment"
41         @file.print @part.decode
42         @file.close
43       end
44
45       ## TODO: handle unknown mime-types
46       system "/usr/bin/run-mailcap --action=view #{@content_type}:#{@file.path}"
47     end
48   end
49
50   class Text
51     attr_reader :lines
52     def initialize lines
53       ## do some wrapping
54       @lines = lines.map { |l| l.wrap 80 }.flatten
55     end
56   end
57
58   class Quote
59     attr_reader :lines
60     def initialize lines
61       @lines = lines
62     end
63   end
64
65   class Signature
66     attr_reader :lines
67     def initialize lines
68       @lines = lines
69     end
70   end
71
72   QUOTE_PATTERN = /^\s{0,4}[>|\}]/
73   BLOCK_QUOTE_PATTERN = /^-----\s*Original Message\s*----+$/
74   QUOTE_START_PATTERN = /(^\s*Excerpts from)|(^\s*In message )|(^\s*In article )|(^\s*Quoting )|((wrote|writes|said|says)\s*:\s*$)/
75   SIG_PATTERN = /(^-- ?$)|(^\s*----------+\s*$)|(^\s*_________+\s*$)/
76   SIG_DISTANCE = 15 # lines from the end
77   DEFAULT_SUBJECT = "(missing subject)"
78   DEFAULT_SENDER = "(missing sender)"
79
80   attr_reader :id, :date, :from, :subj, :refs, :replytos, :to, :source,
81               :cc, :bcc, :labels, :list_address, :recipient_email, :replyto,
82               :source_info, :mbox_status
83
84   bool_reader :dirty
85
86   def initialize source, source_info, labels, snippet=nil
87     @source = source
88     @source_info = source_info
89     @dirty = false
90     @snippet = snippet
91     @labels = labels
92
93     header = @source.load_header @source_info
94     header.each { |k, v| header[k.downcase] = v }
95
96     %w(message-id date).each do |f|
97       raise MessageFormatError, "no #{f} field in header #{header.inspect} (source #@source offset #@source_info)" unless header.include? f
98       raise MessageFormatError, "nil #{f} field in header #{header.inspect} (source #@source offset #@source_info)" unless header[f]
99     end
100
101     begin
102       @date = Time.parse header["date"]
103     rescue ArgumentError => e
104       raise MessageFormatError, "unparsable date #{header['date']}: #{e.message}"
105     end
106
107     if(@subj = header["subject"])
108       @subj = @subj.gsub(/\s+/, " ").gsub(/\s+$/, "")
109     else
110       @subj = DEFAULT_SUBJECT
111     end
112     @from = Person.for header["from"]
113     @to = Person.for_several header["to"]
114     @cc = Person.for_several header["cc"]
115     @bcc = Person.for_several header["bcc"]
116     @id = header["message-id"]
117     @refs = (header["references"] || "").scan(/<(.*?)>/).flatten
118     @replytos = (header["in-reply-to"] || "").scan(/<(.*?)>/).flatten
119     @replyto = Person.for header["reply-to"]
120     @list_address =
121       if header["list-post"]
122         @list_address = Person.for header["list-post"].gsub(/^<mailto:|>$/, "")
123       else
124         nil
125       end
126
127     @recipient_email = header["delivered-to"]
128     @mbox_status = header["status"]
129   end
130
131   def snippet
132     to_chunks unless @snippet
133     @snippet
134   end
135
136   def is_list_message?; !@list_address.nil?; end
137   def is_draft?; DraftLoader === @source; end
138   def draft_filename
139     raise "not a draft" unless is_draft?
140     @source.fn_for_offset @source_info
141   end
142
143   def save index
144     index.update_message self if @dirty
145     @dirty = false
146   end
147
148   def has_label? t; @labels.member? t; end
149   def add_label t
150     return if @labels.member? t
151     @labels.push t
152     @dirty = true
153   end
154   def remove_label t
155     return unless @labels.member? t
156     @labels.delete t
157     @dirty = true
158   end
159
160   def recipients
161     @to + @cc + @bcc
162   end
163
164   def labels= l
165     @labels = l
166     @dirty = true
167   end
168
169   def to_chunks
170     m = @source.load_message @source_info
171     message_to_chunks m
172   end
173
174   def header_text
175     @source.load_header_text @source_info
176   end
177
178   def content
179     [
180       from && from.longname,
181       to.map { |p| p.longname },
182       cc.map { |p| p.longname },
183       bcc.map { |p| p.longname },
184       to_chunks.select { |c| c.is_a? Text }.map { |c| c.lines },
185       subj,
186     ].flatten.compact.join " "
187   end
188
189   def basic_body_lines
190     to_chunks.find_all { |c| c.is_a?(Text) || c.is_a?(Quote) }.map { |c| c.lines }.flatten
191   end
192
193   def basic_header_lines
194     ["From: #{@from.full_address}"] +
195       (@to.empty? ? [] : ["To: " + @to.map { |p| p.full_address }.join(", ")]) +
196       (@cc.empty? ? [] : ["Cc: " + @cc.map { |p| p.full_address }.join(", ")]) +
197       (@bcc.empty? ? [] : ["Bcc: " + @bcc.map { |p| p.full_address }.join(", ")]) +
198       ["Date: #{@date.rfc822}",
199        "Subject: #{@subj}"]
200   end
201
202 private
203
204   ## everything RubyMail-specific goes here.
205   def message_to_chunks m
206     ret = [] <<
207       case m.header.content_type
208       when "text/plain", nil
209         raise MessageFormatError, "no message body before decode" unless
210           m.body
211         body = m.decode or raise MessageFormatError, "no message body"
212         text_to_chunks body.gsub(/\t/, "    ").gsub(/\r/, "").split("\n")
213       when "multipart/alternative", "multipart/mixed"
214         nil
215       else
216         disp = m.header["Content-Disposition"] || ""
217         Attachment.new m.header.content_type, disp.gsub(/[\s\n]+/, " "), m
218       end
219     
220     m.each_part { |p| ret << message_to_chunks(p) } if m.multipart?
221     ret.compact.flatten
222   end
223
224   ## parse the lines of text into chunk objects.  the heuristics here
225   ## need tweaking in some nice manner. TODO: move these heuristics
226   ## into the classes themselves.
227
228   def text_to_chunks lines
229     state = :text # one of :text, :quote, or :sig
230     chunks = []
231     chunk_lines = []
232
233     lines.each_with_index do |line, i|
234       nextline = lines[(i + 1) ... lines.length].find { |l| l !~ /^\s*$/ } # skip blank lines
235       case state
236       when :text
237         newstate = nil
238         if line =~ QUOTE_PATTERN || (line =~ QUOTE_START_PATTERN && (nextline =~ QUOTE_PATTERN || nextline =~ QUOTE_START_PATTERN))
239           newstate = :quote
240         elsif line =~ SIG_PATTERN && (lines.length - i) < SIG_DISTANCE
241           newstate = :sig
242         elsif line =~ BLOCK_QUOTE_PATTERN
243           newstate = :block_quote
244         end
245         if newstate
246           chunks << Text.new(chunk_lines) unless chunk_lines.empty?
247           chunk_lines = [line]
248           state = newstate
249         else
250           chunk_lines << line
251         end
252       when :quote
253         newstate = nil
254         if line =~ QUOTE_PATTERN || line =~ QUOTE_START_PATTERN || line =~ /^\s*$/
255           chunk_lines << line
256         elsif line =~ SIG_PATTERN && (lines.length - i) < SIG_DISTANCE
257           newstate = :sig
258         else
259           newstate = :text
260         end
261         if newstate
262           if chunk_lines.empty?
263             # nothing
264           elsif chunk_lines.size == 1
265             chunks << Text.new(chunk_lines) # forget about one-line quotes
266           else
267             chunks << Quote.new(chunk_lines)
268           end
269           chunk_lines = [line]
270           state = newstate
271         end
272       when :block_quote
273         chunk_lines << line
274       when :sig
275         chunk_lines << line
276       end
277  
278       if state == :text && (@snippet.nil? || @snippet.length < SNIPPET_LEN) &&
279           line !~ /[=\*#_-]{3,}/ && line !~ /^\s*$/
280         @snippet = (@snippet ? @snippet + " " : "") + line.gsub(/^\s+/, "").gsub(/[\r\n]/, "").gsub(/\s+/, " ")
281         @snippet = @snippet[0 ... SNIPPET_LEN]
282       end
283 #      if @snippet.nil? && state == :text && (line.length > 40 ||
284 #                                             line =~ /\S+.*[^,!:]\s*$/)
285 #        @snippet = line.gsub(/^\s+/, "").gsub(/[\r\n]/, "")[0 .. 80]
286 #      end
287     end
288
289     ## final object
290     case state
291     when :quote, :block_quote
292       chunks << Quote.new(chunk_lines) unless chunk_lines.empty?
293     when :text
294       chunks << Text.new(chunk_lines) unless chunk_lines.empty?
295     when :sig
296       chunks << Signature.new(chunk_lines) unless chunk_lines.empty?
297     end
298     chunks
299   end
300 end
301
302 end