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