48e085350ae131dad75199c7a84d5e6cda3c1d71
[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                 int n = Integer.parseInt(files[i]);
106                 if (n>=uidNext) uidNext = n;
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         }
200         public Headers head() { return done() ? null : new Headers(new Fountain.File(file())); }
201         public Message cur() { return Message.newMessage(new Fountain.File(file())); }
202     }
203
204     // there's no reason this has to operate on a FileBasedMailbox -- it could operate on arbitrary mailboxes!
205     // use this for file attachments: http://jakarta.apache.org/commons/fileupload/
206     public static class Servlet extends HttpServlet {
207         public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
208         private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
209             String basename = request.getRequestURI();
210             PrintWriter pw = new PrintWriter(response.getWriter());
211             pw.println("<html>");
212             if (top) {
213                 pw.println("  <frameset rows='30%,*'>");
214                 //pw.println("    <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
215                 //pw.println("    <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
216                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
217                 pw.println("    <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
218             } else {
219                 pw.println("  <frameset cols='150,*'>");
220                 pw.println("    <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
221                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
222             }
223             pw.println("  </frameset>");
224             pw.println("</html>");
225             pw.flush();
226         }
227
228         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
229             String frame = request.getParameter("frame");
230             String basename = request.getRequestURI();
231
232             if (frame == null) { frames(request, response, true); return; }
233             if (frame.equals("top")) { frames(request, response, false); return; }
234             if (frame.equals("banner")) { banner(request, response); return; }
235             if (frame.equals("topleft")) { return; }
236
237             if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
238             ServletContext cx = getServletContext();
239             String path = cx.getRealPath(request.getServletPath());
240             Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false).getMailbox();
241             if (mbox == null) throw new IOException("no such mailbox: " + path);
242
243             Vec msgs = new Vec();
244             for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
245                 String[] s = new String[4];
246                 Message m = it.cur();
247                 s[0] = (m.from==null?"":m.from.toString(true));
248                 s[1] = m.subject;
249                 s[2] = (m.date + "").trim().replaceAll(" ","&nbsp;");
250                 s[3] = it.imapNumber() + "";
251                 msgs.addElement(s);
252             }
253             String[][] messages;
254             msgs.copyInto(messages = new String[msgs.size()][]);
255
256             if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
257             if ("topright".equals(frame)) { topright(request, response, messages); return; }
258         }
259
260         private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
261             throws IOException {
262             PrintWriter pw = new PrintWriter(response.getWriter());
263             pw.println("<html>");
264             pw.println("  <head>");
265             pw.println("  <style>");
266             pw.println("      body { margin: 10px; }");
267             pw.println("      pre {");
268             pw.println("         font-family: monospace;");
269             pw.println("         background-color:  #F0F0E0;");
270             pw.println("         color: rgb(0, 0, 0);");
271             pw.println("         padding: 5px;");
272             pw.println("         margin: 0px;");
273             pw.println("         overflow: auto;");
274             //pw.println("         width: 80%;");
275             //pw.println("         border-style: solid;");
276             //pw.println("         border-width: 1px;");
277             pw.println("      }");
278             pw.println("  </style>");
279             pw.println("  </head>");
280             pw.println("  <body>");
281             if (request.getParameter("msgnum") != null) {
282                 int target = Integer.parseInt(request.getParameter("msgnum"));
283                 Mailbox.Iterator it = mbox.iterator();
284                 while(it.next())
285                     if (it.imapNumber() == target)
286                         break;
287                 if (it.cur() != null) {
288                     pw.println("    <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
289                     pw.println("      <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
290                     Headers h = it.cur().headers;
291                     pw.println(" Subject: " + it.cur().subject +"<br>");
292                     pw.println("    From: " + it.cur().from +"<br>");
293                     pw.println("    Date: " + it.cur().date +"<br>");
294                         /*
295                     for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
296                         String key = (String)e.nextElement();
297                         if (key==null || key.length()==0 || key.equals("from") ||
298                             key.equals("to") || key.equals("subject") || key.equals("date")) continue;
299                         key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
300                         String val = h.get(key);
301                         for(int i=key.length(); i<15; i++)pw.print(" ");
302                         pw.print(key+": ");
303                         pw.println(val);
304                     }
305                         */
306                     pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
307                     StringBuffer tgt = new StringBuffer();
308                     it.cur().getBody().getStream().transcribe(tgt);
309                     pw.println(tgt.toString());
310                     pw.println("    </pre></td></tr></table>");
311                 }
312             }
313             pw.println("  </body>");
314             pw.println("</html>");
315             pw.flush();
316             pw.close();
317         }
318         
319         private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
320             String basename = request.getServletPath();
321             String realpath = getServletContext().getRealPath(basename);
322             /*
323             MailingList list = MailingList.getMailingList(realpath);
324             list.banner(request, response);
325             */
326             banner(request, response);
327         }
328
329         private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
330             PrintWriter pw = new PrintWriter(response.getWriter());
331             String basename = request.getRequestURI();
332             pw.println("<html>");
333             pw.println("  <head>");
334             pw.println("    <style>");
335             pw.println("      TH, TD, P, LI {");
336             pw.println("          font-family: helvetica, verdana, arial, sans-serif;");
337             pw.println("          font-size: 12px;  ");
338             pw.println("          text-decoration:none; ");
339             pw.println("      }");
340             pw.println("      body { margin: 10px; }");
341             pw.println("      a:link    { color: #000; text-decoration: none; }");
342             pw.println("      a:active  { color: #f00; text-decoration: none; }");
343             pw.println("      a:visited { color: #777; text-decoration: none; }");
344             pw.println("      a:hover   { color: #000; text-decoration: none; }");
345             pw.println("      /* a:hover   { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
346             pw.println("    </style>");
347             pw.println("  </head>");
348             pw.println("  <body onKeyPress='doKey(event.keyCode)'>");
349             pw.println("    <script>");
350             pw.println("      var chosen = null;");
351             pw.println("      var all = [];");
352             pw.println("      function doKey(x) {");
353             pw.println("          if (chosen == null) { choose(all[0]); return; }");
354             pw.println("          switch(x) {");
355             pw.println("              case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
356             pw.println("              case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
357             pw.println("          }");
358             pw.println("      }");
359             pw.println("      function choose(who) {");
360             pw.println("          who.style.background = '#ffc';");
361             pw.println("          if (chosen != null) chosen.style.background = '#ccc';");
362             pw.println("          parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
363             pw.println("          chosen = who;");
364             pw.println("      }");
365             pw.println("    </script>");
366             pw.println("    <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
367             pw.println("    <tr><td style='padding: 4px' bgcolor=#eff7ff>");
368             pw.flush();
369             banner(request, response);
370             pw.println("    </td></tr>");
371             pw.println("    <tr><td>");
372             pw.println("    <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
373             boolean odd=true;
374             for(int i=0; i<messages.length; i++) {
375                 odd = !odd;
376                 String[] m = messages[i];
377                 pw.println("      <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
378                            "onmouseover='this.style.color=\"blue\"' "+
379                            "onmouseout='this.style.color=\"black\"' "+
380                            "onclick='choose(this);'>");
381                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
382                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
383                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
384                 pw.println("</tr>");
385                 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
386             }
387             pw.println("    </table>");
388             pw.println("    </td></tr>");
389             pw.println("    </table></div>");
390             pw.println("  </body>");
391             pw.println("</html>");
392             pw.flush();
393             pw.close();
394         }
395     }
396 }