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.
33 SCAN_INTERVAL = 60 # seconds
35 ## upon these errors we'll try to rereconnect a few times
36 RECOVERABLE_ERRORS = [ Errno::EPIPE, Errno::ETIMEDOUT ]
38 attr_reader_cloned :labels
39 attr_accessor :username, :password
41 def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil
42 raise ArgumentError, "username and password must be specified" unless username && password
43 raise ArgumentError, "not an imap uri" unless uri =~ %r!imaps?://!
45 super uri, last_idate, usual, archived, id
47 @parsed_uri = URI(uri)
55 @labels << :inbox unless archived?
56 @labels << mailbox.intern unless mailbox =~ /inbox/i
60 def host; @parsed_uri.host; end
61 def port; @parsed_uri.port || (ssl? ? 993 : 143); end
63 x = @parsed_uri.path[1..-1]
64 x.nil? || x.empty? ? 'INBOX' : x
66 def ssl?; @parsed_uri.scheme == 'imaps' end
69 MBox::read_header StringIO.new(raw_header(id))
73 RMail::Parser.read raw_full_message(id)
77 unsynchronized_scan_mailbox
78 header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
79 header = header + "Status: RO\n" if flags.include? :Seen # fake an mbox-style read header # TODO: improve source-marked-as-read reporting system
80 header.gsub(/\r\n/, "\n")
82 synchronized :raw_header
84 def raw_full_message id
85 unsynchronized_scan_mailbox
86 get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
88 synchronized :raw_full_message
91 return if broken? || @imap
92 safely { } # do nothing!
97 return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
100 @imap.responses["EXISTS"].last
102 @last_scan = Time.now
104 return if last_id == @ids.length
106 Redwood::log "fetching IMAP headers #{(@ids.length + 1) .. last_id}"
107 values = safely { @imap.fetch((@ids.length + 1) .. last_id, ['RFC822.SIZE', 'INTERNALDATE']) }
111 @imap_ids[id] = v.seqno
114 synchronized :scan_mailbox
118 @mutex.synchronize do
119 unsynchronized_scan_mailbox
123 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
125 start.upto(ids.length - 1) do |i|
133 unsynchronized_scan_mailbox
136 synchronized :start_offset
139 unsynchronized_scan_mailbox
142 synchronized :end_offset
144 def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
149 say "Connecting to IMAP server #{host}:#{port}..."
151 ## apparently imap.rb does a lot of threaded stuff internally and
152 ## if an exception occurs, it will catch it and re-raise it on the
153 ## calling thread. but i can't seem to catch that exception, so
154 ## i've resorted to initializing it in its own thread. surely
155 ## there's a better way.
159 #raise Net::IMAP::ByeResponseError, "simulated imap failure"
160 @imap = Net::IMAP.new host, port, ssl?
163 ## although RFC1730 claims that "If an AUTHENTICATE command
164 ## fails with a NO response, the client may try another", in
165 ## practice it seems like they can also send a BAD response.
167 @imap.authenticate 'CRAM-MD5', @username, @password
168 rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
169 Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
171 @imap.authenticate 'LOGIN', @username, @password
172 rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
173 Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
174 @imap.login @username, @password
177 say "Successfully connected to #{@parsed_uri}."
178 rescue Exception => e
185 raise exception if exception
189 @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
194 BufferManager.clear @say_id if BufferManager.instantiated?
198 def die_from e, opts={}
204 "Error while #{opts[:while]}: #{e.message.chomp} (#{e.class.name})."
209 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]
211 self.broken_msg = message
213 BufferManager.flash "Error communicating with IMAP server. See log for details." if BufferManager.instantiated?
214 raise SourceError, message
217 ## build a fake unique id
218 def make_id imap_stuff
219 # use 7 digits for the size. why 7? seems nice.
220 msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
221 sprintf("%d%07d", mdate.to_i, msize).to_i
224 def get_imap_fields id, *fields
225 raise SourceError, broken_msg if broken?
226 imap_id = @imap_ids[id] or die_from "Unknown message id #{id}.", :suggest_rebuild => true
229 results = safely { @imap.fetch imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq }.first
230 got_id = make_id results
231 die_from "IMAP message mismatch: requested #{id}, got #{got_id}.", :suggest_rebuild => true unless got_id == id
233 fields.map { |f| results.attr[f] }
236 ## execute a block, connected if unconnected, re-connected up to 3
237 ## times if a recoverable error occurs, and properly dying if an
238 ## unrecoverable error occurs.
243 unsafe_connect unless @imap
245 rescue *RECOVERABLE_ERRORS
246 if (retries += 1) <= 3
252 rescue Net, SocketError, Net::IMAP::Error, SystemCallError => e
253 die_from e, :while => "communicating with IMAP server"
259 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))