create sqlite mailboxes by default
[org.ibex.mail.git] / src / org / ibex / mail / FileBasedMailbox.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.mail;
6 import org.prevayler.*;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
9 import org.ibex.js.*;
10 import org.ibex.io.*;
11 import org.ibex.io.Fountain;
12 import java.io.*;
13 import java.nio.*;
14 import java.nio.channels.*;
15 import java.net.*;
16 import java.util.*;
17 import java.text.*;
18 import javax.servlet.*;
19 import javax.servlet.http.*;
20
21 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
22 public class FileBasedMailbox extends Mailbox.Default implements MailTree {
23
24     public static final long MAGIC_DATE =  0;
25     private static final char slash = File.separatorChar;
26
27     // FIXME: ideally this should be weak, but we end up getting duplicates of SqliteMailboxes
28     private static final HashMap<String,MailTree> instances = new HashMap<String,MailTree>();
29
30     public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
31
32     public MailTree slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
33
34     public void         rmdir(String subdir) { throw new RuntimeException("FIXME not implemented"); }
35     public void         rename(String subdir, MailTree newParent, String newName) { throw new RuntimeException("FIXME not implemented"); }
36     public Mailbox      getMailbox() { return this; }
37
38     public JS get(JS key) throws JSExn {
39         return (JS)slash(JSU.toString(key), true);
40     }
41
42     // FIXME: should be a File()
43     public static synchronized MailTree getFileBasedMailbox(String path, boolean create) {
44         if (path.endsWith(".sqlite")) path = path.substring(0, path.length()-".sqlite".length());
45         try {
46             MailTree ret = instances.get(path);
47             if (ret == null) {
48                 Log.error("n", "no match for " + path + " in " + instances.hashCode());
49                 if (new File(path+".sqlite").exists()) ret = new SqliteMailbox(path+".sqlite");
50                 else if (new File(path).exists()) ret = new FileBasedMailbox(new File(path));
51                 else if (create) ret = new SqliteMailbox(path+".sqlite");
52                 else return null;
53                 instances.put(path, (MailTree)ret);
54                 Log.error("n", "filling " + path + " with " + instances.get(path));
55             }
56             return ret;
57         } catch (Exception e) {
58             Log.error(FileBasedMailbox.class, e);
59             return null;
60         }
61     }
62
63     // Instance //////////////////////////////////////////////////////////////////////////////
64
65     private File path;
66     private FileLock lock;
67     private int uidNext;
68     private int uidValidity;
69
70     // Helpers //////////////////////////////////////////////////////////////////////////////
71
72     private static void rmDashRf(File f) throws IOException {
73         if (!f.isDirectory()) { f.delete(); return; }
74         String[] children = f.list();
75         for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
76         f.delete();
77     }
78
79     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
80         this.path = path;
81         path.mkdirs();
82
83         // acquire lock
84         File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
85         lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
86         // FIXME!!!
87         /*
88         if (lock == null) {
89             Log.warn(this, "warning: blocking waiting for a lock on " + path);
90             lock = new RandomAccessFile(lockfile, "rw").getChannel().lock();
91             if (lock == null) throw new IOException("unable to lock FileBasedMailbox: " + path);
92         }
93         lockfile.deleteOnExit();
94         */
95
96         uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
97         uidNext = 0;
98         String[] files = path.list();
99         for(int i=0; i<files.length; i++) {
100             try {
101                 if (files[i].indexOf('.') <= 0) continue;
102                 files[i] = files[i].substring(0, files[i].indexOf('.'));
103                 try {
104                     int n = Integer.parseInt(files[i]);
105                     if (n>=uidNext) uidNext = n;
106                 } catch (NumberFormatException nfe) { continue; }
107             } catch(Exception e) { Log.error(this, e); }
108         }
109     }
110
111     public String[] sort(String[] s) {
112         Arrays.sort(s);
113         return s;
114     }
115
116     public String[] files() {
117         String[] s = path.list(filter);
118         Arrays.sort(s, comparator);
119         return s;
120     }
121     
122     private static Comparator<String> comparator = new Comparator<String>() {
123         public int compare(String a, String b) {
124             if (a.indexOf('.')==-1) return a.compareTo(b);
125             if (b.indexOf('.')==-1) return a.compareTo(a);
126             int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
127             int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
128             return ai<bi ? -1 : ai>bi ? 1 : 0;
129         }
130     };
131
132     public Mailbox.Iterator  iterator()           { return new Iterator(); }
133     public String[] children() {
134         Vec vec = new Vec();
135         String[] list = sort(path.list());
136         for(int i=0; i<list.length; i++) {
137             File f = new File(path.getAbsolutePath() + slash + list[i]);
138             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
139             if (!f.isDirectory() && f.getName().endsWith(".sqlite"))
140                 vec.addElement(list[i].substring(0, list[i].length()-".sqlite".length()));
141         }
142         return (String[])vec.copyInto(new String[vec.size()]);
143     }
144
145     public int uidValidity() { return uidValidity; }
146
147     // UGLY: Apple Mail doesn't like UID=0, so we add one
148     public int uidNext() {  return uidNext+1; }
149
150     public synchronized void insert(Message message, int flags) {
151         try {
152             String name, fullname; File target, f;
153             for(int i = uidNext; ; i++) {
154                 name = i + ".";
155                 fullname = path.getAbsolutePath() + slash + name;
156                 target = new File(fullname);
157                 f = new File(target.getCanonicalPath() + "-");
158                 if (!f.exists() && !target.exists()) break;
159                 Log.error(this, "aieeee!!!! target of insert() already exists: " + target.getAbsolutePath());
160             }
161             Stream stream = new Stream(new FileOutputStream(f));
162             message.getStream().transcribe(stream);
163             stream.close();
164             f.renameTo(new File(fullname));
165             uidNext++;
166             f = new File(fullname);
167             if ((flags & Mailbox.Flag.SEEN) == 0)  f.setLastModified(MAGIC_DATE);
168             else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
169         } catch (IOException e) { throw new MailException.IOException(e); }
170         Log.info(this, path + " <= " + message.summary());
171     }
172
173     
174
175     private static FilenameFilter filter =
176         new FilenameFilter() { public boolean accept(File dir, String name) {
177             return name.endsWith(".");
178         } };
179
180     private class Iterator extends Mailbox.Default.Iterator {
181         int cur = -1;
182         String[] files = files();
183         private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
184         public boolean done() { return cur >= files.length; }
185         public boolean next() { cur++; return !done(); }
186         public boolean recent() { return false; }
187         public int nntpNumber() { return cur+1; }  // FIXME: lame
188         public int imapNumber() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
189
190         // UGLY: Apple Mail doesn't like UID=0, so we add one
191         public int uid() { return done() ? -1 : 1+Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
192         public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
193         public int  getFlags() { return file().lastModified()==MAGIC_DATE ? 0 : Flag.SEEN; }
194         public void setFlags(int flags) {
195             File f = file();
196             if ((flags & Mailbox.Flag.SEEN) == 0)  f.setLastModified(MAGIC_DATE);
197             else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
198             // FIXME: other flags?
199             // FIXME: definitely need DELETED flag in order to do message moves!
200         }
201         public Headers head() { return done() ? null : new Headers(new Fountain.File(file())); }
202         public Message cur() { return Message.newMessage(new Fountain.File(file())); }
203     }
204
205     // there's no reason this has to operate on a FileBasedMailbox -- it could operate on arbitrary mailboxes!
206     // use this for file attachments: http://jakarta.apache.org/commons/fileupload/
207     public static class Servlet extends HttpServlet {
208         public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
209         private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
210             String basename = request.getRequestURI();
211             PrintWriter pw = new PrintWriter(response.getWriter());
212             pw.println("<html>");
213             if (top) {
214                 pw.println("  <frameset rows='30%,*'>");
215                 //pw.println("    <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
216                 //pw.println("    <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
217                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
218                 pw.println("    <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
219             } else {
220                 pw.println("  <frameset cols='150,*'>");
221                 pw.println("    <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
222                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
223             }
224             pw.println("  </frameset>");
225             pw.println("</html>");
226             pw.flush();
227         }
228
229         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
230             String frame = request.getParameter("frame");
231             String basename = request.getRequestURI();
232
233             if (frame == null) { frames(request, response, true); return; }
234             if (frame.equals("top")) { frames(request, response, false); return; }
235             if (frame.equals("banner")) { banner(request, response); return; }
236             if (frame.equals("topleft")) { return; }
237
238             if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
239             ServletContext cx = getServletContext();
240             String path = cx.getRealPath(request.getServletPath());
241             Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false).getMailbox();
242             if (mbox == null) throw new IOException("no such mailbox: " + path);
243
244             Vec msgs = new Vec();
245             for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
246                 String[] s = new String[4];
247                 Message m = it.cur();
248                 s[0] = (m.from==null?"":m.from.toString(true));
249                 s[1] = m.subject;
250                 s[2] = (m.date + "").trim().replaceAll(" ","&nbsp;");
251                 s[3] = it.imapNumber() + "";
252                 msgs.addElement(s);
253             }
254             String[][] messages;
255             msgs.copyInto(messages = new String[msgs.size()][]);
256
257             if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
258             if ("topright".equals(frame)) { topright(request, response, messages); return; }
259         }
260
261         private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
262             throws IOException {
263             PrintWriter pw = new PrintWriter(response.getWriter());
264             pw.println("<html>");
265             pw.println("  <head>");
266             pw.println("  <style>");
267             pw.println("      body { margin: 10px; }");
268             pw.println("      pre {");
269             pw.println("         font-family: monospace;");
270             pw.println("         background-color:  #F0F0E0;");
271             pw.println("         color: rgb(0, 0, 0);");
272             pw.println("         padding: 5px;");
273             pw.println("         margin: 0px;");
274             pw.println("         overflow: auto;");
275             //pw.println("         width: 80%;");
276             //pw.println("         border-style: solid;");
277             //pw.println("         border-width: 1px;");
278             pw.println("      }");
279             pw.println("  </style>");
280             pw.println("  </head>");
281             pw.println("  <body>");
282             if (request.getParameter("msgnum") != null) {
283                 int target = Integer.parseInt(request.getParameter("msgnum"));
284                 Mailbox.Iterator it = mbox.iterator();
285                 while(it.next())
286                     if (it.imapNumber() == target)
287                         break;
288                 if (it.cur() != null) {
289                     pw.println("    <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
290                     pw.println("      <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
291                     Headers h = it.cur().headers;
292                     pw.println(" Subject: " + it.cur().subject +"<br>");
293                     pw.println("    From: " + it.cur().from +"<br>");
294                     pw.println("    Date: " + it.cur().date +"<br>");
295                         /*
296                     for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
297                         String key = (String)e.nextElement();
298                         if (key==null || key.length()==0 || key.equals("from") ||
299                             key.equals("to") || key.equals("subject") || key.equals("date")) continue;
300                         key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
301                         String val = h.get(key);
302                         for(int i=key.length(); i<15; i++)pw.print(" ");
303                         pw.print(key+": ");
304                         pw.println(val);
305                     }
306                         */
307                     pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
308                     StringBuffer tgt = new StringBuffer();
309                     it.cur().getBody().getStream().transcribe(tgt);
310                     pw.println(tgt.toString());
311                     pw.println("    </pre></td></tr></table>");
312                 }
313             }
314             pw.println("  </body>");
315             pw.println("</html>");
316             pw.flush();
317             pw.close();
318         }
319         
320         private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
321             String basename = request.getServletPath();
322             String realpath = getServletContext().getRealPath(basename);
323             /*
324             MailingList list = MailingList.getMailingList(realpath);
325             list.banner(request, response);
326             */
327             banner(request, response);
328         }
329
330         private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
331             PrintWriter pw = new PrintWriter(response.getWriter());
332             String basename = request.getRequestURI();
333             pw.println("<html>");
334             pw.println("  <head>");
335             pw.println("    <style>");
336             pw.println("      TH, TD, P, LI {");
337             pw.println("          font-family: helvetica, verdana, arial, sans-serif;");
338             pw.println("          font-size: 12px;  ");
339             pw.println("          text-decoration:none; ");
340             pw.println("      }");
341             pw.println("      body { margin: 10px; }");
342             pw.println("      a:link    { color: #000; text-decoration: none; }");
343             pw.println("      a:active  { color: #f00; text-decoration: none; }");
344             pw.println("      a:visited { color: #777; text-decoration: none; }");
345             pw.println("      a:hover   { color: #000; text-decoration: none; }");
346             pw.println("      /* a:hover   { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
347             pw.println("    </style>");
348             pw.println("  </head>");
349             pw.println("  <body onKeyPress='doKey(event.keyCode)'>");
350             pw.println("    <script>");
351             pw.println("      var chosen = null;");
352             pw.println("      var all = [];");
353             pw.println("      function doKey(x) {");
354             pw.println("          if (chosen == null) { choose(all[0]); return; }");
355             pw.println("          switch(x) {");
356             pw.println("              case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
357             pw.println("              case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
358             pw.println("          }");
359             pw.println("      }");
360             pw.println("      function choose(who) {");
361             pw.println("          who.style.background = '#ffc';");
362             pw.println("          if (chosen != null) chosen.style.background = '#ccc';");
363             pw.println("          parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
364             pw.println("          chosen = who;");
365             pw.println("      }");
366             pw.println("    </script>");
367             pw.println("    <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
368             pw.println("    <tr><td style='padding: 4px' bgcolor=#eff7ff>");
369             pw.flush();
370             banner(request, response);
371             pw.println("    </td></tr>");
372             pw.println("    <tr><td>");
373             pw.println("    <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
374             boolean odd=true;
375             for(int i=0; i<messages.length; i++) {
376                 odd = !odd;
377                 String[] m = messages[i];
378                 pw.println("      <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
379                            "onmouseover='this.style.color=\"blue\"' "+
380                            "onmouseout='this.style.color=\"black\"' "+
381                            "onclick='choose(this);'>");
382                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
383                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
384                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
385                 pw.println("</tr>");
386                 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
387             }
388             pw.println("    </table>");
389             pw.println("    </td></tr>");
390             pw.println("    </table></div>");
391             pw.println("  </body>");
392             pw.println("</html>");
393             pw.flush();
394             pw.close();
395         }
396     }
397 }