c700ae0bd7296282fcd41ea926909f822d803f74
[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) { /* DELIBERATE */ }
76         }
77     }
78
79
80     public Mailbox.Iterator  iterator()           { return new Iterator(); }
81     public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
82     public String[] children() {
83         Vec vec = new Vec();
84         String[] list = path.list();
85         for(int i=0; i<list.length; i++) {
86             File f = new File(path.getAbsolutePath() + slash + list[i]);
87             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
88         }
89         return (String[])vec.copyInto(new String[vec.size()]);
90     }
91
92     public int uidValidity() { return uidValidity; }
93     public int uidNext() {  return uidNext; }
94     public synchronized void add(Message message, int flags) {
95         try {
96             String name, fullname; File target, f;
97             for(int i = uidNext; ; i++) {
98                 name = i + ".";
99                 fullname = path.getAbsolutePath() + slash + name;
100                 target = new File(fullname);
101                 f = new File(target.getCanonicalPath() + "-");
102                 if (!f.exists() && !target.exists()) break;
103                 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
104             }
105             Stream stream = new Stream(new FileOutputStream(f));
106             message.getStream().transcribe(stream);
107             stream.close();
108             f.renameTo(new File(fullname));
109             uidNext++;
110             f = new File(fullname);
111             if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
112         } catch (IOException e) { throw new MailException.IOException(e); }
113         Log.info(this, path + " <= " + message.summary());
114     }
115
116     private class Iterator extends Mailbox.Default.Iterator {
117         int cur = -1;
118         String[] files = path.list(new FilenameFilter() { public boolean accept(File dir, String name) {
119             return name.endsWith(".");
120         } });
121         private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
122         public boolean done() { return cur >= files.length; }
123         public boolean next() { cur++; return !done(); }
124         public boolean seen() { return false; }
125         public boolean recent() { return false; }
126         public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
127         public int uid() { return done() ? -1 : Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
128         public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
129         public void seen(boolean seen) { }
130         public Headers head() {
131             if (done()) return null;
132             FileInputStream fis = null;
133             try {
134                 return new Headers.Original(new Stream(new FileInputStream(file())));
135             } catch (IOException e) { throw new MailException.IOException(e);
136             } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
137         }
138         public Message cur() {
139             FileInputStream fis = null;
140             try {
141                 return Message.newMessage(new Fountain.File(file()));
142                 //} catch (IOException e) { throw new MailException.IOException(e);
143             } catch (Message.Malformed e) { throw new MailException(e.getMessage());
144             } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
145         }
146     }
147
148     public static class Servlet extends HttpServlet {
149         public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
150         private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
151             String basename = request.getRequestURI();
152             PrintWriter pw = new PrintWriter(response.getWriter());
153             pw.println("<html>");
154             if (top) {
155                 pw.println("  <frameset rows='10%,30%,*'>");
156                 pw.println("    <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
157                 pw.println("    <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
158                 pw.println("    <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
159             } else {
160                 pw.println("  <frameset cols='150,*'>");
161                 pw.println("    <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
162                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
163             }
164             pw.println("  </frameset>");
165             pw.println("</html>");
166             pw.flush();
167         }
168
169         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
170             String frame = request.getParameter("frame");
171             String basename = request.getRequestURI();
172
173             if (frame == null) { frames(request, response, true); return; }
174             if (frame.equals("top")) { frames(request, response, false); return; }
175             if (frame.equals("banner")) { banner(request, response); return; }
176             if (frame.equals("topleft")) { return; }
177
178             if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
179             ServletContext cx = getServletContext();
180             String path = cx.getRealPath(request.getServletPath());
181             Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
182             if (mbox == null) throw new IOException("no such mailbox: " + path);
183
184             Vec msgs = new Vec();
185             for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
186                 String[] s = new String[4];
187                 Message m = it.cur();
188                 s[0] = (m.from==null?"":m.from.toString(true));
189                 s[1] = m.subject;
190                 s[2] = (m.date + "").trim().replaceAll(" ","&nbsp;");
191                 s[3] = it.num() + "";
192                 msgs.addElement(s);
193             }
194             String[][] messages;
195             msgs.copyInto(messages = new String[msgs.size()][]);
196
197             if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
198             if ("topright".equals(frame)) { topright(request, response, messages); return; }
199         }
200
201         private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
202             throws IOException {
203             PrintWriter pw = new PrintWriter(response.getWriter());
204             pw.println("<html>");
205             pw.println("  <body>");
206             pw.println("    <pre>");
207             if (request.getParameter("msgnum") != null) {
208                 int target = Integer.parseInt(request.getParameter("msgnum"));
209                 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
210                     if (it.num() == target) {
211                         StringBuffer tgt = new StringBuffer();
212                         it.cur().getBody().getStream().transcribe(tgt);
213                         pw.println(tgt.toString());
214                         break;
215                     }
216                 }
217             }
218             pw.println("    </pre>");
219             pw.println("  </body>");
220             pw.println("</html>");
221             pw.flush();
222             pw.close();
223         }
224         
225         private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
226             String basename = request.getServletPath();
227             String realpath = getServletContext().getRealPath(basename);
228             MailingList list = MailingList.getMailingList(realpath);
229             list.banner(request, response);
230         }
231
232         private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
233             PrintWriter pw = new PrintWriter(response.getWriter());
234             String basename = request.getRequestURI();
235             pw.println("<html>");
236             pw.println("  <head>");
237             pw.println("    <style>");
238             pw.println("      a:link    { color: #000; text-decoration: none; }");
239             pw.println("      a:active  { color: #f00; text-decoration: none; }");
240             pw.println("      a:visited { color: #777; text-decoration: none; }");
241             pw.println("      a:hover   { color: #000; text-decoration: none; }");
242             pw.println("      /* a:hover   { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
243             pw.println("    </style>");
244             pw.println("  </head>");
245             pw.println("  <body onKeyPress='doKey(event.keyCode)'>");
246             pw.println("    <script>");
247             pw.println("      var chosen = null;");
248             pw.println("      var all = [];");
249             pw.println("      function doKey(x) {");
250             pw.println("          if (chosen == null) { choose(all[0]); return; }");
251             pw.println("          switch(x) {");
252             pw.println("              case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
253             pw.println("              case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
254             pw.println("          }");
255             pw.println("      }");
256             pw.println("      function choose(who) {");
257             pw.println("          who.style.background = '#ffc';");
258             pw.println("          if (chosen != null) chosen.style.background = '#aaa';");
259             pw.println("          parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
260             pw.println("          chosen = who;");
261             pw.println("      }");
262             pw.println("    </script>");
263             pw.println("    <table width=100% border=0 cellpadding=0 cellspacing=0>");
264             boolean odd=false;
265             for(int i=0; i<messages.length; i++) {
266                 odd = !odd;
267                 String[] m = messages[i];
268                 pw.println("      <tr style='background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
269                            "onmouseover='this.style.color=\"blue\"' "+
270                            "onmouseout='this.style.color=\"black\"' "+
271                            "onclick='choose(this);'>");
272                 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
273                 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
274                 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
275                 pw.println("</tr>");
276                 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
277                 pw.println("<tr height=1 bgcolor=black><td colspan=3>");
278                 pw.println("    <img src=http://www.xwt.org/images/clearpixel.gif></td></tr>");
279             }
280             pw.println("    </table>");
281             pw.println("  </body>");
282             pw.println("</html>");
283             pw.flush();
284             pw.close();
285         }
286     }
287 }