6 ## fucking imap fucking sucks. what the FUCK kind of committee of
7 ## dunces designed this shit.
9 ## imap talks about 'unique ids' for messages, to be used for
10 ## cross-session identification. great---just what sup needs! except
11 ## it turns out the uids can be invalidated every time the
12 ## 'uidvalidity' value changes on the server, and 'uidvalidity' can
13 ## change without restriction. it can change any time you log in. it
14 ## can change EVERY time you log in. of course the imap spec "strongly
15 ## recommends" that it never change, but there's nothing to stop
16 ## people from just setting it to the current timestamp, and in fact
17 ## that's exactly what the one imap server i have at my disposal
18 ## does. thus the so-called uids are absolutely useless and imap
19 ## provides no cross-session way of uniquely identifying a
20 ## message. but thanks for the "strong recommendation", guys!
22 ## so right now i'm using the 'internal date' and the size of each
23 ## message to uniquely identify it, and i scan over the entire mailbox
24 ## each time i open it to map those things to message ids. that can be
25 ## slow for large mailboxes, and we'll just have to hope that there
26 ## are no collisions. ho ho! a perfectly reasonable solution!
28 ## fuck you, imap committee. you managed to design something as shitty
29 ## as mbox but goddamn THIRTY YEARS LATER.
34 SCAN_INTERVAL = 60 # seconds
36 attr_reader_cloned :labels
37 attr_accessor :username, :password
39 def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil
40 raise ArgumentError, "username and password must be specified" unless username && password
41 raise ArgumentError, "not an imap uri" unless uri =~ %r!imaps?://!
43 super uri, last_idate, usual, archived, id
45 @parsed_uri = URI(uri)
53 @labels << :inbox unless archived?
54 @labels << mailbox.intern unless mailbox =~ /inbox/i
58 def host; @parsed_uri.host; end
59 def port; @parsed_uri.port || (ssl? ? 993 : 143); end
61 x = @parsed_uri.path[1..-1]
62 x.nil? || x.empty? ? 'INBOX' : x
64 def ssl?; @parsed_uri.scheme == 'imaps' end
67 MBox::read_header StringIO.new(raw_header(id))
71 RMail::Parser.read raw_full_message(id)
77 header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
78 header = "Status: RO\n" + header if flags.include? :Seen # fake an mbox-style read header
79 header.gsub(/\r\n/, "\n")
83 def raw_full_message id
86 get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
91 return false if broken?
94 say "Connecting to IMAP server #{host}:#{port}..."
96 ## ok, this is FUCKING ANNOYING.
98 ## what imap.rb likes to do is, if an exception occurs, catch it
99 ## and re-raise it on the calling thread. seems reasonable. but
100 ## what that REALLY means is that the only way to reasonably
101 ## initialize imap is in its own thread, because otherwise, you
102 ## will never be able to catch the exception it raises on the
103 ## calling thread, and the backtrace will not make any sense at
104 ## all, and you will waste HOURS of your life on this fucking
110 Redwood::reporting_thread do
112 #raise Net::IMAP::ByeResponseError, "simulated imap failure"
113 @imap = Net::IMAP.new host, port, ssl?
115 @imap.authenticate 'LOGIN', @username, @password
117 say "Successfully connected to #{@parsed_uri}."
118 rescue SocketError, Net::IMAP::Error, SourceError => e
125 die_from exception, :while => "connecting" if exception
129 @mutex.synchronize { connect or raise SourceError, broken_msg }
131 start = @ids.index(cur_offset || start_offset) or die_from "Unknown message id #{cur_offset || start_offset}.", :suggest_rebuild => true # couldn't find the most recent email
133 start.upto(@ids.length - 1) do |i|
141 @mutex.synchronize { connect }
146 @mutex.synchronize do
150 rescue SocketError, Net::IMAP::Error => e
151 die_from e, :while => "scanning mailbox"
157 def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
162 @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
167 BufferManager.clear @say_id if BufferManager.instantiated?
172 return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
174 @imap.examine mailbox
175 last_id = @imap.responses["EXISTS"].last
176 @last_scan = Time.now
177 return if last_id == @ids.length
178 Redwood::log "fetching IMAP headers #{(@ids.length + 1) .. last_id}"
179 values = @imap.fetch((@ids.length + 1) .. last_id, ['RFC822.SIZE', 'INTERNALDATE'])
183 @imap_ids[id] = v.seqno
187 def die_from e, opts={}
193 "Error while #{opts[:while]}: #{e.message.chomp}."
198 message += " It is likely that messages have been deleted from this IMAP mailbox. Please run sup-import --rebuild #{to_s} to correct this problem." if opts[:suggest_rebuild]
200 self.broken_msg = message
202 BufferManager.flash "Error communicating with IMAP server. See log for details."
203 raise SourceError, message
206 ## build a fake unique id
207 def make_id imap_stuff
208 # use 7 digits for the size. why 7? seems nice.
209 msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
210 sprintf("%d%07d", mdate.to_i, msize).to_i
213 def get_imap_fields id, *fields
216 imap_id = @imap_ids[id] or die_from "Unknown message id #{id}.", :suggest_rebuild => true
218 f = @imap.fetch imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq
219 got_id = make_id f[0]
220 die_from "IMAP message mismatch: requested #{id}, got #{got_id}.", :suggest_rebuild => true unless id == got_id
221 rescue SocketError, Net::IMAP::Error => e
222 die_from e, :while => "communicating with IMAP server"
224 if (retries += 1) <= 3
230 die_from "Null IMAP field '#{field}' for message with id #{id} imap id #{imap_id}." if f.nil?
232 fields.map { |field| f[0].attr[field] }
236 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))