removed Message.Envelope class
[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     private static final char slash = File.separatorChar;
19     private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
20     public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
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 = Math.abs(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             long time = System.currentTimeMillis();
59             Log.info(this, "initializing maildir " + dir.getParent());
60
61             // Drop entries whose files have vanished
62             ArrayList<Transaction> kill = new ArrayList<Transaction>();
63             for(String s : byname.keySet())
64                 if (!new File(dir.getParent() + slash + s).exists())
65                     kill.add(byname.get(s).delete(null));
66             for(Transaction t : kill) prevayler.execute(t);
67
68             // Make entries for new files which have appeared
69             for(String file : new File(dir.getParent()).list()) {
70                 File f = new File(dir.getParent() + slash + file);
71                 if (file.charAt(0)!='.' && !f.isDirectory()) {
72                     Entry e = get(file);
73                     if (e == null)
74                         prevayler.execute(Entry.create(f));
75                     else if ((f.lastModified() == MAGIC_DATE) != e.seen())
76                         prevayler.execute(e.seen(f, !e.seen()));
77                 }
78             }
79
80             // Take a snapshot for posterity
81             if (System.currentTimeMillis() - time > 1000 * 5)
82                 Log.info(this, "  done initializing maildir " + dir.getParent());
83             new Thread() { public void run() {
84                 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); } } }.start();
85         }
86
87        
88         public synchronized int size() { return linear.size(); }
89         public synchronized int uidNext() { return uidNext; }
90         public synchronized Entry get(int uid) { return byuid.get(uid); }
91         public synchronized Entry getLinear(int num) { return linear.get(num); }
92         public synchronized Entry get(String name) { return byname.get(name); }
93
94         public static class Entry implements Serializable {
95             private final byte[] header;
96             public final String name;
97             public final int uid;
98             private boolean seen;
99             private Entry(String name, boolean seen, int uid, byte[] header) {
100                 this.name = name; this.seen = seen; this.uid = uid; this.header = header; }
101
102             // Accessors //////////////////////////////////////////////////////////////////////////////
103
104             public boolean seen() { return seen; }
105             public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
106             public Message message(Cache cache) { try {
107                 FileInputStream fis = null;
108                 try {
109                     fis = new FileInputStream(cache.dir.getParent() + slash + name);
110                     return Message.newMessage(new Stream(fis));
111                 } finally { if (fis != null) fis.close(); }
112             } catch (IOException e) { throw new MailException.IOException(e);
113             } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
114             }
115
116             // Transactions //////////////////////////////////////////////////////////////////////////////
117
118             public static Transaction create(File f) throws IOException {
119                 final boolean seen = f.lastModified() == MAGIC_DATE;
120                 final String name = f.getName();
121                 final byte[] header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
122                 return new Transaction() {
123                         public void executeOn(Object o, Date now) {
124                             Cache cache = (Cache)o;
125                             synchronized(cache) {
126                                 Entry e = new Entry(name, seen, cache.uidNext++, header);
127                                 cache.linear.add(e);
128                                 cache.byuid.put(e.uid, e);
129                                 cache.byname.put(e.name, e);
130                             } } };
131             }
132
133             public Transaction seen(File f, final boolean seen) {
134                 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
135                 final int uid = this.uid;
136                 return new Transaction() {
137                         public void executeOn(Object o, Date now) {
138                             Cache cache = (Cache)o;
139                             synchronized(cache) {
140                                 cache.get(uid).seen = seen;
141                             } } };
142             }
143             public Transaction delete(File f) {
144                 if (f != null && f.exists()) f.delete();
145                 final int uid = this.uid;
146                 return new Transaction() {
147                         public void executeOn(Object o, Date now) {
148                             Cache cache = (Cache)o;
149                             synchronized(cache) {
150                                 Cache.Entry e = cache.get(uid);
151                                 cache.byname.remove(e.name);
152                                 cache.linear.remove(e);
153                                 cache.byuid.remove(uid);
154                             } } };
155             }
156         }
157     }
158
159     // Helpers //////////////////////////////////////////////////////////////////////////////
160
161     private static void rmDashRf(File f) throws IOException {
162         if (!f.isDirectory()) { f.delete(); return; }
163         String[] children = f.list();
164         for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
165         f.delete();
166     }
167
168     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
169         this.path = path;
170         path.mkdirs();
171
172         // acquire lock
173         lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
174         if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
175
176         File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
177         try {
178             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
179             cache = (Cache)prevayler.prevalentSystem();
180         } catch (Throwable t) {
181             Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
182             Log.warn(this, t);
183             Log.warn(this, "discarding cache...");
184             rmDashRf(cacheDir);
185             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
186             cache = (Cache)prevayler.prevalentSystem();
187         }
188         cache.init(prevayler);
189     }
190
191
192     public Mailbox.Iterator  iterator()           { return new Iterator(); }
193     public int               uidValidity()        { return cache.uidValidity; }
194     public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
195     public String[] children() {
196         Vec vec = new Vec();
197         String[] list = path.list();
198         for(int i=0; i<list.length; i++) {
199             File f = new File(path.getAbsolutePath() + slash + list[i]);
200             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
201         }
202         return (String[])vec.copyInto(new String[vec.size()]);
203     }
204
205     public int uidNext() { return cache.uidNext(); }
206     public synchronized void add(Message message, int flags) {
207         try {
208             String name, fullname; File target, f;
209             for(int i = cache.uidNext(); ; i++) {
210                 name = i + ".";
211                 fullname = path.getAbsolutePath() + slash + name;
212                 target = new File(fullname);
213                 f = new File(target.getCanonicalPath() + "-");
214                 if (!f.exists() && !target.exists()) break;
215                 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
216             }
217             FileOutputStream fo = new FileOutputStream(f);
218             Stream stream = new Stream(fo);
219             message.dump(stream);
220             fo.close();
221             f.renameTo(new File(fullname));
222             f = new File(fullname);
223             if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
224             prevayler.execute(Cache.Entry.create(f));
225         } catch (IOException e) { throw new MailException.IOException(e); }
226         Log.info(this, path + " <= " + message.summary());
227     }
228
229     private class Iterator extends Mailbox.Default.Iterator {
230         int cur = -1;
231         private Cache.Entry entry() { return cache.getLinear(cur); }
232         private File file() { return new File(cache.dir.getParent() + slash + entry().name); }
233         public MIME.Headers head() { return done() ? null : entry().headers(); }
234         public boolean done() { return cur >= cache.size(); }
235         public boolean next() { cur++; return !done(); }
236         public boolean seen() { return done() ? false : entry().seen(); }
237         public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
238         public int uid() { return done() ? -1 : entry().uid; }
239         public void delete() { prevayler.execute(entry().delete(file())); }
240         public void seen(boolean seen) { prevayler.execute(entry().seen(file(), seen)); }
241         public Message cur() { return entry().message(cache); }
242     }
243
244 }