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