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 ## fuck you, imap committee. you managed to design something nearly as
30 ## shitty as mbox but goddamn THIRTY YEARS LATER.
34 SCAN_INTERVAL = 60 # seconds
36 ## upon these errors we'll try to rereconnect a few times
37 RECOVERABLE_ERRORS = [ Errno::EPIPE, Errno::ETIMEDOUT ]
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 << mailbox.intern unless mailbox =~ /inbox/i
59 def host; @parsed_uri.host; end
60 def port; @parsed_uri.port || (ssl? ? 993 : 143); end
62 x = @parsed_uri.path[1..-1]
63 x.nil? || x.empty? ? 'INBOX' : x
65 def ssl?; @parsed_uri.scheme == 'imaps' end
67 ## is this necessary? TODO: remove maybe
68 def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
71 MBox::read_header StringIO.new(raw_header(id))
75 RMail::Parser.read raw_full_message(id)
79 unsynchronized_scan_mailbox
80 header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
81 header = header + "Status: RO\n" if flags.include? :Seen # fake an mbox-style read header # TODO: improve source-marked-as-read reporting system
82 header.gsub(/\r\n/, "\n")
84 synchronized :raw_header
86 def raw_full_message id
87 unsynchronized_scan_mailbox
88 get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
90 synchronized :raw_full_message
93 return if broken? || @imap
94 safely { } # do nothing!
99 return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
101 @imap.examine mailbox
102 @imap.responses["EXISTS"].last
104 @last_scan = Time.now
106 return if last_id == @ids.length
108 Redwood::log "fetching IMAP headers #{(@ids.length + 1) .. last_id}"
109 values = safely { @imap.fetch((@ids.length + 1) .. last_id, ['RFC822.SIZE', 'INTERNALDATE']) }
113 @imap_ids[id] = v.seqno
116 synchronized :scan_mailbox
120 @mutex.synchronize do
121 unsynchronized_scan_mailbox
125 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
127 start.upto(ids.length - 1) do |i|
130 yield id, @labels.clone
135 unsynchronized_scan_mailbox
138 synchronized :start_offset
141 unsynchronized_scan_mailbox
144 synchronized :end_offset
146 def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
151 say "Connecting to IMAP server #{host}:#{port}..."
153 ## apparently imap.rb does a lot of threaded stuff internally and
154 ## if an exception occurs, it will catch it and re-raise it on the
155 ## calling thread. but i can't seem to catch that exception, so
156 ## i've resorted to initializing it in its own thread. surely
157 ## there's a better way.
161 #raise Net::IMAP::ByeResponseError, "simulated imap failure"
162 @imap = Net::IMAP.new host, port, ssl?
165 ## although RFC1730 claims that "If an AUTHENTICATE command
166 ## fails with a NO response, the client may try another", in
167 ## practice it seems like they can also send a BAD response.
169 @imap.authenticate 'CRAM-MD5', @username, @password
170 rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
171 Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
173 @imap.authenticate 'LOGIN', @username, @password
174 rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
175 Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
176 @imap.login @username, @password
179 say "Successfully connected to #{@parsed_uri}."
180 rescue Exception => e
187 raise exception if exception
191 @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
196 BufferManager.clear @say_id if BufferManager.instantiated?
200 def die_from e, opts={}
206 "Error while #{opts[:while]}: #{e.message.chomp} (#{e.class.name})."
211 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]
213 self.broken_msg = message
215 BufferManager.flash "Error communicating with IMAP server. See log for details." if BufferManager.instantiated?
216 raise SourceError, message
219 ## build a fake unique id
220 def make_id imap_stuff
221 # use 7 digits for the size. why 7? seems nice.
222 msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
223 sprintf("%d%07d", mdate.to_i, msize).to_i
226 def get_imap_fields id, *fields
227 raise SourceError, broken_msg if broken?
228 imap_id = @imap_ids[id] or die_from "Unknown message id #{id}.", :suggest_rebuild => true
231 results = safely { @imap.fetch imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq }.first
232 got_id = make_id results
233 die_from "IMAP message mismatch: requested #{id}, got #{got_id}.", :suggest_rebuild => true unless got_id == id
235 fields.map { |f| results.attr[f] }
238 ## execute a block, connected if unconnected, re-connected up to 3
239 ## times if a recoverable error occurs, and properly dying if an
240 ## unrecoverable error occurs.
245 unsafe_connect unless @imap
247 rescue *RECOVERABLE_ERRORS
248 if (retries += 1) <= 3
254 rescue Net, SocketError, Net::IMAP::Error, SystemCallError => e
255 die_from e, :while => "communicating with IMAP server"
261 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))