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