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