change seen within a transaction in FileBasedMailbox
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
index 7e3f3a0..4322673 100644 (file)
 package org.ibex.mail.target;
+import org.prevayler.*;
 import org.ibex.mail.*;
 import org.ibex.util.*;
-import org.ibex.mail.*;
+import org.ibex.io.*;
 import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
 import java.net.*;
 import java.util.*;
 import java.text.*;
 
-// FIXME: uids and messagenums are all messed up
+/** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
+public class FileBasedMailbox extends Mailbox.Default {
 
-public class FileBasedMailbox extends Mailbox {
+    public static final long MAGIC_DATE = 0;
 
-    private String path;
-    public FileBasedMailbox(String path) throws MailException { new File(this.path = path).mkdirs(); }
-    public Mailbox slash(String name, boolean create) throws MailException { return new FileBasedMailbox(path + "/" + name); }
+    public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
+    private static final char slash = File.separatorChar;
+    private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
+    public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
 
-    // FIXME
-    public String getName() { return "FOO"; }
-    
-    protected synchronized void flags(Message m, int newFlags) throws MailException {
+    // FIXME: should be a File()
+    public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
         try {
-            File f = new File(messageToFile(m).getCanonicalPath() + ".flags");
-            PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f)));
-            if ((newFlags & Flag.DELETED) != 0)  pw.print("\\Deleted ");
-            if ((newFlags & Flag.SEEN) != 0)     pw.print("\\Seen ");
-            if ((newFlags & Flag.FLAGGED) != 0)  pw.print("\\Flagged ");
-            if ((newFlags & Flag.DRAFT) != 0)    pw.print("\\Draft ");
-            if ((newFlags & Flag.ANSWERED) != 0) pw.print("\\Answered ");
-            if ((newFlags & Flag.RECENT) != 0)   pw.print("\\Recent ");
-            pw.close();
-        } catch (IOException e) { throw new MailException.IOException(e); }
+            FileBasedMailbox ret = instances.get(path);
+            if (ret == null) {
+                if (!create && !(new File(path).exists())) return null;
+                instances.put(path, ret = new FileBasedMailbox(new File(path)));
+            }
+            return ret;
+        } catch (Exception e) {
+            Log.error(FileBasedMailbox.class, e);
+            return null;
+        }
     }
 
-    protected synchronized int flags(Message m) {
-        try {
-            File f = new File(messageToFile(m).getCanonicalPath() + ".flags");
-            if (!f.exists()) return 0;
-            String s = new BufferedReader(new InputStreamReader(new FileInputStream(f))).readLine();
-            StringTokenizer st = new StringTokenizer(s);
-            int ret = 0;
-            while(st.hasMoreTokens()) {
-                String s2 = st.nextToken();
-                if (s2.equals("\\Deleted")) ret |= Flag.DELETED;
-                if (s2.equals("\\Seen")) ret |= Flag.SEEN;
-                if (s2.equals("\\Flagged")) ret |= Flag.FLAGGED;
-                if (s2.equals("\\Draft")) ret |= Flag.DRAFT;
-                if (s2.equals("\\Answered")) ret |= Flag.ANSWERED;
-                if (s2.equals("\\Recent")) ret |= Flag.RECENT;
+
+    // Instance //////////////////////////////////////////////////////////////////////////////
+
+    private File path;
+    private FileLock lock;
+    private Prevayler prevayler;
+    private Cache cache;
+
+    public static class Cache implements Serializable {
+        public            final int uidValidity = new Random().nextInt();
+        private           final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
+        private           final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
+        private           final ArrayList<Entry>        linear = new ArrayList<Entry>();
+        public            final File dir;
+        private                 int uidNext = 0;
+
+        public Cache(File dir) { this.dir = dir; }
+
+        public void init(final Prevayler prevayler) throws IOException {
+            dir.mkdirs();
+            Log.info(this, "initializing maildir " + dir.getParent());
+            boolean invalid = false;
+            ArrayList<Transaction> kill = new ArrayList<Transaction>();
+            for(String s : byname.keySet()) {
+                String name = dir.getParent() + slash + s;
+                if (!new File(name).exists() && !new File(name+"s").exists()) {
+                    Log.error(this, "dropping message " + name);
+                    kill.add(new Drop(byname.get(s).uid()));
+                }
             }
-            return ret;
-        } catch (IOException e) { throw new MailException.IOException(e); }
+            for(Transaction t : kill) prevayler.execute(t);
+            for(String file : new File(dir.getParent()).list())
+                if (file.charAt(0)!='.' && !(new File(dir.getParent() + slash + file).isDirectory())) {
+                    if (get(file) == null) new Entry(this, prevayler, file);
+                    else if ((new File(dir.getParent() + slash + file).lastModified() == MAGIC_DATE) != get(file).seen())
+                        prevayler.execute(new Seen(get(file).uid(), !get(file).seen()));
+                }
+            Log.info(this, "  done initializing maildir " + dir.getParent());
+            new Thread() { public void run() {
+                try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); }
+            } }.start();
+        }
+
+       
+        public synchronized int size() { return linear.size(); }
+        public synchronized int uidNext(boolean increment) { return increment ? uidNext++ : uidNext; }
+        public synchronized Entry get(int uid) { return byuid.get(uid); }
+        public synchronized Entry getLinear(int num) { return linear.get(num); }
+        public synchronized Entry get(String name) {
+            if (name.endsWith("s")) name = name.substring(0, name.length() - 1);
+            return byname.get(name);
+        }
+
+        public static class Entry implements Serializable {
+            private final byte[] header;
+            public final String name;
+            private int uid;
+            private boolean seen;
+            
+            public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
+            public Entry(Cache cache, Prevayler prevayler, String name) throws IOException {
+                File f = new File(cache.dir.getParent()+slash+name);
+                final boolean seen = f.lastModified() == MAGIC_DATE;
+                this.name = name;
+                header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
+                prevayler.execute(new Transaction() {
+                        public void executeOn(Object o, Date now) {
+                            Cache cache = (Cache)o;
+                            synchronized(cache) {
+                                Entry.this.seen = seen;
+                                Entry.this.uid = cache.uidNext(true);
+                                cache.linear.add(Entry.this);
+                                cache.byuid.put(Entry.this.uid, Entry.this);
+                                cache.byname.put(Entry.this.name, Entry.this);
+                            } } });
+            }
+
+            public int uid() { return uid; }
+            public boolean seen() { return seen; }
+            public void seen(Cache cache, boolean seen) {
+                String base = cache.dir.getParent() + slash + name;
+                File target = new File(base);
+                if (!target.exists()) target = new File(base + "s");
+                target.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
+            }
+            public void delete(Cache cache) {
+                String base = cache.dir.getParent() + slash + name;
+                File target = new File(base);
+                if (!target.exists()) target = new File(base + "s");
+                if (target.exists()) target.delete();
+            }
+            public Message message(Cache cache) { try {
+                String base = cache.dir.getParent() + slash + name;
+                File target = new File(base);
+                if (!target.exists()) target = new File(base + "s");
+                FileInputStream fis = null;
+                try {
+                    fis = new FileInputStream(target);
+                    return new Message(new Stream(fis), new Message.Envelope(null, null, new Date(target.lastModified())));
+                } finally { if (fis != null) fis.close(); }
+            } catch (IOException e) { throw new MailException.IOException(e);
+            } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
+            }
+        }
     }
 
-    private int uidNext = 0;
-    public int uidNext() { return uidNext; }
-    public int uidValidity() { return 1; }
-    public int uid(Message m) { Integer i = (Integer)uidMap.get(m); if (i == null) return -1; return i.intValue(); }
-    public int num(Message m) { Integer i = (Integer)numMap.get(m); if (i == null) return -1; return i.intValue(); }
-    private File messageToFile(Message message) { return new File(path + File.separatorChar +  num(message) + "."); }
-
-    public int delete(Message message) throws MailException {
-        messageToFile(message).delete();
-        uidMap.remove(message);
-        numMap.remove(message);
-        return -1;
+    private static void rmDashRf(File f) throws IOException {
+        if (!f.isDirectory()) { f.delete(); return; }
+        String[] children = f.list();
+        for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
+        f.delete();
     }
 
-    public Mailbox.Iterator iterator() { return new FileBasedMailbox.Iterator(); }
-    private class Iterator extends Mailbox.Iterator {
-        private String[] names;
-        public Iterator() { names = new File(path).list(); }
-        public Message cur() { return null; }
-        public boolean next() { return false; }
-        protected  int  flags() { return 0; }
-        protected  void flags(int newFlags) { }
-        public  int  uid() { return -1; }
-        public  int  num() { return -1; }
-        public  void delete() { }
-
-        /*
-            try {
-                //= Integer.parseInt(names[i].substring(0, names[i].length() - 1));
-                // FIXME
-            } catch (NumberFormatException nfe) {
-                Log.warn(FileBasedMailbox.class, "NumberFormatException: " + names[i].substring(0, names[i].length() - 1));
-                j--;
-                int[] newret = new int[ret.length - 1];
-                System.arraycopy(ret, 0, newret, 0, newret.length);
-                ret = newret;
-            }
+    private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
+        this.path = path;
+        path.mkdirs();
+
+        // acquire lock
+        lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
+        if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
+
+        File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
+        try {
+            prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
+            cache = (Cache)prevayler.prevalentSystem();
+        } catch (Throwable t) {
+            Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
+            Log.warn(this, t);
+            Log.warn(this, "discarding cache...");
+            rmDashRf(cacheDir);
+            prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
+            cache = (Cache)prevayler.prevalentSystem();
         }
-        */
+        cache.init(prevayler);
     }
 
