]> git.cworth.org Git - sup/blob - lib/sup/maildir.rb
c754ccdf49aca1b1c1504a4b056f565b278b96b2
[sup] / lib / sup / maildir.rb
1 require 'rmail'
2 require 'uri'
3
4 module Redwood
5
6 ## Maildir doesn't provide an ordered unique id, which is what Sup
7 ## requires to be really useful. So we must maintain, in memory, a
8 ## mapping between Sup "ids" (timestamps, essentially) and the
9 ## pathnames on disk.
10
11 class Maildir < Source
12   SCAN_INTERVAL = 30 # seconds
13
14   ## remind me never to use inheritance again.
15   yaml_properties :uri, :cur_offset, :usual, :archived, :id, :labels
16   def initialize uri, last_date=nil, usual=true, archived=false, id=nil, labels=[]
17     uri = Source.expand_filesystem_uri uri
18     super uri, last_date, usual, archived, id
19     uri = URI(uri)
20
21     raise ArgumentError, "not a maildir URI" unless uri.scheme == "maildir"
22     raise ArgumentError, "maildir URI cannot have a host: #{uri.host}" if uri.host
23
24     @dir = uri.path
25     @labels = (labels || []).freeze
26     @ids = []
27     @ids_to_fns = {}
28     @last_scan = nil
29     @mutex = Mutex.new
30   end
31
32   def file_path; @dir end
33   def self.suggest_labels_for path; [] end
34   def is_source_for? uri; super || (URI(Source.expand_filesystem_uri(uri)) == URI(self.uri)); end
35
36   def check
37     scan_mailbox
38     return unless start_offset
39
40     start = @ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}." # couldn't find the most recent email
41   end
42
43   def load_header id
44     scan_mailbox
45     with_file_for(id) { |f| MBox::read_header f }
46   end
47
48   def load_message id
49     scan_mailbox
50     with_file_for(id) { |f| RMail::Parser.read f }
51   end
52
53   def raw_header id
54     scan_mailbox
55     ret = ""
56     with_file_for(id) do |f|
57       until f.eof? || (l = f.gets) =~ /^$/
58         ret += l
59       end
60     end
61     ret
62   end
63
64   def raw_full_message id
65     scan_mailbox
66     with_file_for(id) { |f| f.readlines.join }
67   end
68
69   def scan_mailbox
70     return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
71
72     cdir = File.join(@dir, 'cur')
73     ndir = File.join(@dir, 'new')
74     
75     raise FatalSourceError, "#{cdir} not a directory" unless File.directory? cdir
76     raise FatalSourceError, "#{ndir} not a directory" unless File.directory? ndir
77
78     begin
79       @ids, @ids_to_fns = @mutex.synchronize do
80         ids, ids_to_fns = [], {}
81         (Dir[File.join(cdir, "*")] + Dir[File.join(ndir, "*")]).map do |fn|
82           id = make_id fn
83           ids << id
84           ids_to_fns[id] = fn
85         end
86         [ids.sort, ids_to_fns]
87       end
88     rescue SystemCallError, IOError => e
89       raise FatalSourceError, "Problem scanning Maildir directories: #{e.message}."
90     end
91     
92     @last_scan = Time.now
93   end
94
95   def each
96     scan_mailbox
97     return unless start_offset
98
99     start = @ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}." # couldn't find the most recent email
100
101     start.upto(@ids.length - 1) do |i|         
102       id = @ids[i]
103       self.cur_offset = id
104       yield id, @labels + (seen?(id) ? [] : [:unread]) + (trashed?(id) ? [:deleted] : [])
105     end
106   end
107
108   def start_offset
109     scan_mailbox
110     @ids.first
111   end
112
113   def end_offset
114     scan_mailbox
115     @ids.last
116   end
117
118   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
119
120   def draft? msg; maildir_data(msg)[2].include? "D"; end
121   def flagged? msg; maildir_data(msg)[2].include? "F"; end
122   def passed? msg; maildir_data(msg)[2].include? "P"; end
123   def replied? msg; maildir_data(msg)[2].include? "R"; end
124   def seen? msg; maildir_data(msg)[2].include? "S"; end
125   def trashed? msg; maildir_data(msg)[2].include? "T"; end
126
127   def mark_draft msg; maildir_mark_file msg, "D" unless draft? msg; end
128   def mark_flagged msg; maildir_mark_file msg, "F" unless flagged? msg; end
129   def mark_passed msg; maildir_mark_file msg, "P" unless passed? msg; end
130   def mark_replied msg; maildir_mark_file msg, "R" unless replied? msg; end
131   def mark_seen msg; maildir_mark_file msg, "S" unless seen? msg; end
132   def mark_trashed msg; maildir_mark_file msg, "T" unless trashed? msg; end
133
134 private
135
136   def make_id fn
137     # use 7 digits for the size. why 7? seems nice.
138     sprintf("%d%07d", File.mtime(fn), File.size(fn)).to_i
139   end
140
141   def with_file_for id
142     fn = @ids_to_fns[id] or raise OutOfSyncSourceError, "No such id: #{id.inspect}."
143     begin
144       File.open(fn) { |f| yield f }
145     rescue SystemCallError, IOError => e
146       raise FatalSourceError, "Problem reading file for id #{id.inspect}: #{fn.inspect}: #{e.message}."
147     end
148   end
149
150   def maildir_data msg
151     fn = File.basename @ids_to_fns[msg]
152     fn =~ %r{^([^:,]+):([12]),([DFPRST]*)$}
153     [($1 || fn), ($2 || "2"), ($3 || "")]
154   end
155
156   ## not thread-safe on msg
157   def maildir_mark_file msg, flag
158     orig_path = @ids_to_fns[msg]
159     orig_base, orig_fn = File.split(orig_path)
160     new_base = orig_base.slice(0..-4) + 'cur'
161     tmp_base = orig_base.slice(0..-4) + 'tmp'
162     md_base, md_ver, md_flags = maildir_data msg
163     md_flags += flag; md_flags = md_flags.split(//).sort.join.squeeze
164     new_path = File.join new_base, "#{md_base}:#{md_ver},#{md_flags}"
165     tmp_path = File.join tmp_base, "#{md_base}:#{md_ver},#{md_flags}"
166     File.link orig_path, tmp_path
167     File.unlink orig_path
168     File.link tmp_path, new_path
169     File.unlink tmp_path
170     @ids_to_fns[msg] = new_path
171   end
172 end
173
174 end