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.
6 import org.prevayler.*;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
11 import org.ibex.io.Fountain;
14 import java.nio.channels.*;
18 import javax.servlet.*;
19 import javax.servlet.http.*;
21 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
22 public class FileBasedMailbox extends Mailbox.Default implements MailTree {
24 public static final long MAGIC_DATE = 0;
25 private static final char slash = File.separatorChar;
27 // FIXME: ideally this should be weak, but we end up getting duplicates of SqliteMailboxes
28 private static final HashMap<String,MailTree> instances = new HashMap<String,MailTree>();
30 public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
32 public MailTree slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
34 public void rmdir(String subdir) { throw new RuntimeException("FIXME not implemented"); }
35 public void rename(String subdir, MailTree newParent, String newName) { throw new RuntimeException("FIXME not implemented"); }
36 public Mailbox getMailbox() { return this; }
38 public JS get(JS key) throws JSExn {
39 return (JS)slash(JSU.toString(key), true);
42 // FIXME: should be a File()
43 public static synchronized MailTree getFileBasedMailbox(String path, boolean create) {
44 if (path.endsWith(".sqlite")) path = path.substring(0, path.length()-".sqlite".length());
46 MailTree ret = instances.get(path);
48 Log.error("n", "no match for " + path + " in " + instances.hashCode());
49 if (new File(path+".sqlite").exists())
50 ret = new SqliteMailbox(path+".sqlite");
52 if (!create && !(new File(path).exists())) return null;
53 ret = new FileBasedMailbox(new File(path));
55 instances.put(path, (MailTree)ret);
56 Log.error("n", "filling " + path + " with " + instances.get(path));
59 } catch (Exception e) {
60 Log.error(FileBasedMailbox.class, e);
65 // Instance //////////////////////////////////////////////////////////////////////////////
68 private FileLock lock;
70 private int uidValidity;
72 // Helpers //////////////////////////////////////////////////////////////////////////////
74 private static void rmDashRf(File f) throws IOException {
75 if (!f.isDirectory()) { f.delete(); return; }
76 String[] children = f.list();
77 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
81 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
86 File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
87 lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
91 Log.warn(this, "warning: blocking waiting for a lock on " + path);
92 lock = new RandomAccessFile(lockfile, "rw").getChannel().lock();
93 if (lock == null) throw new IOException("unable to lock FileBasedMailbox: " + path);
95 lockfile.deleteOnExit();
98 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
100 String[] files = path.list();
101 for(int i=0; i<files.length; i++) {
103 if (files[i].indexOf('.') <= 0) continue;
104 files[i] = files[i].substring(0, files[i].indexOf('.'));
105 int n = Integer.parseInt(files[i]);
106 if (n>=uidNext) uidNext = n;
107 } catch(Exception e) { Log.error(this, e); }
111 public String[] sort(String[] s) {
116 public String[] files() {
117 String[] s = path.list(filter);
118 Arrays.sort(s, comparator);
122 private static Comparator<String> comparator = new Comparator<String>() {
123 public int compare(String a, String b) {
124 if (a.indexOf('.')==-1) return a.compareTo(b);
125 if (b.indexOf('.')==-1) return a.compareTo(a);
126 int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
127 int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
128 return ai<bi ? -1 : ai>bi ? 1 : 0;
132 public Mailbox.Iterator iterator() { return new Iterator(); }
133 public String[] children() {
135 String[] list = sort(path.list());
136 for(int i=0; i<list.length; i++) {
137 File f = new File(path.getAbsolutePath() + slash + list[i]);
138 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
139 if (!f.isDirectory() && f.getName().endsWith(".sqlite"))
140 vec.addElement(list[i].substring(0, list[i].length()-".sqlite".length()));
142 return (String[])vec.copyInto(new String[vec.size()]);
145 public int uidValidity() { return uidValidity; }
147 // UGLY: Apple Mail doesn't like UID=0, so we add one
148 public int uidNext() { return uidNext+1; }
150 public synchronized void insert(Message message, int flags) {
152 String name, fullname; File target, f;
153 for(int i = uidNext; ; i++) {
155 fullname = path.getAbsolutePath() + slash + name;
156 target = new File(fullname);
157 f = new File(target.getCanonicalPath() + "-");
158 if (!f.exists() && !target.exists()) break;
159 Log.error(this, "aieeee!!!! target of insert() already exists: " + target.getAbsolutePath());
161 Stream stream = new Stream(new FileOutputStream(f));
162 message.getStream().transcribe(stream);
164 f.renameTo(new File(fullname));
166 f = new File(fullname);
167 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
168 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
169 } catch (IOException e) { throw new MailException.IOException(e); }
170 Log.info(this, path + " <= " + message.summary());
175 private static FilenameFilter filter =
176 new FilenameFilter() { public boolean accept(File dir, String name) {
177 return name.endsWith(".");
180 private class Iterator extends Mailbox.Default.Iterator {
182 String[] files = files();
183 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
184 public boolean done() { return cur >= files.length; }
185 public boolean next() { cur++; return !done(); }
186 public boolean recent() { return false; }
187 public int nntpNumber() { return cur+1; } // FIXME: lame
188 public int imapNumber() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
190 // UGLY: Apple Mail doesn't like UID=0, so we add one
191 public int uid() { return done() ? -1 : 1+Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
192 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
193 public int getFlags() { return file().lastModified()==MAGIC_DATE ? 0 : Flag.SEEN; }
194 public void setFlags(int flags) {
196 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
197 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
198 // FIXME: other flags?
200 public Headers head() { return done() ? null : new Headers(new Fountain.File(file())); }
201 public Message cur() { return Message.newMessage(new Fountain.File(file())); }
204 // there's no reason this has to operate on a FileBasedMailbox -- it could operate on arbitrary mailboxes!
205 // use this for file attachments: http://jakarta.apache.org/commons/fileupload/
206 public static class Servlet extends HttpServlet {
207 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
208 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
209 String basename = request.getRequestURI();
210 PrintWriter pw = new PrintWriter(response.getWriter());
211 pw.println("<html>");
213 pw.println(" <frameset rows='30%,*'>");
214 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
215 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
216 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
217 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
219 pw.println(" <frameset cols='150,*'>");
220 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
221 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
223 pw.println(" </frameset>");
224 pw.println("</html>");
228 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
229 String frame = request.getParameter("frame");
230 String basename = request.getRequestURI();
232 if (frame == null) { frames(request, response, true); return; }
233 if (frame.equals("top")) { frames(request, response, false); return; }
234 if (frame.equals("banner")) { banner(request, response); return; }
235 if (frame.equals("topleft")) { return; }
237 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
238 ServletContext cx = getServletContext();
239 String path = cx.getRealPath(request.getServletPath());
240 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false).getMailbox();
241 if (mbox == null) throw new IOException("no such mailbox: " + path);
243 Vec msgs = new Vec();
244 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
245 String[] s = new String[4];
246 Message m = it.cur();
247 s[0] = (m.from==null?"":m.from.toString(true));
249 s[2] = (m.date + "").trim().replaceAll(" "," ");
250 s[3] = it.imapNumber() + "";
254 msgs.copyInto(messages = new String[msgs.size()][]);
256 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
257 if ("topright".equals(frame)) { topright(request, response, messages); return; }
260 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
262 PrintWriter pw = new PrintWriter(response.getWriter());
263 pw.println("<html>");
264 pw.println(" <head>");
265 pw.println(" <style>");
266 pw.println(" body { margin: 10px; }");
267 pw.println(" pre {");
268 pw.println(" font-family: monospace;");
269 pw.println(" background-color: #F0F0E0;");
270 pw.println(" color: rgb(0, 0, 0);");
271 pw.println(" padding: 5px;");
272 pw.println(" margin: 0px;");
273 pw.println(" overflow: auto;");
274 //pw.println(" width: 80%;");
275 //pw.println(" border-style: solid;");
276 //pw.println(" border-width: 1px;");
278 pw.println(" </style>");
279 pw.println(" </head>");
280 pw.println(" <body>");
281 if (request.getParameter("msgnum") != null) {
282 int target = Integer.parseInt(request.getParameter("msgnum"));
283 Mailbox.Iterator it = mbox.iterator();
285 if (it.imapNumber() == target)
287 if (it.cur() != null) {
288 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
289 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
290 Headers h = it.cur().headers;
291 pw.println(" Subject: " + it.cur().subject +"<br>");
292 pw.println(" From: " + it.cur().from +"<br>");
293 pw.println(" Date: " + it.cur().date +"<br>");
295 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
296 String key = (String)e.nextElement();
297 if (key==null || key.length()==0 || key.equals("from") ||
298 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
299 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
300 String val = h.get(key);
301 for(int i=key.length(); i<15; i++)pw.print(" ");
306 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
307 StringBuffer tgt = new StringBuffer();
308 it.cur().getBody().getStream().transcribe(tgt);
309 pw.println(tgt.toString());
310 pw.println(" </pre></td></tr></table>");
313 pw.println(" </body>");
314 pw.println("</html>");
319 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
320 String basename = request.getServletPath();
321 String realpath = getServletContext().getRealPath(basename);
323 MailingList list = MailingList.getMailingList(realpath);
324 list.banner(request, response);
326 banner(request, response);
329 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
330 PrintWriter pw = new PrintWriter(response.getWriter());
331 String basename = request.getRequestURI();
332 pw.println("<html>");
333 pw.println(" <head>");
334 pw.println(" <style>");
335 pw.println(" TH, TD, P, LI {");
336 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
337 pw.println(" font-size: 12px; ");
338 pw.println(" text-decoration:none; ");
340 pw.println(" body { margin: 10px; }");
341 pw.println(" a:link { color: #000; text-decoration: none; }");
342 pw.println(" a:active { color: #f00; text-decoration: none; }");
343 pw.println(" a:visited { color: #777; text-decoration: none; }");
344 pw.println(" a:hover { color: #000; text-decoration: none; }");
345 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
346 pw.println(" </style>");
347 pw.println(" </head>");
348 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
349 pw.println(" <script>");
350 pw.println(" var chosen = null;");
351 pw.println(" var all = [];");
352 pw.println(" function doKey(x) {");
353 pw.println(" if (chosen == null) { choose(all[0]); return; }");
354 pw.println(" switch(x) {");
355 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
356 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
359 pw.println(" function choose(who) {");
360 pw.println(" who.style.background = '#ffc';");
361 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
362 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
363 pw.println(" chosen = who;");
365 pw.println(" </script>");
366 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
367 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
369 banner(request, response);
370 pw.println(" </td></tr>");
371 pw.println(" <tr><td>");
372 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
374 for(int i=0; i<messages.length; i++) {
376 String[] m = messages[i];
377 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
378 "onmouseover='this.style.color=\"blue\"' "+
379 "onmouseout='this.style.color=\"black\"' "+
380 "onclick='choose(this);'>");
381 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
382 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
383 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
385 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
387 pw.println(" </table>");
388 pw.println(" </td></tr>");
389 pw.println(" </table></div>");
390 pw.println(" </body>");
391 pw.println("</html>");