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