]> git.cworth.org Git - sup/blob - lib/sup/mbox.rb
change email header parsing. MASSIVE SPEEDUP!
[sup] / lib / sup / mbox.rb
1 require "sup/mbox/loader"
2 require "sup/mbox/ssh-file"
3 require "sup/mbox/ssh-loader"
4 require "sup/rfc2047"
5
6 module Redwood
7
8 ## some utility functions. actually these are not mbox-specific at all
9 ## and should be moved somewhere else.
10 ##
11 ## TODO: move functionality to somewhere better, like message.rb
12 module MBox
13   BREAK_RE = /^From \S+/ ######### TODO REMOVE ME
14
15   ## WARNING! THIS IS A SPEED-CRITICAL SECTION. Everything you do here will have
16   ## a significant effect on Sup's processing speed of email from ALL sources.
17   ## Little things like string interpolation, regexp interpolation, += vs <<,
18   ## all have DRAMATIC effects. BE CAREFUL WHAT YOU DO!
19   def read_header f
20     header = {}
21     last = nil
22
23     while(line = f.gets)
24       case line
25       ## these three can occur multiple times, and we want the first one
26       when /^(Delivered-To|X-Original-To|Envelope-To):\s*(.*?)\s*$/i; header[last = $1.downcase] ||= $2
27       ## mark this guy specially. not sure why i care.
28       when /^([^:\s]+):\s*(.*?)\s*$/i; header[last = $1.downcase] = $2
29       when /^\r*$/; break
30       else
31         if last
32           header[last] << " " unless header[last].empty?
33           header[last] << line.strip
34         end
35       end
36     end
37
38     %w(subject from to cc bcc).each do |k|
39       v = header[k] or next
40       next unless Rfc2047.is_encoded? v
41       header[k] = begin
42         Rfc2047.decode_to $encoding, v
43       rescue Errno::EINVAL, Iconv::InvalidEncoding, Iconv::IllegalSequence => e
44         Redwood::log "warning: error decoding RFC 2047 header (#{e.class.name}): #{e.message}"
45         v
46       end
47     end
48     header
49   end
50   
51   module_function :read_header
52 end
53 end