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