change seen within a transaction in FileBasedMailbox
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
index b9450be..4322673 100644 (file)
@@ -13,6 +13,8 @@ import java.text.*;
 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
 public class FileBasedMailbox extends Mailbox.Default {
 
+    public static final long MAGIC_DATE = 0;
+
     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>();
@@ -44,49 +46,67 @@ public class FileBasedMailbox extends Mailbox.Default {
     public static class Cache implements Serializable {
         public            final int uidValidity = new Random().nextInt();
         private           final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
-        private transient final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,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(Prevayler prevayler) throws IOException {
+        public void init(final Prevayler prevayler) throws IOException {
             dir.mkdirs();
-            Log.info(this, "initializing maildir " + dir.getAbsolutePath());
+            Log.info(this, "initializing maildir " + dir.getParent());
             boolean invalid = false;
-            for(String s : byname.keySet()) create(prevayler, s);
+            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()));
+                }
+            }
+            for(Transaction t : kill) prevayler.execute(t);
             for(String file : new File(dir.getParent()).list())
-                if (file.charAt(0)!='.' && !(new File(dir.getAbsolutePath() + slash + file).isDirectory()))
-                    create(prevayler, file);
-            Log.info(this, "  done initializing maildir " + dir.getAbsolutePath());
-            prevayler.takeSnapshot();
-        }
-
-        public synchronized void create(Prevayler prevayler, String name) throws IOException {
-            if (get(name) != null) return;
-            new Entry(this, prevayler, name);
+                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 byname.size(); }
+       
+        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 get(String name) { return byname.get(name); }
+        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 {
-            public final MIME.Headers headers;
+            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 {
-                seen = name.endsWith(".s");
-                this.name = seen ? name.substring(0, name.length() - 2) : name;
-                headers = new MIME.Headers(new Stream(new FileInputStream(cache.dir.getAbsolutePath()+slash+name)), true);
+                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);
                             } } });
@@ -95,21 +115,21 @@ public class FileBasedMailbox extends Mailbox.Default {
             public int uid() { return uid; }
             public boolean seen() { return seen; }
             public void seen(Cache cache, boolean seen) {
-                String base = cache.dir.getAbsolutePath() + slash + name;
-                File target = new File(base + (seen?".s":""));
-                if (target.exists()) return;
-                new File(base + (seen?"":".s")).renameTo(target);
+                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.getAbsolutePath() + slash + name;
+                String base = cache.dir.getParent() + slash + name;
                 File target = new File(base);
-                if (!target.exists()) target = new File(base + ".s");
+                if (!target.exists()) target = new File(base + "s");
                 if (target.exists()) target.delete();
             }
             public Message message(Cache cache) { try {
-                String base = cache.dir.getAbsolutePath() + slash + name;
+                String base = cache.dir.getParent() + slash + name;
                 File target = new File(base);
-                if (!target.exists()) target = new File(base + ".s");
+                if (!target.exists()) target = new File(base + "s");
                 FileInputStream fis = null;
                 try {
                     fis = new FileInputStream(target);
@@ -169,12 +189,15 @@ public class FileBasedMailbox extends Mailbox.Default {
     public synchronized void add(Message message, int flags) {
         Log.info(path, message.summary());
         try {
-           final String name = path.getAbsolutePath() + slash + cache.uidNext(true) + "." +
-                ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN ? "s" : "");
-            File target = new File(name);
-            File f = new File(target.getCanonicalPath() + "-");
-            if (f.exists() || target.exists())
-                throw new RuntimeException("aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
+            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);
             Stream stream = new Stream(fo);
             if (message.envelope != null) {
@@ -183,34 +206,47 @@ public class FileBasedMailbox extends Mailbox.Default {
             }
             message.dump(stream);
             fo.close();
-            f.renameTo(new File(name));
+            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 implements Serializable {
+    private class Iterator extends Mailbox.Default.Iterator {
         int cur = -1;
-        private Cache.Entry entry() { return cache.get(cur); }
-        public MIME.Headers head() { return done() ? null : entry().headers; }
+        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(final boolean seen) {
-            if (done()) return;
-            final int cur = this.cur;
-            prevayler.execute(new Transaction() {
-                    public void executeOn(Object c, Date d) {
-                        ((Cache)c).get(cur).seen((Cache)c, seen); } });
+        public void seen(boolean seen) {
+            entry().seen((Cache)prevayler.prevalentSystem(), seen);
+            prevayler.execute(new Seen(uid(), seen));
         }
         public void delete() {
-            if (done()) return;
-            final int cur = this.cur;
-            prevayler.execute(new Transaction() {
-                    public void executeOn(Object c, Date d) {
-                        ((Cache)c).get(cur).delete((Cache)c); } });
-       }
+            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);
+        } 
     }
 }