-    private Hashtable uidMap = new Hashtable();
-    private Hashtable numMap = new Hashtable();
-    private int numNext = 0;
 
-    public synchronized int add(Message message) throws MailException {
+    public Mailbox.Iterator  iterator()           { return new Iterator(); }
+    public int               uidValidity()        { return cache.uidValidity; }
+    public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
+    public String[] children() {
+        Vec vec = new Vec();
+        String[] list = path.list();
+        for(int i=0; i<list.length; i++) {
+            File f = new File(path.getAbsolutePath() + slash + list[i]);
+            if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
+        }
+        return (String[])vec.copyInto(new String[vec.size()]);
+    }
+
+    public int uidNext() { return cache.uidNext(false); }
+    public synchronized void add(Message message, int flags) {
+        Log.info(path, message.summary());
         try {
-            File target = messageToFile(message);
-            File f = new File(target.getCanonicalPath() + ".-");
+            String name; String fullname; File target; File f;
+            while(true) {
+                name = cache.uidNext(true) + ".";
+                fullname = path.getAbsolutePath() + slash + name;
+                target = new File(fullname);
+                f = new File(target.getCanonicalPath() + "-");
+                if (!f.exists() && !target.exists()) break;
+                Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
+            }
             FileOutputStream fo = new FileOutputStream(f);
-            message.dump(fo);
+            Stream stream = new Stream(fo);
+            if (message.envelope != null) {
+                stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
+                stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
+            }
+            message.dump(stream);
             fo.close();
-            f.renameTo(target);
-            uidMap.put(new Integer(uidNext++), message);
-            numMap.put(new Integer(numNext++), message);
-            return numNext - 1;
+            f.renameTo(new File(fullname));
+            if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
+            new Cache.Entry(cache, prevayler, name);
         } catch (IOException e) { throw new MailException.IOException(e); }
     }
 
+    private class Iterator extends Mailbox.Default.Iterator {
+        int cur = -1;
+        private Cache.Entry entry() { return cache.getLinear(cur); }
+        public MIME.Headers head() { return done() ? null : entry().headers(); }
+        public boolean done() { return cur >= cache.size(); }
+        public boolean next() { cur++; return !done(); }
+        public boolean seen() { return done() ? false : entry().seen(); }
+        public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
+        public int uid() { return done() ? -1 : entry().uid(); }
+        public Message cur() { return done() ? null : entry().message(cache); }
+        public void seen(boolean seen) {
+            entry().seen((Cache)prevayler.prevalentSystem(), seen);
+            prevayler.execute(new Seen(uid(), seen));
+        }
+        public void delete() {
+            entry().delete((Cache)prevayler.prevalentSystem());
+            prevayler.execute(new Drop(entry().uid()));
+        }
+    }
+
+    private static class Seen implements Transaction {
+        private int uid;
+        private boolean seen;
+        public Seen(int uid, boolean seen) { this.uid = uid; this.seen = seen; }
+        public void executeOn(Object c, Date d) { ((Cache)c).get(uid).seen = seen; }
+    }
+    public static class Drop implements Transaction {
+        int uid;
+        public Drop(int uid) { this.uid = uid; }
+        public void executeOn(Object o, Date now) {
+            Cache c = (Cache)o;
+            Cache.Entry e = c.get(uid);
+            c.byname.remove(e.name);
+            c.linear.remove(e);
+            c.byuid.remove(uid);
+        } 
+    }
 }