]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
yet more error-handling minor tweaks. jesus christ i hope it works now.
[sup] / lib / sup / imap.rb
1 require 'uri'
2 require 'net/imap'
3 require 'stringio'
4 require 'time'
5
6 ## fucking imap fucking sucks. what the FUCK kind of committee of
7 ## dunces designed this shit.
8
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!
21
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!
27
28 ## fuck you, imap committee. you managed to design something as shitty
29 ## as mbox but goddamn THIRTY YEARS LATER.
30
31 module Redwood
32
33 class IMAP < Source
34   SCAN_INTERVAL = 60 # seconds
35
36   attr_reader_cloned :labels
37   attr_accessor :username, :password
38
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?://!
42
43     super uri, last_idate, usual, archived, id
44
45     @parsed_uri = URI(uri)
46     @username = username
47     @password = password
48     @imap = nil
49     @imap_ids = {}
50     @ids = []
51     @last_scan = nil
52     @labels = [:unread]
53     @labels << :inbox unless archived?
54     @labels << mailbox.intern unless mailbox =~ /inbox/i
55     @mutex = Mutex.new
56   end
57
58   def host; @parsed_uri.host; end
59   def port; @parsed_uri.port || (ssl? ? 993 : 143); end
60   def mailbox
61     x = @parsed_uri.path[1..-1]
62     x.nil? || x.empty? ? 'INBOX' : x
63   end
64   def ssl?; @parsed_uri.scheme == 'imaps' end
65
66   def load_header id
67     MBox::read_header StringIO.new(raw_header(id))
68   end
69
70   def load_message id
71     RMail::Parser.read raw_full_message(id)
72   end
73
74   def raw_header id
75     @mutex.synchronize do
76       connect
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")
80     end
81   end
82
83   def raw_full_message id
84     @mutex.synchronize do
85       connect
86       get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
87     end
88   end
89
90   def connect
91     return false if broken?
92     return true if @imap
93
94     say "Connecting to IMAP server #{host}:#{port}..."
95
96     ## ok, this is FUCKING ANNOYING.
97     ##
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
105     ## problem.
106     ##
107     ## FUCK!!!!!!!!!
108
109     exception = nil
110     Redwood::reporting_thread do
111       begin
112         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
113         @imap = Net::IMAP.new host, port, ssl?
114         say "Logging in..."
115         @imap.authenticate 'LOGIN', @username, @password
116         scan_mailbox
117         say "Successfully connected to #{@parsed_uri}."
118       rescue SocketError, Net::IMAP::Error, SourceError => e
119         exception = e
120       ensure
121         shutup
122       end
123     end.join
124
125     die_from exception, :while => "connecting" if exception
126   end
127
128   def each
129     @mutex.synchronize { connect or raise SourceError, broken_msg }
130
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
132
133     start.upto(@ids.length - 1) do |i|         
134       id = @ids[i]
135       self.cur_offset = id
136       yield id, labels
137     end
138   end
139
140   def start_offset
141     @mutex.synchronize { connect }
142     @ids.first
143   end
144
145   def end_offset
146     @mutex.synchronize do
147       begin
148         connect
149         scan_mailbox
150       rescue SocketError, Net::IMAP::Error => e
151         die_from e, :while => "scanning mailbox"
152       end
153     end
154     @ids.last
155   end
156
157   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
158
159 private
160
161   def say s
162     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
163     Redwood::log s
164   end
165
166   def shutup
167     BufferManager.clear @say_id if BufferManager.instantiated?
168     @say_id = nil
169   end
170
171   def scan_mailbox
172     return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
173
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'])
180     values.each do |v|
181       id = make_id v
182       @ids << id
183       @imap_ids[id] = v.seqno
184     end
185   end
186
187   def die_from e, opts={}
188     @imap = nil
189
190     message =
191       case e
192       when Exception
193         "Error while #{opts[:while]}: #{e.message.chomp}."
194       when String
195         e
196       end
197
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]
199
200     self.broken_msg = message
201     Redwood::log message
202     BufferManager.flash "Error communicating with IMAP server. See log for details."
203     raise SourceError, message
204   end
205   
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
211   end
212
213   def get_imap_fields id, *fields
214     retries = 0
215     f = nil
216     imap_id = @imap_ids[id] or die_from "Unknown message id #{id}.", :suggest_rebuild => true
217     begin
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"
223     rescue Errno::EPIPE
224       if (retries += 1) <= 3
225         @imap = nil
226         connect
227         retry
228       end
229     end
230     die_from "Null IMAP field '#{field}' for message with id #{id} imap id #{imap_id}." if f.nil?
231
232     fields.map { |field| f[0].attr[field] }
233   end
234 end
235
236 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))
237
238 end