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