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