total overhaul; were using MIME and MIME.Part now
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
1 package org.ibex.mail.target;
2 import org.ibex.mail.*;
3 import org.ibex.util.*;
4 import org.ibex.io.*;
5 import java.io.*;
6 import java.net.*;
7 import java.util.*;
8 import java.text.*;
9
10 // FIXME: we can omit UIDNEXT!
11 // FIXME use directory date/time as UIDNEXT and file date/time as UID; need to 'correct' file date/time after changes
12
13 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
14 public class FileBasedMailbox extends Mailbox.Default {
15
16     public String toString() { return "[FileBasedMailbox " + path + "]"; }
17
18     private static final char slash = File.separatorChar;
19     private static final Hashtable instances = new Hashtable();
20     public static FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
21         FileBasedMailbox ret = (FileBasedMailbox)instances.get(path);
22         if (ret != null) return ret;
23         File f = new File(path);
24         if (!create && !f.exists()) return null;
25         instances.put(path, ret = new FileBasedMailbox(path));
26         return ret;
27     }
28
29     public static final FilenameFilter filter = new FilenameFilter() {
30             public boolean accept(File f, String s) {
31                 return s.indexOf('.') != -1;
32             } };
33
34
35     // Instance //////////////////////////////////////////////////////////////////////////////
36
37     private String path;
38     private File uidNext;
39     private FileBasedMailbox(String path) throws MailException {
40         new File(this.path = path).mkdirs();
41         uidNext(false);
42     }
43
44     public Mailbox          slash(String name, boolean create) {
45         return FileBasedMailbox.getFileBasedMailbox(path + slash + name, create); }
46
47     public String[] children() {
48         Vec vec = new Vec();
49         String[] list = new File(path).list();
50         for(int i=0; i<list.length; i++) {
51             if (!(new File(path + slash + list[i]).isDirectory())) continue;
52             vec.addElement(list[i]);
53         }
54         String[] ret = new String[vec.size()];
55         vec.copyInto(ret);
56         return ret;
57     }
58
59     public Mailbox.Iterator iterator() { return new FileBasedMailbox.Iterator(); }
60     public int              uidValidity() { return (int)(new File(path).lastModified() & 0xffffffL); }
61
62     public int uidNext() { return uidNext(false); }
63     public int uidNext(boolean inc) {
64         try {
65             uidNext = new File(path + slash + "UIDNEXT");
66             if (!uidNext.exists()) {
67                 File tmp = new File(uidNext + "-");
68                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tmp)));
69                 pw.println("1");
70                 pw.flush();
71                 pw.close();
72                 tmp.renameTo(uidNext);
73                 return 1;
74             }
75             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(uidNext)));
76             int ret = Integer.parseInt(br.readLine());
77             br.close();
78             if (inc) {
79                 File tmp = new File(uidNext + "-");
80                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tmp)));
81                 pw.println(ret+1);
82                 pw.flush();
83                 pw.close();
84                 tmp.renameTo(uidNext);
85             }
86             return ret;
87         } catch (IOException e) { throw new MailException.IOException(e); }
88     }        
89
90     public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
91     public synchronized void add(Message message, int flags) {
92         Log.info(this, "adding message to ["+toString()+"]:\n" + message.summary());
93         try {
94             int num = new File(path).list(filter).length;
95             String name = path + slash + uidNext(true) + "." +
96                 ((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED ? "x" : "") +
97                 ((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT ? "d" : "") +
98                 ((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT ? "r" : "") +
99                 ((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED ? "a" : "") +
100                 ((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED ? "f" : "") +
101                 ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN ? "s" : "");
102             Log.info(this, "    with chosen filename " + name);
103             File target = new File(name);
104             File f = new File(target.getCanonicalPath() + "-");
105             FileOutputStream fo = new FileOutputStream(f);
106             Stream stream = new Stream(fo);
107             stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
108             stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
109             message.dump(stream);
110             fo.close();
111             f.renameTo(target);
112             Log.info(this, "    done writing.");
113         } catch (IOException e) { throw new MailException.IOException(e); }
114     }
115
116     private class Iterator extends Mailbox.Default.Iterator {
117         int cur = -1;
118         private String[] names;
119         private boolean seen = false, deleted = false, draft = false, flagged = false, answered = false, recent = false;
120         public Iterator() { names = new File(path).list(filter); }
121
122         public Message head() { return cur(); }
123         public Message cur() {
124             if (cur >= names.length) return null;
125             try {
126                 File file = new File(path + File.separatorChar + names[cur]);
127                 FileInputStream fis = new FileInputStream(file);
128                 Stream stream = new Stream(fis);
129                 Address envelopeFrom = null;
130                 Address envelopeTo = null;
131                 for(String s = stream.readln(); s != null; s = stream.readln()) {
132                     if (s.startsWith("X-org.ibex.mail.headers.envelope.From: "))
133                         envelopeFrom = Address.parse(s.substring(38).trim());
134                     else if (s.startsWith("X-org.ibex.mail.headers.envelope.To: "))
135                         envelopeTo = Address.parse(s.substring(36).trim());
136                     else {
137                         stream.unread(s + "\r\n");
138                         break;
139                     }
140                 }
141                 Message ret = new Message(stream,
142                                           new Message.Envelope(envelopeFrom, envelopeTo, new Date(file.lastModified())));
143                 fis.close();
144                 return ret;
145             } catch (IOException e) { throw new MailException.IOException(e);
146             } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
147         }
148         public boolean next() {
149             cur++;
150             if (cur >= names.length) return false;
151             String name = names[cur].substring(names[cur].indexOf('.') + 1);
152             if (!(new File(path + File.separatorChar + names[cur])).exists()) return next();
153             seen     = name.indexOf('s') != -1;
154             deleted  = name.indexOf('x') != -1;
155             flagged  = name.indexOf('f') != -1;
156             draft    = name.indexOf('d') != -1;
157             answered = name.indexOf('a') != -1;
158             recent   = name.indexOf('r') != -1;
159             return true;
160         }
161         public int num() { return cur; }
162         public int uid() {
163             try { return Integer.parseInt(names[cur].substring(0, names[cur].indexOf('.')));
164             } catch (NumberFormatException nfe) {
165                 Log.warn(FileBasedMailbox.class, "NumberFormatException: " + names[cur].substring(0, names[cur].length() - 1));
166                 return -1; } }
167
168         private void fixflags() {
169             String newName =
170                 names[cur].substring(0, names[cur].indexOf('.') + 1) +
171                 (seen ? "s" : "") +
172                 (deleted ? "x" : "") +
173                 (flagged ? "f" : "") +
174                 (draft ? "d" : "") +
175                 (recent ? "r" : "") +
176                 (answered ? "a" : "");
177             new File(path + File.separatorChar + names[cur]).renameTo(new File(path + File.separatorChar + newName));
178             names[cur] = newName;
179         }
180
181         public void    delete() {
182             new File(path + File.separatorChar + names[cur]).delete();
183             // FIXME remove from list?
184         }
185         public void    set(String key, String val) { throw new MailException("not supported"); }
186         public String  get(String key) { throw new MailException("not supported"); }
187
188         public boolean seen() { return seen; }
189         public boolean deleted() { return deleted; }
190         public boolean flagged() { return flagged; }
191         public boolean draft() { return draft; }
192         public boolean answered() { return answered; }
193         public boolean recent() { return recent; }
194         public void    seen(boolean on) { seen = on; fixflags(); }
195         public void    deleted(boolean on) { deleted = on; fixflags(); }
196         public void    flagged(boolean on) { flagged = on; fixflags(); }
197         public void    draft(boolean on) { draft = on; fixflags(); }
198         public void    answered(boolean on) { answered = on; fixflags(); }
199         public void    recent(boolean on) { recent = on; fixflags(); }
200
201     }
202 }