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