mailing list improvements (and nntp)
[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='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=topright' marginwidth=0 marginheight=0 name=topright/>");
159                 pw.println("    <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
160             } else {
161                 pw.println("  <frameset cols='150,*'>");
162                 pw.println("    <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
163                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
164             }
165             pw.println("  </frameset>");
166             pw.println("</html>");
167             pw.flush();
168         }
169
170         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
171             String frame = request.getParameter("frame");
172             String basename = request.getRequestURI();
173
174             if (frame == null) { frames(request, response, true); return; }
175             if (frame.equals("top")) { frames(request, response, false); return; }
176             if (frame.equals("banner")) { banner(request, response); return; }
177             if (frame.equals("topleft")) { return; }
178
179             if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
180             ServletContext cx = getServletContext();
181             String path = cx.getRealPath(request.getServletPath());
182             Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
183             if (mbox == null) throw new IOException("no such mailbox: " + path);
184
185             Vec msgs = new Vec();
186             for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
187                 String[] s = new String[4];
188                 Message m = it.cur();
189                 s[0] = (m.from==null?"":m.from.toString(true));
190                 s[1] = m.subject;
191                 s[2] = (m.date + "").trim().replaceAll(" ","&nbsp;");
192                 s[3] = it.num() + "";
193                 msgs.addElement(s);
194             }
195             String[][] messages;
196             msgs.copyInto(messages = new String[msgs.size()][]);
197
198             if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
199             if ("topright".equals(frame)) { topright(request, response, messages); return; }
200         }
201
202         private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
203             throws IOException {
204             PrintWriter pw = new PrintWriter(response.getWriter());
205             pw.println("<html>");
206             pw.println("  <head>");
207             pw.println("  <style>");
208             pw.println("      body { margin: 10px; }");
209             pw.println("      pre {");
210             pw.println("         font-family: monospace;");
211             pw.println("         background-color:  #F0F0E0;");
212             pw.println("         color: rgb(0, 0, 0);");
213             pw.println("         padding: 5px;");
214             pw.println("         margin: 0px;");
215             pw.println("         overflow: auto;");
216             //pw.println("         width: 80%;");
217             //pw.println("         border-style: solid;");
218             //pw.println("         border-width: 1px;");
219             pw.println("      }");
220             pw.println("  </style>");
221             pw.println("  </head>");
222             pw.println("  <body>");
223             if (request.getParameter("msgnum") != null) {
224                 int target = Integer.parseInt(request.getParameter("msgnum"));
225                 Mailbox.Iterator it = mbox.iterator();
226                 while(it.next())
227                     if (it.num() == target)
228                         break;
229                 if (it.cur() != null) {
230                     pw.println("    <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
231                     pw.println("      <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
232                     Headers h = it.cur().headers;
233                     pw.println(" Subject: " + it.cur().subject +"<br>");
234                     pw.println("    From: " + it.cur().from +"<br>");
235                     pw.println("    Date: " + it.cur().date +"<br>");
236                         /*
237                     for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
238                         String key = (String)e.nextElement();
239                         if (key==null || key.length()==0 || key.equals("from") ||
240                             key.equals("to") || key.equals("subject") || key.equals("date")) continue;
241                         key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
242                         String val = h.get(key);
243                         for(int i=key.length(); i<15; i++)pw.print(" ");
244                         pw.print(key+": ");
245                         pw.println(val);
246                     }
247                         */
248                     pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
249                     StringBuffer tgt = new StringBuffer();
250                     it.cur().getBody().getStream().transcribe(tgt);
251                     pw.println(tgt.toString());
252                     pw.println("    </pre></td></tr></table>");
253                 }
254             }
255             pw.println("  </body>");
256             pw.println("</html>");
257             pw.flush();
258             pw.close();
259         }
260         
261         private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
262             String basename = request.getServletPath();
263             String realpath = getServletContext().getRealPath(basename);
264             MailingList list = MailingList.getMailingList(realpath);
265             list.banner(request, response);
266         }
267
268         private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
269             PrintWriter pw = new PrintWriter(response.getWriter());
270             String basename = request.getRequestURI();
271             pw.println("<html>");
272             pw.println("  <head>");
273             pw.println("    <style>");
274             pw.println("      TH, TD, P, LI {");
275             pw.println("          font-family: helvetica, verdana, arial, sans-serif;");
276             pw.println("          font-size: 12px;  ");
277             pw.println("          text-decoration:none; ");
278             pw.println("      }");
279             pw.println("      body { margin: 10px; }");
280             pw.println("      a:link    { color: #000; text-decoration: none; }");
281             pw.println("      a:active  { color: #f00; text-decoration: none; }");
282             pw.println("      a:visited { color: #777; text-decoration: none; }");
283             pw.println("      a:hover   { color: #000; text-decoration: none; }");
284             pw.println("      /* a:hover   { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
285             pw.println("    </style>");
286             pw.println("  </head>");
287             pw.println("  <body onKeyPress='doKey(event.keyCode)'>");
288             pw.println("    <script>");
289             pw.println("      var chosen = null;");
290             pw.println("      var all = [];");
291             pw.println("      function doKey(x) {");
292             pw.println("          if (chosen == null) { choose(all[0]); return; }");
293             pw.println("          switch(x) {");
294             pw.println("              case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
295             pw.println("              case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
296             pw.println("          }");
297             pw.println("      }");
298             pw.println("      function choose(who) {");
299             pw.println("          who.style.background = '#ffc';");
300             pw.println("          if (chosen != null) chosen.style.background = '#ccc';");
301             pw.println("          parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
302             pw.println("          chosen = who;");
303             pw.println("      }");
304             pw.println("    </script>");
305             pw.println("    <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
306             pw.println("    <tr><td style='padding: 4px' bgcolor=#eff7ff>");
307             pw.flush();
308             banner(request, response);
309             pw.println("    </td></tr>");
310             pw.println("    <tr><td>");
311             pw.println("    <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
312             boolean odd=true;
313             for(int i=0; i<messages.length; i++) {
314                 odd = !odd;
315                 String[] m = messages[i];
316                 pw.println("      <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
317                            "onmouseover='this.style.color=\"blue\"' "+
318                            "onmouseout='this.style.color=\"black\"' "+
319                            "onclick='choose(this);'>");
320                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
321                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
322                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
323                 pw.println("</tr>");
324                 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
325             }
326             pw.println("    </table>");
327             pw.println("    </td></tr>");
328             pw.println("    </table></div>");
329             pw.println("  </body>");
330             pw.println("</html>");
331             pw.flush();
332             pw.close();
333         }
334     }
335 }