lib/sup/mbox.rb (5393B) - raw
1 require 'uri'
2 require 'set'
3 require 'time'
4
5 module Redwood
6
7 class MBox < Source
8 BREAK_RE = /^From \S+ (.+)$/
9
10 include SerializeLabelsNicely
11 yaml_properties :uri, :usual, :archived, :id, :labels
12
13 attr_reader :labels
14
15 ## uri_or_fp is horrific. need to refactor.
16 def initialize uri_or_fp, usual=true, archived=false, id=nil, labels=nil
17 @mutex = Mutex.new
18 @labels = Set.new((labels || []) - LabelManager::RESERVED_LABELS)
19
20 case uri_or_fp
21 when String
22 @expanded_uri = Source.expand_filesystem_uri(uri_or_fp)
23 parts = /^([a-zA-Z0-9]*:(\/\/)?)(.*)/.match @expanded_uri
24 if parts
25 prefix = parts[1]
26 @path = parts[3]
27 uri = URI(prefix + Source.encode_path_for_uri(@path))
28 else
29 uri = URI(Source.encode_path_for_uri @expanded_uri)
30 @path = uri.path
31 end
32
33 raise ArgumentError, "not an mbox uri" unless uri.scheme == "mbox"
34 raise ArgumentError, "mbox URI ('#{uri}') cannot have a host: #{uri.host}" unless uri.host.nil? || uri.host.empty?
35 raise ArgumentError, "mbox URI must have a path component" unless uri.path
36 @f = nil
37 else
38 @f = uri_or_fp
39 @path = uri_or_fp.path
40 @expanded_uri = "mbox://#{Source.encode_path_for_uri @path}"
41 end
42
43 super uri_or_fp, usual, archived, id
44 end
45
46 def file_path; @path end
47 def is_source_for? uri; super || (uri == @expanded_uri) end
48
49 def self.suggest_labels_for path
50 ## heuristic: use the filename as a label, unless the file
51 ## has a path that probably represents an inbox.
52 if File.dirname(path) =~ /\b(var|usr|spool)\b/
53 []
54 else
55 [File.basename(path).downcase.intern]
56 end
57 end
58
59 def ensure_open
60 @f = File.open @path, 'rb' if @f.nil?
61 end
62 private :ensure_open
63
64 def go_idle
65 @mutex.synchronize do
66 return if @f.nil? or @path.nil?
67 @f.close
68 @f = nil
69 end
70 end
71
72 def load_message offset
73 @mutex.synchronize do
74 ensure_open
75 @f.seek offset
76 begin
77 ## don't use RMail::Mailbox::MBoxReader because it doesn't properly ignore
78 ## "From" at the start of a message body line.
79 string = +""
80 until @f.eof? || MBox::is_break_line?(l = @f.gets)
81 string << l
82 end
83 RMail::Parser.read string
84 rescue RMail::Parser::Error => e
85 raise FatalSourceError, "error parsing mbox file: #{e.message}"
86 end
87 end
88 end
89
90 def raw_header offset
91 ret = +""
92 @mutex.synchronize do
93 ensure_open
94 @f.seek offset
95 until @f.eof? || (l = @f.gets) =~ /^\r*$/
96 ret << l
97 end
98 end
99 ret
100 end
101
102 def raw_message offset
103 enum_for(:each_raw_message_line, offset).reduce(:+)
104 end
105
106 def store_message date, from_email, &block
107 need_blank = File.exist?(@path) && !File.zero?(@path)
108 File.open(@path, "ab") do |f|
109 f.puts if need_blank
110 f.puts "From #{from_email} #{date.asctime}"
111 yield f
112 end
113 end
114
115 ## apparently it's a million times faster to call this directly if
116 ## we're just moving messages around on disk, than reading things
117 ## into memory with raw_message.
118 ##
119 def each_raw_message_line offset
120 @mutex.synchronize do
121 ensure_open
122 @f.seek offset
123 until @f.eof? || MBox::is_break_line?(l = @f.gets)
124 yield l
125 end
126 end
127 end
128
129 def fallback_date_for_message offset
130 ## This is a bit awkward... We treat the From line as a delimiter,
131 ## not part of the message. So the offset is pointing *after* the
132 ## From line for the desired message. With a bit of effort we can
133 ## scan backwards to find its From line and extract a date from it.
134 buf = @mutex.synchronize do
135 ensure_open
136 start = offset
137 loop do
138 start = (start - 200).clamp 0, 2**64
139 @f.seek start
140 buf = @f.read (offset - start)
141 break buf if buf.include? ?\n or start == 0
142 end
143 end
144 BREAK_RE.match buf.lines.last do |m|
145 Time.strptime m[1], "%a %b %d %H:%M:%S %Y"
146 end
147 end
148
149 def default_labels
150 [:inbox, :unread]
151 end
152
153 def poll
154 first_offset = first_new_message
155 offset = first_offset
156 end_offset = File.size @f
157 while offset and offset < end_offset
158 yield :add,
159 :info => offset,
160 :labels => (labels + default_labels),
161 :progress => (offset - first_offset).to_f/end_offset
162 offset = next_offset offset
163 end
164 end
165
166 def next_offset offset
167 @mutex.synchronize do
168 ensure_open
169 @f.seek offset
170 nil while line = @f.gets and not MBox::is_break_line? line
171 offset = @f.tell
172 offset != File.size(@f) ? offset : nil
173 end
174 end
175
176 ## TODO optimize this by iterating over allterms list backwards or
177 ## storing source_info negated
178 def last_indexed_message
179 benchmark(:mbox_read_index) { Index.instance.enum_for(:each_source_info, self.id).map(&:to_i).max }
180 end
181
182 ## offset of first new message or nil
183 def first_new_message
184 next_offset(last_indexed_message || 0)
185 end
186
187 def self.is_break_line? l
188 l =~ BREAK_RE or return false
189 time = $1
190 begin
191 Time.strptime time, "%a %b %d %H:%M:%S %Y"
192 true
193 rescue NoMethodError, ArgumentError
194 warn "found invalid date in potential mbox split line, not splitting: #{l.inspect}"
195 false
196 end
197 end
198
199 class Loader < self
200 yaml_properties :uri, :usual, :archived, :id, :labels
201 end
202 end
203 end