change seen within a transaction in FileBasedMailbox
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
1 package org.ibex.mail.target;
2 import org.prevayler.*;
3 import org.ibex.mail.*;
4 import org.ibex.util.*;
5 import org.ibex.io.*;
6 import java.io.*;
7 import java.nio.*;
8 import java.nio.channels.*;
9 import java.net.*;
10 import java.util.*;
11 import java.text.*;
12
13 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
14 public class FileBasedMailbox extends Mailbox.Default {
15
16     public static final long MAGIC_DATE = 0;
17
18     public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
19     private static final char slash = File.separatorChar;
20     private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
21     public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
22
23     // FIXME: should be a File()
24     public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
25         try {
26             FileBasedMailbox ret = instances.get(path);
27             if (ret == null) {
28                 if (!create && !(new File(path).exists())) return null;
29                 instances.put(path, ret = new FileBasedMailbox(new File(path)));
30             }
31             return ret;
32         } catch (Exception e) {
33             Log.error(FileBasedMailbox.class, e);
34             return null;
35         }
36     }
37
38
39     // Instance //////////////////////////////////////////////////////////////////////////////
40
41     private File path;
42     private FileLock lock;
43     private Prevayler prevayler;
44     private Cache cache;
45
46     public static class Cache implements Serializable {
47         public            final int uidValidity = new Random().nextInt();
48         private           final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
49         private           final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
50         private           final ArrayList<Entry>        linear = new ArrayList<Entry>();
51         public            final File dir;
52         private                 int uidNext = 0;
53
54         public Cache(File dir) { this.dir = dir; }
55
56         public void init(final Prevayler prevayler) throws IOException {
57             dir.mkdirs();
58             Log.info(this, "initializing maildir " + dir.getParent());
59             boolean invalid = false;
60             ArrayList<Transaction> kill = new ArrayList<Transaction>();
61             for(String s : byname.keySet()) {
62                 String name = dir.getParent() + slash + s;
63                 if (!new File(name).exists() && !new File(name+"s").exists()) {
64                     Log.error(this, "dropping message " + name);
65                     kill.add(new Drop(byname.get(s).uid()));
66                 }
67             }
68             for(Transaction t : kill) prevayler.execute(t);
69             for(String file : new File(dir.getParent()).list())
70                 if (file.charAt(0)!='.' && !(new File(dir.getParent() + slash + file).isDirectory())) {
71                     if (get(file) == null) new Entry(this, prevayler, file);
72                     else if ((new File(dir.getParent() + slash + file).lastModified() == MAGIC_DATE) != get(file).seen())
73                         prevayler.execute(new Seen(get(file).uid(), !get(file).seen()));
74                 }
75             Log.info(this, "  done initializing maildir " + dir.getParent());
76             new Thread() { public void run() {
77                 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); }
78             } }.start();
79         }
80
81        
82         public synchronized int size() { return linear.size(); }
83         public synchronized int uidNext(boolean increment) { return increment ? uidNext++ : uidNext; }
84         public synchronized Entry get(int uid) { return byuid.get(uid); }
85         public synchronized Entry getLinear(int num) { return linear.get(num); }
86         public synchronized Entry get(String name) {
87             if (name.endsWith("s")) name = name.substring(0, name.length() - 1);
88             return byname.get(name);
89         }
90
91         public static class Entry implements Serializable {
92             private final byte[] header;
93             public final String name;
94             private int uid;
95             private boolean seen;
96             
97             public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
98             public Entry(Cache cache, Prevayler prevayler, String name) throws IOException {
99                 File f = new File(cache.dir.getParent()+slash+name);
100                 final boolean seen = f.lastModified() == MAGIC_DATE;
101                 this.name = name;
102                 header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
103                 prevayler.execute(new Transaction() {
104                         public void executeOn(Object o, Date now) {
105                             Cache cache = (Cache)o;
106                             synchronized(cache) {
107                                 Entry.this.seen = seen;
108                                 Entry.this.uid = cache.uidNext(true);
109                                 cache.linear.add(Entry.this);
110                                 cache.byuid.put(Entry.this.uid, Entry.this);
111                                 cache.byname.put(Entry.this.name, Entry.this);
112                             } } });
113             }
114
115             public int uid() { return uid; }
116             public boolean seen() { return seen; }
117             public void seen(Cache cache, boolean seen) {
118                 String base = cache.dir.getParent() + slash + name;
119                 File target = new File(base);
120                 if (!target.exists()) target = new File(base + "s");
121                 target.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
122             }
123             public void delete(Cache cache) {
124                 String base = cache.dir.getParent() + slash + name;
125                 File target = new File(base);
126                 if (!target.exists()) target = new File(base + "s");
127                 if (target.exists()) target.delete();
128             }
129             public Message message(Cache cache) { try {
130                 String base = cache.dir.getParent() + slash + name;
131                 File target = new File(base);
132                 if (!target.exists()) target = new File(base + "s");
133                 FileInputStream fis = null;
134                 try {
135                     fis = new FileInputStream(target);
136                     return new Message(new Stream(fis), new Message.Envelope(null, null, new Date(target.lastModified())));
137                 } finally { if (fis != null) fis.close(); }
138             } catch (IOException e) { throw new MailException.IOException(e);
139             } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
140             }
141         }
142     }
143
144     private static void rmDashRf(File f) throws IOException {
145         if (!f.isDirectory()) { f.delete(); return; }
146         String[] children = f.list();
147         for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
148         f.delete();
149     }
150
151     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
152         this.path = path;
153         path.mkdirs();
154
155         // acquire lock
156         lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
157         if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
158
159         File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
160         try {
161             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
162             cache = (Cache)prevayler.prevalentSystem();
163         } catch (Throwable t) {
164             Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
165             Log.warn(this, t);
166             Log.warn(this, "discarding cache...");
167             rmDashRf(cacheDir);
168             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
169             cache = (Cache)prevayler.prevalentSystem();
170         }
171         cache.init(prevayler);
172     }
173
174
175     public Mailbox.Iterator  iterator()           { return new Iterator(); }
176     public int               uidValidity()        { return cache.uidValidity; }
177     public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
178     public String[] children() {
179         Vec vec = new Vec();
180         String[] list = path.list();
181         for(int i=0; i<list.length; i++) {
182             File f = new File(path.getAbsolutePath() + slash + list[i]);
183             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
184         }
185         return (String[])vec.copyInto(new String[vec.size()]);
186     }
187
188     public int uidNext() { return cache.uidNext(false); }
189     public synchronized void add(Message message, int flags) {
190         Log.info(path, message.summary());
191         try {
192             String name; String fullname; File target; File f;
193             while(true) {
194                 name = cache.uidNext(true) + ".";
195                 fullname = path.getAbsolutePath() + slash + name;
196                 target = new File(fullname);
197                 f = new File(target.getCanonicalPath() + "-");
198                 if (!f.exists() && !target.exists()) break;
199                 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
200             }
201             FileOutputStream fo = new FileOutputStream(f);
202             Stream stream = new Stream(fo);
203             if (message.envelope != null) {
204                 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
205                 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
206             }
207             message.dump(stream);
208             fo.close();
209             f.renameTo(new File(fullname));
210             if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
211             new Cache.Entry(cache, prevayler, name);
212         } catch (IOException e) { throw new MailException.IOException(e); }
213     }
214
215     private class Iterator extends Mailbox.Default.Iterator {
216         int cur = -1;
217         private Cache.Entry entry() { return cache.getLinear(cur); }
218         public MIME.Headers head() { return done() ? null : entry().headers(); }
219         public boolean done() { return cur >= cache.size(); }
220         public boolean next() { cur++; return !done(); }
221         public boolean seen() { return done() ? false : entry().seen(); }
222         public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
223         public int uid() { return done() ? -1 : entry().uid(); }
224         public Message cur() { return done() ? null : entry().message(cache); }
225         public void seen(boolean seen) {
226             entry().seen((Cache)prevayler.prevalentSystem(), seen);
227             prevayler.execute(new Seen(uid(), seen));
228         }
229         public void delete() {
230             entry().delete((Cache)prevayler.prevalentSystem());
231             prevayler.execute(new Drop(entry().uid()));
232         }
233     }
234
235     private static class Seen implements Transaction {
236         private int uid;
237         private boolean seen;
238         public Seen(int uid, boolean seen) { this.uid = uid; this.seen = seen; }
239         public void executeOn(Object c, Date d) { ((Cache)c).get(uid).seen = seen; }
240     }
241     public static class Drop implements Transaction {
242         int uid;
243         public Drop(int uid) { this.uid = uid; }
244         public void executeOn(Object o, Date now) {
245             Cache c = (Cache)o;
246             Cache.Entry e = c.get(uid);
247             c.byname.remove(e.name);
248             c.linear.remove(e);
249             c.byuid.remove(uid);
250         } 
251     }
252 }