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 RE_PATTERN = /^((re|re[\[\(]\d[\]\)]):\s*)+/i
22 ## some utility methods
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
30 attr_reader :content_type, :desc, :filename
31 def initialize content_type, desc, part
32 @content_type = content_type
36 desc =~ /filename="(.*?)"/ && @filename = $1
41 @file = Tempfile.new "redwood.attachment"
46 ## TODO: handle unknown mime-types
47 system "/usr/bin/run-mailcap --action=view #{@content_type}:#{@file.path}"
50 def to_s; @part.decode; end
57 @lines = lines.map { |l| l.wrap 80 }.flatten
75 QUOTE_PATTERN = /^\s{0,4}[>|\}]/
76 BLOCK_QUOTE_PATTERN = /^-----\s*Original Message\s*----+$/
77 QUOTE_START_PATTERN = /(^\s*Excerpts from)|(^\s*In message )|(^\s*In article )|(^\s*Quoting )|((wrote|writes|said|says)\s*:\s*$)/
78 SIG_PATTERN = /(^-- ?$)|(^\s*----------+\s*$)|(^\s*_________+\s*$)/
79 MAX_SIG_DISTANCE = 15 # lines from the end
80 DEFAULT_SUBJECT = "(missing subject)"
81 DEFAULT_SENDER = "(missing sender)"
83 attr_reader :id, :date, :from, :subj, :refs, :replytos, :to, :source,
84 :cc, :bcc, :labels, :list_address, :recipient_email, :replyto,
89 ## if index_entry is specified, will fill in values from that,
92 @source = opts[:source]
93 @source_info = opts[:source_info] or raise ArgumentError, ":source but no :source_info"
96 @source = @source_info = nil
97 @body = opts[:body] or raise ArgumentError, "one of :body or :source must be specified"
99 @snippet = opts[:snippet] || ""
100 @labels = opts[:labels] || []
107 header = @source.load_header @source_info
108 header.each { |k, v| header[k.downcase] = v }
112 %w(message-id date).each do |f|
113 raise MessageFormatError, "no #{f} field in header #{header.inspect} (source #@source offset #@source_info)" unless header.include? f
114 raise MessageFormatError, "nil #{f} field in header #{header.inspect} (source #@source offset #@source_info)" unless header[f]
118 date = header["date"]
119 @date = (Time === date ? date : Time.parse(header["date"]))
120 rescue ArgumentError => e
121 raise MessageFormatError, "unparsable date #{header['date']}: #{e.message}"
124 if(@subj = header["subject"])
125 @subj = @subj.gsub(/\s+/, " ").gsub(/\s+$/, "")
127 @subj = DEFAULT_SUBJECT
129 @from = Person.for header["from"]
130 @to = Person.for_several header["to"]
131 @cc = Person.for_several header["cc"]
132 @bcc = Person.for_several header["bcc"]
133 @id = header["message-id"]
134 @refs = (header["references"] || "").scan(/<(.*?)>/).flatten
135 @replytos = (header["in-reply-to"] || "").scan(/<(.*?)>/).flatten
136 @replyto = Person.for header["reply-to"]
138 if header["list-post"]
139 @list_address = Person.for header["list-post"].gsub(/^<mailto:|>$/, "")
144 @recipient_email = header["delivered-to"]
145 @status = header["status"]
148 def broken?; @source.nil?; end
149 def snippet; @snippet || to_chunks && @snippet; end
150 def is_list_message?; !@list_address.nil?; end
151 def is_draft?; DraftLoader === @source; end
153 raise "not a draft" unless is_draft?
154 @source.fn_for_offset @source_info
159 index.update_message self if @dirty
163 def has_label? t; @labels.member? t; end
165 return if @labels.member? t
170 return unless @labels.member? t
186 [Text.new(@body.split("\n"))]
188 message_to_chunks @source.load_message(@source_info)
193 @source.raw_header @source_info
197 @source.raw_full_message @source_info
202 from && "#{from.name} #{from.email}",
203 to.map { |p| "#{p.name} #{p.email}" },
204 cc.map { |p| "#{p.name} #{p.email}" },
205 bcc.map { |p| "#{p.name} #{p.email}" },
206 to_chunks.select { |c| c.is_a? Text }.map { |c| c.lines },
207 Message.normalize_subj(subj),
208 ].flatten.compact.join " "
212 to_chunks.find_all { |c| c.is_a?(Text) || c.is_a?(Quote) }.map { |c| c.lines }.flatten
215 def basic_header_lines
216 ["From: #{@from.full_address}"] +
217 (@to.empty? ? [] : ["To: " + @to.map { |p| p.full_address }.join(", ")]) +
218 (@cc.empty? ? [] : ["Cc: " + @cc.map { |p| p.full_address }.join(", ")]) +
219 (@bcc.empty? ? [] : ["Bcc: " + @bcc.map { |p| p.full_address }.join(", ")]) +
220 ["Date: #{@date.rfc822}",
226 ## everything RubyMail-specific goes here.
227 def message_to_chunks m
229 case m.header.content_type
230 when "text/plain", nil
231 raise MessageFormatError, "no message body before decode" unless
233 body = m.decode or raise MessageFormatError, "no message body"
234 text_to_chunks body.gsub(/\t/, " ").gsub(/\r/, "").split("\n")
238 disp = m.header["Content-Disposition"] || ""
239 Attachment.new m.header.content_type, disp.gsub(/[\s\n]+/, " "), m
242 m.each_part { |p| ret << message_to_chunks(p) } if m.multipart?
246 ## parse the lines of text into chunk objects. the heuristics here
247 ## need tweaking in some nice manner. TODO: move these heuristics
248 ## into the classes themselves.
250 def text_to_chunks lines
251 state = :text # one of :text, :quote, or :sig
255 lines.each_with_index do |line, i|
256 nextline = lines[(i + 1) ... lines.length].find { |l| l !~ /^\s*$/ } # skip blank lines
260 if line =~ QUOTE_PATTERN || (line =~ QUOTE_START_PATTERN && (nextline =~ QUOTE_PATTERN || nextline =~ QUOTE_START_PATTERN))
262 elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
264 elsif line =~ BLOCK_QUOTE_PATTERN
265 newstate = :block_quote
268 chunks << Text.new(chunk_lines) unless chunk_lines.empty?
276 if line =~ QUOTE_PATTERN || line =~ QUOTE_START_PATTERN || line =~ /^\s*$/
278 elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
284 if chunk_lines.empty?
286 elsif chunk_lines.size == 1
287 chunks << Text.new(chunk_lines) # forget about one-line quotes
289 chunks << Quote.new(chunk_lines)
300 if state == :text && (@snippet.nil? || @snippet.length < SNIPPET_LEN) &&
301 line !~ /[=\*#_-]{3,}/ && line !~ /^\s*$/
302 @snippet += " " unless @snippet.empty?
303 @snippet += line.gsub(/^\s+/, "").gsub(/[\r\n]/, "").gsub(/\s+/, " ")
304 @snippet = @snippet[0 ... SNIPPET_LEN]
310 when :quote, :block_quote
311 chunks << Quote.new(chunk_lines) unless chunk_lines.empty?
313 chunks << Text.new(chunk_lines) unless chunk_lines.empty?
315 chunks << Signature.new(chunk_lines) unless chunk_lines.empty?