more fixups to MailingList
[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(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.getServletPath();
152             PrintWriter pw = new PrintWriter(response.getWriter());
153             pw.println("<html>");
154             if (top) {
155                 pw.println("  <frameset rows='30%,*'>");
156                 pw.println("    <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
157                 pw.println("    <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
158             } else {
159                 pw.println("  <frameset cols='150,*'>");
160                 pw.println("    <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
161                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
162             }
163             pw.println("  </frameset>");
164             pw.println("</html>");
165             pw.flush();
166         }
167
168         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
169             String frame = request.getParameter("frame");
170             String basename = request.getServletPath();
171
172             if (frame == null) { frames(request, response, true); return; }
173             if (frame.equals("top")) { frames(request, response, false); return; }
174             if (frame.equals("topleft")) { return; }
175
176             if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
177             ServletContext cx = getServletContext();
178             String path = cx.getRealPath(request.getServletPath());
179             Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
180             if (mbox == null) throw new IOException("no such mailbox: " + path);
181
182             Vec msgs = new Vec();
183             for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
184                 String[] s = new String[4];
185                 Message m = it.cur();
186                 s[0] = (m.from==null?"":m.from.toString(true));
187                 s[1] = m.subject;
188                 s[2] = (m.date + "").trim().replaceAll(" ","&nbsp;");
189                 s[3] = it.num() + "";
190                 msgs.addElement(s);
191             }
192             String[][] messages;
193             msgs.copyInto(messages = new String[msgs.size()][]);
194
195             if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
196             if ("topright".equals(frame)) { topright(request, response, messages); return; }
197         }
198
199         private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
200             throws IOException {
201             PrintWriter pw = new PrintWriter(response.getWriter());
202             pw.println("<html>");
203             pw.println("  <body>");
204             pw.println("    <pre>");
205             if (request.getParameter("msgnum") != null) {
206                 int target = Integer.parseInt(request.getParameter("msgnum"));
207                 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
208                     if (it.num() == target) {
209                         StringBuffer tgt = new StringBuffer();
210                         it.cur().getBody().getStream().transcribe(tgt);
211                         pw.println(tgt.toString());
212                         break;
213                     }
214                 }
215             }
216             pw.println("    </pre>");
217             pw.println("  </body>");
218             pw.println("</html>");
219         }
220         
221         private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
222             PrintWriter pw = new PrintWriter(response.getWriter());
223             String basename = request.getServletPath();
224             pw.println("<html>");
225             pw.println("  <head>");
226             pw.println("    <style>");
227             pw.println("      a:link    { color: #000; text-decoration: none; }");
228             pw.println("      a:active  { color: #f00; text-decoration: none; }");
229             pw.println("      a:visited { color: #777; text-decoration: none; }");
230             pw.println("      a:hover   { color: #000; text-decoration: none; }");
231             pw.println("      /* a:hover   { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
232             pw.println("    </style>");
233             pw.println("  </head>");
234             pw.println("  <body onKeyPress='doKey(event.keyCode)'>");
235             pw.println("    <script>");
236             pw.println("      var chosen = null;");
237             pw.println("      var all = [];");
238             pw.println("      function doKey(x) {");
239             pw.println("          if (chosen == null) { choose(all[0]); return; }");
240             pw.println("          switch(x) {");
241             pw.println("              case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
242             pw.println("              case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
243             pw.println("          }");
244             pw.println("      }");
245             pw.println("      function choose(who) {");
246             pw.println("          who.style.background = '#ffc';");
247             pw.println("          if (chosen != null) chosen.style.background = '#aaa';");
248             pw.println("          top.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
249             pw.println("          chosen = who;");
250             pw.println("      }");
251             pw.println("    </script>");
252             pw.println("    <table width=100% border=0 cellpadding=0 cellspacing=0>");
253             boolean odd=false;
254             for(int i=0; i<messages.length; i++) {
255                 odd = !odd;
256                 String[] m = messages[i];
257                 pw.println("      <tr style='background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
258                            "onmouseover='this.style.color=\"blue\"' "+
259                            "onmouseout='this.style.color=\"black\"' "+
260                            "onclick='choose(this);'>");
261                 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
262                 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
263                 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
264                 pw.println("</tr>");
265                 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
266                 pw.println("<tr height=1 bgcolor=black><td colspan=3>");
267                 pw.println("    <img src=http://www.xwt.org/images/clearpixel.gif></td></tr>");
268             }
269             pw.println("    </table>");
270             pw.println("  </body>");
271             pw.println("</html>");
272         }
273     }
274 }