lib/sup/message.rb (26778B) - raw
1 # encoding: UTF-8
2
3 require 'time'
4 require 'string-scrub' if /^2\.0\./ =~ RUBY_VERSION
5
6 module Redwood
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 class Message
17 SNIPPET_LEN = 80
18 RE_PATTERN = /^((re|re[\[\(]\d[\]\)]):\s*)+/i
19
20 ## some utility methods
21 class << self
22 def normalize_subj s; s.gsub(RE_PATTERN, ""); end
23 def subj_is_reply? s; s =~ RE_PATTERN; end
24 def reify_subj s; subj_is_reply?(s) ? s : "Re: " + s; end
25 end
26
27 QUOTE_PATTERN = /^\s{0,4}[>|\}]/
28 BLOCK_QUOTE_PATTERN = /^-----\s*Original Message\s*----+$/
29 SIG_PATTERN = /(^(- )*-- ?$)|(^\s*----------+\s*$)|(^\s*_________+\s*$)|(^\s*--~--~-)|(^\s*--\+\+\*\*==)/
30
31 GPG_SIGNED_START = "-----BEGIN PGP SIGNED MESSAGE-----"
32 GPG_SIGNED_END = "-----END PGP SIGNED MESSAGE-----"
33 GPG_START = "-----BEGIN PGP MESSAGE-----"
34 GPG_END = "-----END PGP MESSAGE-----"
35 GPG_SIG_START = "-----BEGIN PGP SIGNATURE-----"
36 GPG_SIG_END = "-----END PGP SIGNATURE-----"
37
38 MAX_SIG_DISTANCE = 15 # lines from the end
39 DEFAULT_SUBJECT = ""
40 DEFAULT_SENDER = "(missing sender)"
41 MAX_HEADER_VALUE_SIZE = 4096
42
43 attr_reader :id, :date, :from, :subj, :refs, :replytos, :to,
44 :cc, :bcc, :labels, :attachments, :list_address, :recipient_email, :replyto,
45 :list_subscribe, :list_unsubscribe
46
47 bool_reader :dirty, :source_marked_read, :snippet_contains_encrypted_content
48
49 attr_accessor :locations
50
51 ## if you specify a :header, will use values from that. otherwise,
52 ## will try and load the header from the source.
53 def initialize opts
54 @locations = opts[:locations] or raise ArgumentError, "locations can't be nil"
55 @snippet = opts[:snippet]
56 @snippet_contains_encrypted_content = false
57 @have_snippet = !(opts[:snippet].nil? || opts[:snippet].empty?)
58 @labels = Set.new(opts[:labels] || [])
59 @dirty = false
60 @encrypted = false
61 @chunks = nil
62 @attachments = []
63
64 ## we need to initialize this. see comments in parse_header as to
65 ## why.
66 @refs = []
67
68 #parse_header(opts[:header] || @source.load_header(@source_info))
69 end
70
71 def decode_header_field v
72 return unless v
73 return v unless v.is_a? String
74 return unless v.size < MAX_HEADER_VALUE_SIZE # avoid regex blowup on spam
75 ## Header values should be either 7-bit with RFC2047-encoded words
76 ## or UTF-8 as per RFC6532. Replace any invalid high bytes with U+FFFD.
77 Rfc2047.decode_to $encoding, v.dup.force_encoding(Encoding::UTF_8).scrub
78 end
79
80 def parse_header encoded_header
81 header = SavingHash.new { |k| decode_header_field encoded_header[k] }
82
83 @id = ''
84 if header["message-id"]
85 mid = header["message-id"] =~ /<(.+?)>/ ? $1 : header["message-id"]
86 @id = sanitize_message_id mid
87 end
88 if (not @id.include? '@') || @id.length < 6
89 @id = "sup-faked-" + Digest::MD5.hexdigest(raw_header)
90 #from = header["from"]
91 #debug "faking non-existent message-id for message from #{from}: #{id}"
92 end
93
94 @from = Person.from_address(if header["from"]
95 header["from"]
96 else
97 name = "Sup Auto-generated Fake Sender <sup@fake.sender.example.com>"
98 #debug "faking non-existent sender for message #@id: #{name}"
99 name
100 end)
101
102 @date = case(date = header["date"])
103 when Time
104 date
105 when String
106 Time.rfc2822 date rescue nil
107 end
108 @date = location.fallback_date if @date.nil?
109 @date = Time.utc 1970, 1, 1 if @date.nil?
110
111 subj = header["subject"]
112 subj = subj ? subj.fix_encoding! : nil
113 @subj = subj ? subj.gsub(/\s+/, " ").gsub(/\s+$/, "") : DEFAULT_SUBJECT
114 @to = Person.from_address_list header["to"]
115 @cc = Person.from_address_list header["cc"]
116 @bcc = Person.from_address_list header["bcc"]
117
118 ## before loading our full header from the source, we can actually
119 ## have some extra refs set by the UI. (this happens when the user
120 ## joins threads manually). so we will merge the current refs values
121 ## in here.
122 refs = (header["references"] || "").scan(/<(.+?)>/).map { |x| sanitize_message_id x.first }
123 @refs = (@refs + refs).uniq
124 @replytos = (header["in-reply-to"] || "").scan(/<(.+?)>/).map { |x| sanitize_message_id x.first }
125
126 @replyto = Person.from_address header["reply-to"]
127 @list_address = if header["list-post"]
128 address = if header["list-post"] =~ /mailto:(.*?)[>\s$]/
129 $1
130 elsif header["list-post"] =~ /@/
131 header["list-post"] # just try the whole fucking thing
132 end
133 address && Person.from_address(address)
134 elsif header["mailing-list"]
135 address = if header["mailing-list"] =~ /list (.*?);/
136 $1
137 end
138 address && Person.from_address(address)
139 elsif header["x-mailing-list"]
140 Person.from_address header["x-mailing-list"]
141 end
142
143 @recipient_email = header["envelope-to"] || header["x-original-to"] || header["delivered-to"]
144 @source_marked_read = header["status"] == "RO"
145 @list_subscribe = header["list-subscribe"]
146 @list_unsubscribe = header["list-unsubscribe"]
147 end
148
149 ## Expected index entry format:
150 ## :message_id, :subject => String
151 ## :date => Time
152 ## :refs, :replytos => Array of String
153 ## :from => Person
154 ## :to, :cc, :bcc => Array of Person
155 def load_from_index! entry
156 @id = entry[:message_id]
157 @from = entry[:from]
158 @date = entry[:date]
159 @subj = entry[:subject]
160 @to = entry[:to]
161 @cc = entry[:cc]
162 @bcc = entry[:bcc]
163 @refs = (@refs + entry[:refs]).uniq
164 @replytos = entry[:replytos]
165
166 @replyto = nil
167 @list_address = nil
168 @recipient_email = nil
169 @source_marked_read = false
170 @list_subscribe = nil
171 @list_unsubscribe = nil
172 end
173
174 def add_ref ref
175 @refs << ref
176 @dirty = true
177 end
178
179 def remove_ref ref
180 @dirty = true if @refs.delete ref
181 end
182
183 attr_reader :snippet
184 def is_list_message?; !@list_address.nil?; end
185 def is_draft?; @labels.member? :draft; end
186 def draft_filename
187 raise "not a draft" unless is_draft?
188 source.fn_for_offset source_info
189 end
190
191 ## sanitize message ids by removing spaces and non-ascii characters.
192 ## also, truncate to 255 characters. all these steps are necessary
193 ## to make the index happy. of course, we probably fuck up a couple
194 ## valid message ids as well. as long as we're consistent, this
195 ## should be fine, though.
196 ##
197 ## also, mostly the message ids that are changed by this belong to
198 ## spam email.
199 ##
200 ## an alternative would be to SHA1 or MD5 all message ids on a regular basis.
201 ## don't tempt me.
202 def sanitize_message_id mid; mid.gsub(/(\s|[^\000-\177])+/, "")[0..254] end
203
204 def clear_dirty
205 @dirty = false
206 end
207
208 def has_label? t; @labels.member? t; end
209 def add_label l
210 l = l.to_sym
211 return if @labels.member? l
212 @labels << l
213 @dirty = true
214 end
215 def remove_label l
216 l = l.to_sym
217 return unless @labels.member? l
218 @labels.delete l
219 @dirty = true
220 end
221
222 def recipients
223 @to + @cc + @bcc
224 end
225
226 def labels= l
227 raise ArgumentError, "not a set" unless l.is_a?(Set)
228 raise ArgumentError, "not a set of labels" unless l.all? { |ll| ll.is_a?(Symbol) }
229 return if @labels == l
230 @labels = l
231 @dirty = true
232 end
233
234 def chunks
235 load_from_source!
236 @chunks
237 end
238
239 def location
240 @locations.find { |x| x.valid? } || raise(OutOfSyncSourceError.new)
241 end
242
243 def source
244 location.source
245 end
246
247 def source_info
248 location.info
249 end
250
251 ## this is called when the message body needs to actually be loaded.
252 def load_from_source!
253 @chunks ||=
254 begin
255 ## we need to re-read the header because it contains information
256 ## that we don't store in the index. actually i think it's just
257 ## the mailing list address (if any), so this is kinda overkill.
258 ## i could just store that in the index, but i think there might
259 ## be other things like that in the future, and i'd rather not
260 ## bloat the index.
261 ## actually, it's also the differentiation between to/cc/bcc,
262 ## so i will keep this.
263 rmsg = location.parsed_message
264 parse_header rmsg.header
265 message_to_chunks rmsg
266 rescue SourceError, SocketError, RMail::EncodingUnsupportedError => e
267 warn_with_location "problem reading message #{id}"
268 debug "could not load message, exception: #{e.inspect}"
269
270 [Chunk::Text.new(error_message.split("\n"))]
271
272 rescue Exception => e
273
274 warn_with_location "problem reading message #{id}"
275 debug "could not load message: #{location.inspect}, exception: #{e.inspect}"
276
277 raise e
278
279 end
280 end
281
282 def reload_from_source!
283 @chunks = nil
284 load_from_source!
285 end
286
287
288 def error_message
289 <<EOS
290 #@snippet...
291
292 ***********************************************************************
293 An error occurred while loading this message.
294 ***********************************************************************
295 EOS
296 end
297
298 def raw_header
299 location.raw_header
300 end
301
302 def raw_message
303 location.raw_message
304 end
305
306 def each_raw_message_line &b
307 location.each_raw_message_line(&b)
308 end
309
310 def sync_back
311 @locations.map { |l| l.sync_back @labels, self }.any? do
312 UpdateManager.relay self, :updated, self
313 end
314 end
315
316 def merge_labels_from_locations merge_labels
317 ## Get all labels from all locations
318 location_labels = Set.new([])
319
320 @locations.each do |l|
321 if l.valid?
322 location_labels = location_labels.union(l.labels?)
323 end
324 end
325
326 ## Add to the message labels the intersection between all location
327 ## labels and those we want to merge
328 location_labels = location_labels.intersection(merge_labels.to_set)
329
330 if not location_labels.empty?
331 @labels = @labels.union(location_labels)
332 @dirty = true
333 end
334 end
335
336 def indexable_body
337 indexable_chunks.map { |c| c.lines }.flatten.compact.join " "
338 end
339
340 def indexable_chunks
341 chunks.select { |c| c.indexable? } || []
342 end
343
344 def indexable_subject
345 Message.normalize_subj(subj)
346 end
347
348 def quotable_body_lines
349 chunks.find_all { |c| c.quotable? }.map { |c| c.lines }.flatten
350 end
351
352 def quotable_header_lines
353 ["From: #{@from.full_address}"] +
354 (@to.empty? ? [] : ["To: " + @to.map { |p| p.full_address }.join(", ")]) +
355 (@cc.empty? ? [] : ["Cc: " + @cc.map { |p| p.full_address }.join(", ")]) +
356 (@bcc.empty? ? [] : ["Bcc: " + @bcc.map { |p| p.full_address }.join(", ")]) +
357 ["Date: #{@date.rfc822}",
358 "Subject: #{@subj}"]
359 end
360
361 def self.build_from_source source, source_info
362 m = Message.new :locations => [Location.new(source, source_info)]
363 m.load_from_source!
364 m
365 end
366
367 private
368
369 ## here's where we handle decoding mime attachments. unfortunately
370 ## but unsurprisingly, the world of mime attachments is a bit of a
371 ## mess. as an empiricist, i'm basing the following behavior on
372 ## observed mail rather than on interpretations of rfcs, so probably
373 ## this will have to be tweaked.
374 ##
375 ## the general behavior i want is: ignore content-disposition, at
376 ## least in so far as it suggests something being inline vs being an
377 ## attachment. (because really, that should be the recipient's
378 ## decision to make.) if a mime part is text/plain, OR if the user
379 ## decoding hook converts it, then decode it and display it
380 ## inline. for these decoded attachments, if it has associated
381 ## filename, then make it collapsable and individually saveable;
382 ## otherwise, treat it as regular body text.
383 ##
384 ## everything else is just an attachment and is not displayed
385 ## inline.
386 ##
387 ## so, in contrast to mutt, the user is not exposed to the workings
388 ## of the gruesome slaughterhouse and sausage factory that is a
389 ## mime-encoded message, but need only see the delicious end
390 ## product.
391
392 def multipart_signed_to_chunks m
393 if m.body.size != 2
394 warn_with_location "multipart/signed with #{m.body.size} parts (expecting 2)"
395 return
396 end
397
398 payload, signature = m.body
399 if signature.multipart?
400 warn_with_location "multipart/signed with payload multipart #{payload.multipart?} and signature multipart #{signature.multipart?}"
401 return
402 end
403
404 ## this probably will never happen
405 if payload.header.content_type && payload.header.content_type.downcase == "application/pgp-signature"
406 warn_with_location "multipart/signed with payload content type #{payload.header.content_type}"
407 return
408 end
409
410 if signature.header.content_type && signature.header.content_type.downcase != "application/pgp-signature"
411 ## unknown signature type; just ignore.
412 #warn "multipart/signed with signature content type #{signature.header.content_type}"
413 return
414 end
415
416 [CryptoManager.verify(payload, signature), message_to_chunks(payload)].flatten.compact
417 end
418
419 def multipart_encrypted_to_chunks m
420 if m.body.size != 2
421 warn_with_location "multipart/encrypted with #{m.body.size} parts (expecting 2)"
422 return
423 end
424
425 control, payload = m.body
426 if control.multipart?
427 warn_with_location "multipart/encrypted with control multipart #{control.multipart?} and payload multipart #{payload.multipart?}"
428 return
429 end
430
431 if payload.header.content_type && payload.header.content_type.downcase != "application/octet-stream"
432 warn_with_location "multipart/encrypted with payload content type #{payload.header.content_type}"
433 return
434 end
435
436 if control.header.content_type && control.header.content_type.downcase != "application/pgp-encrypted"
437 warn_with_location "multipart/encrypted with control content type #{signature.header.content_type}"
438 return
439 end
440
441 notice, sig, decryptedm = CryptoManager.decrypt payload
442 if decryptedm # managed to decrypt
443 children = message_to_chunks(decryptedm, true)
444 [notice, sig].compact + children
445 else
446 [notice]
447 end
448 end
449
450 def has_embedded_message? m
451 return false unless m.header.content_type
452 %w(message/rfc822 message/global).include? m.header.content_type.downcase
453 end
454
455 ## takes a RMail::Message, breaks it into Chunk:: classes.
456 def message_to_chunks m, encrypted=false, sibling_types=[]
457 if m.multipart?
458 chunks =
459 case m.header.content_type.downcase
460 when "multipart/signed"
461 multipart_signed_to_chunks m
462 when "multipart/encrypted"
463 multipart_encrypted_to_chunks m
464 end
465
466 unless chunks
467 sibling_types = m.body.map { |p| p.header.content_type }
468 chunks = m.body.map { |p| message_to_chunks p, encrypted, sibling_types }.flatten.compact
469 end
470
471 chunks
472 elsif has_embedded_message? m
473 encoding = m.header["Content-Transfer-Encoding"]
474 if m.body
475 body =
476 case encoding
477 when "base64"
478 m.body.unpack("m")[0]
479 when "quoted-printable"
480 m.body.unpack("M")[0]
481 when "7bit", "8bit", nil
482 m.body
483 else
484 raise RMail::EncodingUnsupportedError, encoding.inspect
485 end
486 body = body.normalize_whitespace
487 payload = RMail::Parser.read(body)
488 from = payload.header.from.first ? payload.header.from.first.format : ""
489 to = payload.header.to.map { |p| p.format }.join(", ")
490 cc = payload.header.cc.map { |p| p.format }.join(", ")
491 subj = decode_header_field(payload.header.subject) || DEFAULT_SUBJECT
492 subj = Message.normalize_subj(subj.gsub(/\s+/, " ").gsub(/\s+$/, ""))
493 msgdate = payload.header.date
494 from_person = from ? Person.from_address(decode_header_field(from)) : nil
495 to_people = to ? Person.from_address_list(decode_header_field(to)) : nil
496 cc_people = cc ? Person.from_address_list(decode_header_field(cc)) : nil
497 [Chunk::EnclosedMessage.new(from_person, to_people, cc_people, msgdate, subj)] + message_to_chunks(payload, encrypted)
498 else
499 debug "no body for message/rfc822 enclosure; skipping"
500 []
501 end
502 elsif m.header.content_type && m.header.content_type.downcase == "application/pgp" && m.body
503 ## apparently some versions of Thunderbird generate encryped email that
504 ## does not follow RFC3156, e.g. messages with X-Enigmail-Version: 0.95.0
505 ## they have no MIME multipart and just set the body content type to
506 ## application/pgp. this handles that.
507 ##
508 ## TODO 1: unduplicate code between here and
509 ## multipart_encrypted_to_chunks
510 ## TODO 2: this only tries to decrypt. it cannot handle inline PGP
511 notice, sig, decryptedm = CryptoManager.decrypt m.body
512 if decryptedm # managed to decrypt
513 children = message_to_chunks decryptedm, true
514 [notice, sig].compact + children
515 else
516 ## try inline pgp signed
517 chunks = inline_gpg_to_chunks m.body, $encoding, (m.charset || $encoding)
518 if chunks
519 chunks
520 else
521 [notice]
522 end
523 end
524 else
525 filename =
526 ## first, paw through the headers looking for a filename.
527 ## RFC 2183 (Content-Disposition) specifies that disposition-parms are
528 ## separated by ";". So, we match everything up to " and ; (if present).
529 if m.header["Content-Disposition"] && m.header["Content-Disposition"] =~ /filename="?(.*?[^\\])("|;|\z)/m
530 $1
531 elsif m.header["Content-Type"] && m.header["Content-Type"] =~ /name="?(.*?[^\\])("|;|\z)/im
532 $1
533
534 ## haven't found one, but it's a non-text message. fake
535 ## it.
536 ##
537 ## TODO: make this less lame.
538 elsif m.header["Content-Type"] && m.header["Content-Type"] !~ /^text\/plain/i
539 extension =
540 case m.header["Content-Type"]
541 when /text\/html/ then "html"
542 when /image\/(.*)/ then $1
543 end
544
545 ["sup-attachment-#{Time.now.to_i}-#{rand 10000}", extension].join(".")
546 end
547
548 ## if there's a filename, we'll treat it as an attachment.
549 if filename
550 ## filename could be 2047 encoded
551 filename = Rfc2047.decode_to $encoding, filename
552 # add this to the attachments list if its not a generated html
553 # attachment (should we allow images with generated names?).
554 # Lowercase the filename because searches are easier that way
555 @attachments.push filename.downcase unless filename =~ /^sup-attachment-/
556 add_label :attachment unless filename =~ /^sup-attachment-/
557 content_type = (m.header.content_type || "application/unknown").downcase # sometimes RubyMail gives us nil
558 [Chunk::Attachment.new(content_type, filename, m, sibling_types)]
559
560 ## otherwise, it's body text
561 else
562 ## Decode the body, charset conversion will follow either in
563 ## inline_gpg_to_chunks (for inline GPG signed messages) or
564 ## a few lines below (messages without inline GPG)
565 body = m.body ? m.decode : ""
566
567 ## Check for inline-PGP
568 chunks = inline_gpg_to_chunks body, $encoding, (m.charset || $encoding)
569 return chunks if chunks
570
571 if m.body
572 ## if there's no charset, use the current encoding as the charset.
573 ## this ensures that the body is normalized to avoid non-displayable
574 ## characters
575 body = m.decode.transcode($encoding, m.charset)
576 else
577 body = ""
578 end
579
580 text_to_chunks(body.normalize_whitespace.split("\n"), encrypted)
581 end
582 end
583 end
584
585 ## looks for gpg signed (but not encrypted) inline messages inside the
586 ## message body (there is no extra header for inline GPG) or for encrypted
587 ## (and possible signed) inline GPG messages
588 def inline_gpg_to_chunks body, encoding_to, encoding_from
589 lines = body.split("\n")
590
591 # First case: Message is enclosed between
592 #
593 # -----BEGIN PGP SIGNED MESSAGE-----
594 # and
595 # -----END PGP SIGNED MESSAGE-----
596 #
597 # In some cases, END PGP SIGNED MESSAGE doesn't appear
598 # (and may leave strange -----BEGIN PGP SIGNATURE----- ?)
599 gpg = lines.between(GPG_SIGNED_START, GPG_SIGNED_END)
600 # between does not check if GPG_END actually exists
601 # Reference: http://permalink.gmane.org/gmane.mail.sup.devel/641
602 if !gpg.empty?
603 msg = RMail::Message.new
604 msg.body = gpg.join("\n")
605
606 body = body.transcode(encoding_to, encoding_from)
607 lines = body.split("\n")
608 sig = lines.between(GPG_SIGNED_START, GPG_SIG_START)
609 startidx = lines.index(GPG_SIGNED_START)
610 endidx = lines.index(GPG_SIG_END)
611 before = startidx != 0 ? lines[0 .. startidx-1] : []
612 after = endidx ? lines[endidx+1 .. lines.size] : []
613
614 # sig contains BEGIN PGP SIGNED MESSAGE and END PGP SIGNATURE, so
615 # we ditch them. sig may also contain the hash used by PGP (with a
616 # newline), so we also skip them
617 sig_start = sig[1].match(/^Hash:/) ? 3 : 1
618 sig_end = sig.size-2
619 payload = RMail::Message.new
620 payload.body = sig[sig_start, sig_end].join("\n")
621 return [text_to_chunks(before, false),
622 CryptoManager.verify(nil, msg, false),
623 message_to_chunks(payload),
624 text_to_chunks(after, false)].flatten.compact
625 end
626
627 # Second case: Message is encrypted
628
629 gpg = lines.between(GPG_START, GPG_END)
630 # between does not check if GPG_END actually exists
631 if !gpg.empty? && !lines.index(GPG_END).nil?
632 msg = RMail::Message.new
633 msg.body = gpg.join("\n")
634
635 startidx = lines.index(GPG_START)
636 before = startidx != 0 ? lines[0 .. startidx-1] : []
637 after = lines[lines.index(GPG_END)+1 .. lines.size]
638
639 notice, sig, decryptedm = CryptoManager.decrypt msg, true
640 chunks = if decryptedm # managed to decrypt
641 children = message_to_chunks(decryptedm, true)
642 [notice, sig].compact + children
643 else
644 [notice]
645 end
646 return [text_to_chunks(before, false),
647 chunks,
648 text_to_chunks(after, false)].flatten.compact
649 end
650 end
651
652 ## parse the lines of text into chunk objects. the heuristics here
653 ## need tweaking in some nice manner. TODO: move these heuristics
654 ## into the classes themselves.
655 def text_to_chunks lines, encrypted
656 state = :text # one of :text, :quote, or :sig
657 chunks = []
658 chunk_lines = []
659 nextline_index = -1
660
661 lines.each_with_index do |line, i|
662 if i >= nextline_index
663 # look for next nonblank line only when needed to avoid O(n²)
664 # behavior on sequences of blank lines
665 if nextline_index = lines[(i+1)..-1].index { |l| l !~ /^\s*$/ } # skip blank lines
666 nextline_index += i + 1
667 nextline = lines[nextline_index]
668 else
669 nextline_index = lines.length
670 nextline = nil
671 end
672 end
673
674 case state
675 when :text
676 newstate = nil
677
678 ## the following /:$/ followed by /\w/ is an attempt to detect the
679 ## start of a quote. this is split into two regexen because the
680 ## original regex /\w.*:$/ had very poor behavior on long lines
681 ## like ":a:a:a:a:a" that occurred in certain emails.
682 if line =~ QUOTE_PATTERN || (line =~ /:$/ && line =~ /\w/ && nextline =~ QUOTE_PATTERN)
683 newstate = :quote
684 elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE && !lines[(i+1)..-1].index { |l| l =~ /^-- $/ }
685 newstate = :sig
686 elsif line =~ BLOCK_QUOTE_PATTERN && nextline !~ QUOTE_PATTERN
687 newstate = :block_quote
688 end
689
690 if newstate
691 chunks << Chunk::Text.new(chunk_lines) unless chunk_lines.empty?
692 chunk_lines = [line]
693 state = newstate
694 else
695 chunk_lines << line
696 end
697
698 when :quote
699 newstate = nil
700
701 if line =~ QUOTE_PATTERN || (line =~ /^\s*$/ && nextline =~ QUOTE_PATTERN)
702 chunk_lines << line
703 elsif line =~ SIG_PATTERN && (lines.length - i) < MAX_SIG_DISTANCE
704 newstate = :sig
705 else
706 newstate = :text
707 end
708
709 if newstate
710 if chunk_lines.empty?
711 # nothing
712 else
713 chunks << Chunk::Quote.new(chunk_lines)
714 end
715 chunk_lines = [line]
716 state = newstate
717 end
718
719 when :block_quote, :sig
720 chunk_lines << line
721 end
722
723 if !@have_snippet && state == :text && (@snippet.nil? || @snippet.length < SNIPPET_LEN) && line !~ /[=\*#_-]{3,}/ && line !~ /^\s*$/
724 @snippet ||= ""
725 @snippet += " " unless @snippet.empty?
726 @snippet += line.gsub(/^\s+/, "").gsub(/[\r\n]/, "").gsub(/\s+/, " ")
727 oldlen = @snippet.length
728 @snippet = @snippet[0 ... SNIPPET_LEN].chomp
729 @snippet += "..." if @snippet.length < oldlen
730 @dirty = true unless encrypted && $config[:discard_snippets_from_encrypted_messages]
731 @snippet_contains_encrypted_content = true if encrypted
732 end
733 end
734
735 ## final object
736 case state
737 when :quote, :block_quote
738 chunks << Chunk::Quote.new(chunk_lines) unless chunk_lines.empty?
739 when :text
740 chunks << Chunk::Text.new(chunk_lines) unless chunk_lines.empty?
741 when :sig
742 chunks << Chunk::Signature.new(chunk_lines) unless chunk_lines.empty?
743 end
744 chunks
745 end
746
747 def warn_with_location msg
748 warn msg
749 warn "Message is in #{@locations}"
750 end
751 end
752
753 class Location
754 attr_reader :source
755 attr_reader :info
756
757 def initialize source, info
758 @source = source
759 @info = info
760 end
761
762 def raw_header
763 source.raw_header info
764 end
765
766 def raw_message
767 source.raw_message info
768 end
769
770 def sync_back labels, message
771 synced = false
772 return synced unless sync_back_enabled? and valid?
773 source.synchronize do
774 new_info = source.sync_back(@info, labels)
775 if new_info
776 @info = new_info
777 Index.sync_message message, true
778 synced = true
779 end
780 end
781 synced
782 end
783
784 def sync_back_enabled?
785 source.respond_to? :sync_back and $config[:sync_back_to_maildir] and source.sync_back_enabled?
786 end
787
788 ## much faster than raw_message
789 def each_raw_message_line &b
790 source.each_raw_message_line info, &b
791 end
792
793 def parsed_message
794 source.load_message info
795 end
796
797 def fallback_date
798 source.fallback_date_for_message info
799 end
800
801 def valid?
802 source.valid? info
803 end
804
805 def labels?
806 source.labels? info
807 end
808
809 def == o
810 o.source.id == source.id and o.info == info
811 end
812
813 def hash
814 [source.id, info].hash
815 end
816 end
817
818 end