7 ## fucking imap fucking sucks. what the FUCK kind of committee of
8 ## dunces designed this shit.
10 ## imap talks about 'unique ids' for messages, to be used for
11 ## cross-session identification. great---just what sup needs! except
12 ## it turns out the uids can be invalidated every time the
13 ## 'uidvalidity' value changes on the server, and 'uidvalidity' can
14 ## change without restriction. it can change any time you log in. it
15 ## can change EVERY time you log in. of course the imap spec "strongly
16 ## recommends" that it never change, but there's nothing to stop
17 ## people from just setting it to the current timestamp, and in fact
18 ## that's exactly what the one imap server i have at my disposal
19 ## does. thus the so-called uids are absolutely useless and imap
20 ## provides no cross-session way of uniquely identifying a
21 ## message. but thanks for the "strong recommendation", guys!
23 ## so right now i'm using the 'internal date' and the size of each
24 ## message to uniquely identify it, and i scan over the entire mailbox
25 ## each time i open it to map those things to message ids. that can be
26 ## slow for large mailboxes, and we'll just have to hope that there
27 ## are no collisions. ho ho! a perfectly reasonable solution!
29 ## and here's another thing. check out RFC2060 2.2.2 paragraph 5:
31 ## A client MUST be prepared to accept any server response at all times.
32 ## This includes server data that was not requested.
34 ## yeah. that totally makes a lot of sense. and once again, the idiocy
35 ## of the spec actually happens in practice. you'll request flags for
36 ## one message, and get it interspersed with a random bunch of flags
37 ## for some other messages, including a different set of flags for the
38 ## same message! totally ok by the imap spec. totally retarded by any
41 ## fuck you, imap committee. you managed to design something nearly as
42 ## shitty as mbox but goddamn THIRTY YEARS LATER.
46 SCAN_INTERVAL = 60 # seconds
48 ## upon these errors we'll try to rereconnect a few times
49 RECOVERABLE_ERRORS = [ Errno::EPIPE, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError ]
51 attr_accessor :username, :password
52 yaml_properties :uri, :username, :password, :cur_offset, :usual,
53 :archived, :id, :labels
55 def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil, labels=[]
56 raise ArgumentError, "username and password must be specified" unless username && password
57 raise ArgumentError, "not an imap uri" unless uri =~ %r!imaps?://!
59 super uri, last_idate, usual, archived, id
61 @parsed_uri = URI(uri)
68 @labels = (labels || []).freeze
73 def self.suggest_labels_for path
81 def host; @parsed_uri.host; end
82 def port; @parsed_uri.port || (ssl? ? 993 : 143); end
84 x = @parsed_uri.path[1..-1]
85 x.nil? || x.empty? ? 'INBOX' : x
87 def ssl?; @parsed_uri.scheme == 'imaps' end
92 unsynchronized_scan_mailbox
96 start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
99 ## is this necessary? TODO: remove maybe
100 def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
103 MBox::read_header StringIO.new(raw_header(id))
107 RMail::Parser.read raw_full_message(id)
111 unsynchronized_scan_mailbox
112 header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
113 ## very bad. this is very very bad. very bad bad bad.
114 header = header + "Status: RO\n" if flags.include? :Seen # fake an mbox-style read header # TODO: improve source-marked-as-read reporting system
115 header.gsub(/\r\n/, "\n")
117 synchronized :raw_header
119 def raw_full_message id
120 unsynchronized_scan_mailbox
121 get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
123 synchronized :raw_full_message
127 safely { } # do nothing!
129 synchronized :connect
132 return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
134 @imap.examine mailbox
135 @imap.responses["EXISTS"].last
137 @last_scan = Time.now
139 return if last_id == @ids.length
141 range = (@ids.length + 1) .. last_id
142 Redwood::log "fetching IMAP headers #{range}"
143 fetch(range, ['RFC822.SIZE', 'INTERNALDATE']).each do |v|
146 @imap_ids[id] = v.seqno
149 synchronized :scan_mailbox
153 @mutex.synchronize do
154 unsynchronized_scan_mailbox
158 start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
160 start.upto(ids.length - 1) do |i|
168 unsynchronized_scan_mailbox
171 synchronized :start_offset
174 unsynchronized_scan_mailbox
177 synchronized :end_offset
179 def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
183 def fetch ids, fields
184 results = safely { @imap.fetch ids, fields }
186 if ids.respond_to? :member?
187 results.find_all { |r| ids.member?(r.seqno) && fields.all? { |f| r.attr.member?(f) } }
189 results.find_all { |r| ids == r.seqno && fields.all? { |f| r.attr.member?(f) } }
192 if good_results.empty?
193 raise FatalSourceError, "no IMAP response for #{ids} containing all fields #{fields.join(', ')} (got #{results.size} results)"
194 elsif good_results.size < results.size
195 Redwood::log "Your IMAP server sucks. It sent #{results.size} results for a request for #{good_results.size} messages. What are you using, Binc?"
202 say "Connecting to IMAP server #{host}:#{port}..."
204 ## apparently imap.rb does a lot of threaded stuff internally and
205 ## if an exception occurs, it will catch it and re-raise it on the
206 ## calling thread. but i can't seem to catch that exception, so
207 ## i've resorted to initializing it in its own thread. surely
208 ## there's a better way.
212 #raise Net::IMAP::ByeResponseError, "simulated imap failure"
213 @imap = Net::IMAP.new host, port, ssl?
216 ## although RFC1730 claims that "If an AUTHENTICATE command
217 ## fails with a NO response, the client may try another", in
218 ## practice it seems like they can also send a BAD response.
220 @imap.authenticate 'CRAM-MD5', @username, @password
221 rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
222 Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
224 @imap.authenticate 'LOGIN', @username, @password
225 rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
226 Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
227 @imap.login @username, @password
230 say "Successfully connected to #{@parsed_uri}."
231 rescue Exception => e
238 raise exception if exception
242 @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
247 BufferManager.clear @say_id if BufferManager.instantiated?
251 def make_id imap_stuff
252 # use 7 digits for the size. why 7? seems nice.
253 %w(RFC822.SIZE INTERNALDATE).each do |w|
254 raise FatalSourceError, "requested data not in IMAP response: #{w}" unless imap_stuff.attr[w]
257 msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
258 sprintf("%d%07d", mdate.to_i, msize).to_i
261 def get_imap_fields id, *fields
262 imap_id = @imap_ids[id] or raise OutOfSyncSourceError, "Unknown message id #{id}"
265 result = fetch(imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq).first
266 got_id = make_id result
267 raise OutOfSyncSourceError, "IMAP message mismatch: requested #{id}, got #{got_id}." unless got_id == id
269 fields.map { |f| result.attr[f] or raise FatalSourceError, "empty response from IMAP server: #{f}" }
272 ## execute a block, connected if unconnected, re-connected up to 3
273 ## times if a recoverable error occurs, and properly dying if an
274 ## unrecoverable error occurs.
279 unsafe_connect unless @imap
281 rescue *RECOVERABLE_ERRORS => e
282 if (retries += 1) <= 3
284 Redwood::log "got #{e.class.name}: #{e.message.inspect}"
290 rescue SocketError, Net::IMAP::Error, SystemCallError, IOError, OpenSSL::SSL::SSLError => e
291 raise FatalSourceError, "While communicating with IMAP server (type #{e.class.name}): #{e.message.inspect}"