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