6 class MessageFormatError < StandardError; end
8 ## a Message is what's threaded.
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?)
16 ## TODO: integrate with user's addressbook to render names
20 WRAP_LEN = 80 # wrap at this width
21 RE_PATTERN = /^((re|re[\[\(]\d[\]\)]):\s*)+/i
23 ## some utility methods
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
31 attr_reader :content_type, :desc, :filename
32 def initialize content_type, desc, part
33 @content_type = content_type
37 desc =~ /filename="(.*?)"/ && @filename = $1
42 @file = Tempfile.new "redwood.attachment"
47 ## TODO: handle unknown mime-types
48 system "/usr/bin/run-mailcap --action=view #{@content_type}:#{@file.path}"
51 def to_s; @part.decode; end
58 @lines = lines.map { |l| l.chomp.wrap WRAP_LEN }.flatten
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)"
84 attr_reader :id, :date, :from, :subj, :refs, :replytos, :to, :source,
85 :cc, :bcc, :labels, :list_address, :recipient_email, :replyto,
88 bool_reader :dirty, :source_marked_read
90 ## if you specify a :header, will use values from that. otherwise, will try and
91 ## load the header from the source.
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] || []
100 read_header(opts[:header] || @source.load_header(@source_info))
103 def read_header header
104 header.each { |k, v| header[k.downcase] = v }
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]
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}"
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"]
128 if header["list-post"]
129 @list_address = Person.for header["list-post"].gsub(/^<mailto:|>$/, "")
134 @recipient_email = header["envelope-to"] || header["x-original-to"] || header["delivered-to"]
135 @source_marked_read = header["status"] == "RO"
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
144 raise "not a draft" unless is_draft?
145 @source.fn_for_offset @source_info
150 index.update_message self if @dirty
154 def has_label? t; @labels.member? t; end
156 return if @labels.member? t
161 return unless @labels.member? t
175 ## this is called when the message body needs to actually be loaded.
179 [Text.new(error_message(@source.broken_msg.split("\n")))]
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
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))]
196 def error_message msg
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 ***********************************************************************
205 The error message was:
212 @source.raw_header @source_info
213 rescue SourceError => e
214 error_message e.message
220 @source.raw_full_message @source_info
221 rescue SourceError => e
222 error_message(e.message)
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 " "
238 chunks.find_all { |c| c.is_a?(Text) || c.is_a?(Quote) }.map { |c| c.lines }.flatten
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}",
252 ## everything RubyMail-specific goes here.
253 def message_to_chunks m
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")
262 disp = m.header["Content-Disposition"] || ""
263 Attachment.new m.header.content_type, disp.gsub(/[\s\n]+/, " "), m
266 m.each_part { |p| ret << message_to_chunks(p) } if m.multipart?
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
278 lines.each_with_index do |line, i|
279 nextline = lines[(i + 1) ... lines.length].find { |l| l !~ /^\s*$/ } # skip blank lines
285 if line =~ QUOTE_PATTERN || (line =~ QUOTE_START_PATTERN && (nextline =~ QUOTE_PATTERN || nextline =~ QUOTE_START_PATTERN))
287 elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
289 elsif line =~ BLOCK_QUOTE_PATTERN
290 newstate = :block_quote
294 chunks << Text.new(chunk_lines) unless chunk_lines.empty?
304 if line =~ QUOTE_PATTERN || line =~ QUOTE_START_PATTERN || line =~ /^\s*$/
306 elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
313 if chunk_lines.empty?
315 elsif chunk_lines.size == 1
316 chunks << Text.new(chunk_lines) # forget about one-line quotes
318 chunks << Quote.new(chunk_lines)
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
340 when :quote, :block_quote
341 chunks << Quote.new(chunk_lines) unless chunk_lines.empty?
343 chunks << Text.new(chunk_lines) unless chunk_lines.empty?
345 chunks << Signature.new(chunk_lines) unless chunk_lines.empty?