]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
fixed imap error handling
[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   attr_reader_cloned :labels
35   attr_accessor :username, :password
36
37   def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil
38     raise ArgumentError, "username and password must be specified" unless username && password
39     raise ArgumentError, "not an imap uri" unless uri =~ %r!imaps?://!
40
41     super uri, last_idate, usual, archived, id
42
43     @parsed_uri = URI(uri)
44     @username = username
45     @password = password
46     @imap = nil
47     @imap_ids = {}
48     @ids = []
49     @labels = [:unread]
50     @labels << :inbox unless archived?
51     @labels << mailbox.intern unless mailbox =~ /inbox/i
52     @mutex = Mutex.new
53
54     @recover_msg = "It is likely that messages have been deleted from this IMAP mailbox. Please run sup-import --rebuild #{to_s} to correct this problem."
55   end
56
57   def say s
58     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
59     Redwood::log s
60   end
61   def shutup
62     BufferManager.clear @say_id if BufferManager.instantiated?
63     @say_id = nil
64   end
65   private :say, :shutup
66
67   def connect
68     return false if broken?
69     return true if @imap
70
71     ## ok, this is FUCKING ANNOYING.
72     ##
73     ## what imap.rb likes to do is, if an exception occurs, catch it
74     ## and re-raise it on the calling thread. seems reasonable. but
75     ## what that REALLY means is that the only way to reasonably
76     ## initialize imap is in its own thread, because otherwise, you
77     ## will never be able to catch the exception it raises on the
78     ## calling thread, and the backtrace will not make any sense at
79     ## all, and you will waste HOURS of your life on this fucking
80     ## problem.
81     ##
82     ## FUCK!!!!!!!!!
83
84     say "Connecting to IMAP server #{host}:#{port}..."
85
86     Redwood::reporting_thread do
87       begin
88         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
89         @imap = Net::IMAP.new host, ssl? ? 993 : 143, ssl?
90         say "Logging in..."
91         @imap.authenticate 'LOGIN', @username, @password
92         say "Sizing mailbox..."
93         @imap.examine mailbox
94         last_id = @imap.responses["EXISTS"][-1]
95         
96         say "Reading headers (because IMAP sucks)..."
97         values = @imap.fetch(1 .. last_id, ['RFC822.SIZE', 'INTERNALDATE'])
98         say "Successfully connected to #{@parsed_uri}."
99         
100         values.each do |v|
101           id = make_id v
102           @ids << id
103           @imap_ids[id] = v.seqno
104         end
105       rescue SocketError, Net::IMAP::Error, SourceError => e
106         self.broken_msg = e.message.chomp # fucking chomp! fuck!!!
107         @imap = nil
108         msg = "error connecting to IMAP server: #{self.broken_msg}"
109         Redwood::log msg
110         BufferManager.flash msg
111       ensure
112         shutup
113       end
114     end.join
115
116     !!@imap
117   end
118   private :connect
119
120   def make_id imap_stuff
121     msize, mdate = imap_stuff.attr['RFC822.SIZE'], Time.parse(imap_stuff.attr["INTERNALDATE"])
122     sprintf("%d%07d", mdate.to_i, msize).to_i
123   end
124   private :make_id
125
126   def host; @parsed_uri.host; end
127   def port; @parsed_uri.port || (ssl? ? 993 : 143); end
128   def mailbox
129     x = @parsed_uri.path[1..-1]
130     x.nil? || x.empty? ? 'INBOX' : x
131   end
132   def ssl?; @parsed_uri.scheme == 'imaps' end
133
134   def load_header id
135     MBox::read_header StringIO.new(raw_header(id))
136   end
137
138   def load_message id
139     RMail::Parser.read raw_full_message(id)
140   end
141
142   ## load the full header text
143   def raw_header id
144     @mutex.synchronize do
145       connect or raise SourceError, broken_msg
146       get_imap_field(id, 'RFC822.HEADER').gsub(/\r\n/, "\n")
147     end
148   end
149
150   def raw_full_message id
151     @mutex.synchronize do
152       connect or raise SourceError, broken_msg
153       get_imap_field(id, 'RFC822').gsub(/\r\n/, "\n")
154     end
155   end
156
157   def get_imap_field id, field
158     retries = 0
159     f = nil
160     imap_id = @imap_ids[id] or raise SourceError, "Unknown message id #{id}. #@recover_msg"
161     begin
162       f = @imap.fetch imap_id, [field, 'RFC822.SIZE', 'INTERNALDATE']
163       got_id = make_id f[0]
164       raise SourceError, "IMAP message mismatch: requested #{id}, got #{got_id}. #@recover_msg" unless got_id == id
165     rescue Net::IMAP::Error => e
166       raise SourceError, e.message
167     rescue Errno::EPIPE
168       if (retries += 1) <= 3
169         @imap = nil
170         connect
171         retry
172       end
173     end
174     raise SourceError, "null IMAP field '#{field}' for message with id #{id} imap id #{imap_id}" if f.nil?
175
176     f[0].attr[field]
177   end
178   private :get_imap_field
179   
180   def each
181     @mutex.synchronize { connect or raise SourceError, broken_msg }
182
183     start = @ids.index(cur_offset || start_offset)
184     if start.nil? # couldn't find the most recent email
185       self.broken_msg = "Unknown message id #{cur_offset || start_offset}. #@recover_msg" 
186       raise SourceError, broken_msg
187     end
188     start.upto(@ids.length - 1) do |i|         
189       id = @ids[i]
190       self.cur_offset = id
191       yield id, labels
192     end
193   end
194
195   def start_offset
196     @mutex.synchronize { connect or raise SourceError, broken_msg }
197     @ids.first
198   end
199
200   def end_offset
201     @mutex.synchronize { connect or raise SourceError, broken_msg }
202     @ids.last
203   end
204 end
205
206 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))
207
208 end