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 // FIXME: should be a File()
39 public static synchronized MailTree getFileBasedMailbox(String path, boolean create) {
40 if (path.endsWith(".sqlite")) path = path.substring(0, path.length()-".sqlite".length());
41 path = new File(path).getAbsolutePath().toString();
43 MailTree ret = instances.get(path);
45 Log.error("n", "no match for " + path + " in " + instances.hashCode());
46 if (new File(path+".sqlite").exists()) ret = new SqliteMailbox(path+".sqlite");
47 else if (new File(path).exists()) ret = new FileBasedMailbox(new File(path));
48 else if (create) ret = new SqliteMailbox(path+".sqlite");
50 instances.put(path, (MailTree)ret);
51 Log.error("n", "filling " + path + " with " + instances.get(path));
54 } catch (Exception e) {
55 Log.error(FileBasedMailbox.class, e);
60 // Instance //////////////////////////////////////////////////////////////////////////////
63 private FileLock lock;
65 private int uidValidity;
67 // Helpers //////////////////////////////////////////////////////////////////////////////
69 private static void rmDashRf(File f) throws IOException {
70 if (!f.isDirectory()) { f.delete(); return; }
71 String[] children = f.list();
72 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
76 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
81 File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
82 lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
86 Log.warn(this, "warning: blocking waiting for a lock on " + path);
87 lock = new RandomAccessFile(lockfile, "rw").getChannel().lock();
88 if (lock == null) throw new IOException("unable to lock FileBasedMailbox: " + path);
90 lockfile.deleteOnExit();
93 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
95 String[] files = path.list();
96 for(int i=0; i<files.length; i++) {
98 if (files[i].indexOf('.') <= 0) continue;
99 files[i] = files[i].substring(0, files[i].indexOf('.'));
101 int n = Integer.parseInt(files[i]);
102 if (n>=uidNext) uidNext = n;
103 } catch (NumberFormatException nfe) { continue; }
104 } catch(Exception e) { Log.error(this, e); }
108 public String[] sort(String[] s) {
113 public String[] files() {
114 String[] s = path.list(filter);
115 Arrays.sort(s, comparator);
119 private static Comparator<String> comparator = new Comparator<String>() {
120 public int compare(String a, String b) {
121 if (a.indexOf('.')==-1) return a.compareTo(b);
122 if (b.indexOf('.')==-1) return a.compareTo(a);
123 int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
124 int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
125 return ai<bi ? -1 : ai>bi ? 1 : 0;
129 public Mailbox.Iterator iterator() { return new Iterator(); }
130 public String[] children() {
132 String[] list = sort(path.list());
133 for(int i=0; i<list.length; i++) {
134 File f = new File(path.getAbsolutePath() + slash + list[i]);
135 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
136 if (!f.isDirectory() && f.getName().endsWith(".sqlite"))
137 vec.addElement(list[i].substring(0, list[i].length()-".sqlite".length()));
139 return (String[])vec.copyInto(new String[vec.size()]);
142 public int uidValidity() { return uidValidity; }
144 // UGLY: Apple Mail doesn't like UID=0, so we add one
145 public int uidNext() { return uidNext+1; }
147 public synchronized void insert(Message message, int flags) {
149 String name, fullname; File target, f;
150 for(int i = uidNext; ; i++) {
152 fullname = path.getAbsolutePath() + slash + name;
153 target = new File(fullname);
154 f = new File(target.getCanonicalPath() + "-");
155 if (!f.exists() && !target.exists()) break;
156 Log.error(this, "aieeee!!!! target of insert() already exists: " + target.getAbsolutePath());
158 Stream stream = new Stream(new FileOutputStream(f));
159 message.getStream().transcribe(stream);
161 f.renameTo(new File(fullname));
163 f = new File(fullname);
164 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
165 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
166 } catch (IOException e) { throw new MailException.IOException(e); }
167 Log.info(this, path + " <= " + message.summary());
172 private static FilenameFilter filter =
173 new FilenameFilter() { public boolean accept(File dir, String name) {
174 return name.endsWith(".");
177 private class Iterator extends Mailbox.Default.Iterator {
179 String[] files = files();
180 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
181 public boolean done() { return cur >= files.length; }
182 public boolean next() { cur++; return !done(); }
183 public boolean recent() { return false; }
184 public int nntpNumber() { return cur+1; } // FIXME: lame
185 public int imapNumber() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
187 // UGLY: Apple Mail doesn't like UID=0, so we add one
188 public int uid() { return done() ? -1 : 1+Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
189 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
190 public int getFlags() { return file().lastModified()==MAGIC_DATE ? 0 : Flag.SEEN; }
191 public void setFlags(int flags) {
193 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
194 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
195 // FIXME: other flags?
196 // FIXME: definitely need DELETED flag in order to do message moves!
198 public Headers head() { return done() ? null : new Headers(new Fountain.File(file())); }
199 public Message cur() { return Message.newMessage(new Fountain.File(file())); }
202 // there's no reason this has to operate on a FileBasedMailbox -- it could operate on arbitrary mailboxes!
203 // use this for file attachments: http://jakarta.apache.org/commons/fileupload/
204 public static class Servlet extends HttpServlet {
205 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
206 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
207 String basename = request.getRequestURI();
208 PrintWriter pw = new PrintWriter(response.getWriter());
209 pw.println("<html>");
211 pw.println(" <frameset rows='30%,*'>");
212 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
213 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
214 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
215 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
217 pw.println(" <frameset cols='150,*'>");
218 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
219 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
221 pw.println(" </frameset>");
222 pw.println("</html>");
226 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
227 String frame = request.getParameter("frame");
228 String basename = request.getRequestURI();
230 if (frame == null) { frames(request, response, true); return; }
231 if (frame.equals("top")) { frames(request, response, false); return; }
232 if (frame.equals("banner")) { banner(request, response); return; }
233 if (frame.equals("topleft")) { return; }
235 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
236 ServletContext cx = getServletContext();
237 String path = cx.getRealPath(request.getServletPath());
238 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false).getMailbox();
239 if (mbox == null) throw new IOException("no such mailbox: " + path);
241 Vec msgs = new Vec();
242 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
243 String[] s = new String[4];
244 Message m = it.cur();
245 s[0] = (m.from==null?"":m.from.toString(true));
247 s[2] = (m.date + "").trim().replaceAll(" "," ");
248 s[3] = it.imapNumber() + "";
252 msgs.copyInto(messages = new String[msgs.size()][]);
254 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
255 if ("topright".equals(frame)) { topright(request, response, messages); return; }
258 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
260 PrintWriter pw = new PrintWriter(response.getWriter());
261 pw.println("<html>");
262 pw.println(" <head>");
263 pw.println(" <style>");
264 pw.println(" body { margin: 10px; }");
265 pw.println(" pre {");
266 pw.println(" font-family: monospace;");
267 pw.println(" background-color: #F0F0E0;");
268 pw.println(" color: rgb(0, 0, 0);");
269 pw.println(" padding: 5px;");
270 pw.println(" margin: 0px;");
271 pw.println(" overflow: auto;");
272 //pw.println(" width: 80%;");
273 //pw.println(" border-style: solid;");
274 //pw.println(" border-width: 1px;");
276 pw.println(" </style>");
277 pw.println(" </head>");
278 pw.println(" <body>");
279 if (request.getParameter("msgnum") != null) {
280 int target = Integer.parseInt(request.getParameter("msgnum"));
281 Mailbox.Iterator it = mbox.iterator();
283 if (it.imapNumber() == target)
285 if (it.cur() != null) {
286 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
287 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
288 Headers h = it.cur().headers;
289 pw.println(" Subject: " + it.cur().subject +"<br>");
290 pw.println(" From: " + it.cur().from +"<br>");
291 pw.println(" Date: " + it.cur().date +"<br>");
293 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
294 String key = (String)e.nextElement();
295 if (key==null || key.length()==0 || key.equals("from") ||
296 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
297 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
298 String val = h.get(key);
299 for(int i=key.length(); i<15; i++)pw.print(" ");
304 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
305 StringBuffer tgt = new StringBuffer();
306 it.cur().getBody().getStream().transcribe(tgt);
307 pw.println(tgt.toString());
308 pw.println(" </pre></td></tr></table>");
311 pw.println(" </body>");
312 pw.println("</html>");
317 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
318 String basename = request.getServletPath();
319 String realpath = getServletContext().getRealPath(basename);
321 MailingList list = MailingList.getMailingList(realpath);
322 list.banner(request, response);
324 banner(request, response);
327 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
328 PrintWriter pw = new PrintWriter(response.getWriter());
329 String basename = request.getRequestURI();
330 pw.println("<html>");
331 pw.println(" <head>");
332 pw.println(" <style>");
333 pw.println(" TH, TD, P, LI {");
334 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
335 pw.println(" font-size: 12px; ");
336 pw.println(" text-decoration:none; ");
338 pw.println(" body { margin: 10px; }");
339 pw.println(" a:link { color: #000; text-decoration: none; }");
340 pw.println(" a:active { color: #f00; text-decoration: none; }");
341 pw.println(" a:visited { color: #777; text-decoration: none; }");
342 pw.println(" a:hover { color: #000; text-decoration: none; }");
343 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
344 pw.println(" </style>");
345 pw.println(" </head>");
346 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
347 pw.println(" <script>");
348 pw.println(" var chosen = null;");
349 pw.println(" var all = [];");
350 pw.println(" function doKey(x) {");
351 pw.println(" if (chosen == null) { choose(all[0]); return; }");
352 pw.println(" switch(x) {");
353 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
354 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
357 pw.println(" function choose(who) {");
358 pw.println(" who.style.background = '#ffc';");
359 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
360 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
361 pw.println(" chosen = who;");
363 pw.println(" </script>");
364 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
365 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
367 banner(request, response);
368 pw.println(" </td></tr>");
369 pw.println(" <tr><td>");
370 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
372 for(int i=0; i<messages.length; i++) {
374 String[] m = messages[i];
375 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
376 "onmouseover='this.style.color=\"blue\"' "+
377 "onmouseout='this.style.color=\"black\"' "+
378 "onclick='choose(this);'>");
379 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
380 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
381 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
383 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
385 pw.println(" </table>");
386 pw.println(" </td></tr>");
387 pw.println(" </table></div>");
388 pw.println(" </body>");
389 pw.println("</html>");