]> git.cworth.org Git - sup/blob - lib/sup/message.rb
27fbfa93d733af20849d81cebc983f96579869c3
[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   WRAP_LEN = 80 # wrap at this width
21   RE_PATTERN = /^((re|re[\[\(]\d[\]\)]):\s*)+/i
22     
23   ## some utility methods
24   class << self
25     def normalize_subj s; s.gsub(RE_PATTERN, ""); end
26     def subj_is_reply? s; s =~ RE_PATTERN; end
27     def reify_subj s; subj_is_reply?(s) ? s : "Re: " + s; end
28   end
29
30   class Attachment
31     attr_reader :content_type, :desc, :filename
32     def initialize content_type, desc, part
33       @content_type = content_type
34       @desc = desc
35       @part = part
36       @file = nil
37       desc =~ /filename="(.*?)"/ && @filename = $1
38     end
39
40     def view!
41       unless @file
42         @file = Tempfile.new "redwood.attachment"
43         @file.print self
44         @file.close
45       end
46
47       ## TODO: handle unknown mime-types
48       system "/usr/bin/run-mailcap --action=view #{@content_type}:#{@file.path}"
49     end
50
51     def to_s; @part.decode; end
52   end
53
54   class Text
55     attr_reader :lines
56     def initialize lines
57       ## do some wrapping
58       @lines = lines.map { |l| l.chomp.wrap WRAP_LEN }.flatten
59     end
60   end
61
62   class Quote
63     attr_reader :lines
64     def initialize lines
65       @lines = lines
66     end
67   end
68
69   class Signature
70     attr_reader :lines
71     def initialize lines
72       @lines = lines
73     end
74   end
75
76   QUOTE_PATTERN = /^\s{0,4}[>|\}]/
77   BLOCK_QUOTE_PATTERN = /^-----\s*Original Message\s*----+$/
78   QUOTE_START_PATTERN = /(^\s*Excerpts from)|(^\s*In message )|(^\s*In article )|(^\s*Quoting )|((wrote|writes|said|says)\s*:\s*$)/
79   SIG_PATTERN = /(^-- ?$)|(^\s*----------+\s*$)|(^\s*_________+\s*$)/
80   MAX_SIG_DISTANCE = 15 # lines from the end
81   DEFAULT_SUBJECT = "(missing subject)"
82   DEFAULT_SENDER = "(missing sender)"
83
84   attr_reader :id, :date, :from, :subj, :refs, :replytos, :to, :source,
85               :cc, :bcc, :labels, :list_address, :recipient_email, :replyto,
86               :source_info
87
88   bool_reader :dirty, :source_marked_read
89
90   ## if you specify a :header, will use values from that. otherwise, will try and
91   ## load the header from the source.
92   def initialize opts
93     @source = opts[:source] or raise ArgumentError, "source can't be nil"
94     @source_info = opts[:source_info] or raise ArgumentError, "source_info can't be nil"
95     @snippet = opts[:snippet] || ""
96     @have_snippet = !opts[:snippet].nil?
97     @labels = opts[:labels] || []
98     @dirty = false
99
100     read_header(opts[:header] || @source.load_header(@source_info))
101   end
102
103   def read_header header
104     header.each { |k, v| header[k.downcase] = v }
105
106     %w(message-id date).each do |f|
107       raise MessageFormatError, "no #{f} field in header #{header.inspect} (source #@source offset #@source_info)" unless header.include? f
108       raise MessageFormatError, "nil #{f} field in header #{header.inspect} (source #@source offset #@source_info)" unless header[f]
109     end
110
111     begin
112       date = header["date"]
113       @date = Time === date ? date : Time.parse(header["date"])
114     rescue ArgumentError => e
115       raise MessageFormatError, "unparsable date #{header['date']}: #{e.message}"
116     end
117
118     @subj = header.member?("subject") ? header["subject"].gsub(/\s+/, " ").gsub(/\s+$/, "") : DEFAULT_SUBJECT
119     @from = Person.for header["from"]
120     @to = Person.for_several header["to"]
121     @cc = Person.for_several header["cc"]
122     @bcc = Person.for_several header["bcc"]
123     @id = header["message-id"]
124     @refs = (header["references"] || "").gsub(/[<>]/, "").split(/\s+/).flatten
125     @replytos = (header["in-reply-to"] || "").scan(/<(.*?)>/).flatten
126     @replyto = Person.for header["reply-to"]
127     @list_address =
128       if header["list-post"]
129         @list_address = Person.for header["list-post"].gsub(/^<mailto:|>$/, "")
130       else
131         nil
132       end
133
134     @recipient_email = header["envelope-to"] || header["x-original-to"] || header["delivered-to"]
135     @source_marked_read = header["status"] == "RO"
136   end
137   private :read_header
138
139   def broken?; @source.broken?; end
140   def snippet; @snippet || chunks && @snippet; end
141   def is_list_message?; !@list_address.nil?; end
142   def is_draft?; DraftLoader === @source; end
143   def draft_filename
144     raise "not a draft" unless is_draft?
145     @source.fn_for_offset @source_info
146   end
147
148   def save index
149     return if broken?
150     index.update_message self if @dirty
151     @dirty = false
152   end
153
154   def has_label? t; @labels.member? t; end
155   def add_label t
156     return if @labels.member? t
157     @labels.push t
158     @dirty = true
159   end
160   def remove_label t
161     return unless @labels.member? t
162     @labels.delete t
163     @dirty = true
164   end
165
166   def recipients
167     @to + @cc + @bcc
168   end
169
170   def labels= l
171     @labels = l
172     @dirty = true
173   end
174
175   ## this is called when the message body needs to actually be loaded.
176   def chunks
177     @chunks ||=
178       if @source.broken?
179         [Text.new(error_message(@source.broken_msg.split("\n")))]
180       else
181         begin
182           ## we need to re-read the header because it contains information
183           ## that we don't store in the index. actually i think it's just
184           ## the mailing list address (if any), so this is kinda overkill.
185           ## i could just store that in the index, but i think there might
186           ## be other things like that in the future, and i'd rather not
187           ## bloat the index.
188           read_header @source.load_header(@source_info)
189           message_to_chunks @source.load_message(@source_info)
190         rescue SourceError, SocketError, MessageFormatError => e
191           [Text.new(error_message(e.message))]
192         end
193       end
194   end
195
196   def error_message msg
197     <<EOS
198 #@snippet...
199
200 ***********************************************************************
201 * An error occurred while loading this message. It is possible that   *
202 * the source has changed, or (in the case of remote sources) is down. *
203 ***********************************************************************
204
205 The error message was:
206   #{msg}
207 EOS
208   end
209
210   def raw_header
211     begin
212       @source.raw_header @source_info
213     rescue SourceError => e
214       error_message e.message
215     end
216   end
217
218   def raw_full_message
219     begin
220       @source.raw_full_message @source_info
221     rescue SourceError => e
222       error_message(e.message)
223     end
224   end
225
226   def content
227     [
228       from && "#{from.name} #{from.email}",
229       to.map { |p| "#{p.name} #{p.email}" },
230       cc.map { |p| "#{p.name} #{p.email}" },
231       bcc.map { |p| "#{p.name} #{p.email}" },
232       chunks.select { |c| c.is_a? Text }.map { |c| c.lines },
233       Message.normalize_subj(subj),
234     ].flatten.compact.join " "
235   end
236
237   def basic_body_lines
238     chunks.find_all { |c| c.is_a?(Text) || c.is_a?(Quote) }.map { |c| c.lines }.flatten
239   end
240
241   def basic_header_lines
242     ["From: #{@from.full_address}"] +
243       (@to.empty? ? [] : ["To: " + @to.map { |p| p.full_address }.join(", ")]) +
244       (@cc.empty? ? [] : ["Cc: " + @cc.map { |p| p.full_address }.join(", ")]) +
245       (@bcc.empty? ? [] : ["Bcc: " + @bcc.map { |p| p.full_address }.join(", ")]) +
246       ["Date: #{@date.rfc822}",
247        "Subject: #{@subj}"]
248   end
249
250 private
251
252   ## everything RubyMail-specific goes here.
253   def message_to_chunks m
254     ret = [] <<
255       case m.header.content_type
256       when "text/plain", nil
257         m.body && body = m.decode or raise MessageFormatError, "for some bizarre reason, RubyMail was unable to parse this message."
258         text_to_chunks body.normalize_whitespace.split("\n")
259       when /^multipart\//
260         nil
261       else
262         disp = m.header["Content-Disposition"] || ""
263         Attachment.new m.header.content_type, disp.gsub(/[\s\n]+/, " "), m
264       end
265     
266     m.each_part { |p| ret << message_to_chunks(p) } if m.multipart?
267     ret.compact.flatten
268   end
269
270   ## parse the lines of text into chunk objects.  the heuristics here
271   ## need tweaking in some nice manner. TODO: move these heuristics
272   ## into the classes themselves.
273   def text_to_chunks lines
274     state = :text # one of :text, :quote, or :sig
275     chunks = []
276     chunk_lines = []
277
278     lines.each_with_index do |line, i|
279       nextline = lines[(i + 1) ... lines.length].find { |l| l !~ /^\s*$/ } # skip blank lines
280
281       case state
282       when :text
283         newstate = nil
284
285         if line =~ QUOTE_PATTERN || (line =~ QUOTE_START_PATTERN && (nextline =~ QUOTE_PATTERN || nextline =~ QUOTE_START_PATTERN))
286           newstate = :quote
287         elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
288           newstate = :sig
289         elsif line =~ BLOCK_QUOTE_PATTERN
290           newstate = :block_quote
291         end
292
293         if newstate
294           chunks << Text.new(chunk_lines) unless chunk_lines.empty?
295           chunk_lines = [line]
296           state = newstate
297         else
298           chunk_lines << line
299         end
300
301       when :quote
302         newstate = nil
303
304         if line =~ QUOTE_PATTERN || line =~ QUOTE_START_PATTERN || line =~ /^\s*$/
305           chunk_lines << line
306         elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
307           newstate = :sig
308         else
309           newstate = :text
310         end
311
312         if newstate
313           if chunk_lines.empty?
314             # nothing
315           elsif chunk_lines.size == 1
316             chunks << Text.new(chunk_lines) # forget about one-line quotes
317           else
318             chunks << Quote.new(chunk_lines)
319           end
320           chunk_lines = [line]
321           state = newstate
322         end
323
324       when :block_quote
325         chunk_lines << line
326
327       when :sig
328         chunk_lines << line
329       end
330  
331       if !@have_snippet && state == :text && (@snippet.nil? || @snippet.length < SNIPPET_LEN) && line !~ /[=\*#_-]{3,}/ && line !~ /^\s*$/
332         @snippet += " " unless @snippet.empty?
333         @snippet += line.gsub(/^\s+/, "").gsub(/[\r\n]/, "").gsub(/\s+/, " ")
334         @snippet = @snippet[0 ... SNIPPET_LEN].chomp
335       end
336     end
337
338     ## final object
339     case state
340     when :quote, :block_quote
341       chunks << Quote.new(chunk_lines) unless chunk_lines.empty?
342     when :text
343       chunks << Text.new(chunk_lines) unless chunk_lines.empty?
344     when :sig
345       chunks << Signature.new(chunk_lines) unless chunk_lines.empty?
346     end
347     chunks
348   end
349 end
350
351 end