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.*;
12 import java.nio.channels.*;
16 import javax.servlet.*;
17 import javax.servlet.http.*;
19 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
20 public class FileBasedMailbox extends Mailbox.Default {
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); }
28 // FIXME: should be a File()
29 public static synchronized Mailbox getFileBasedMailbox(String path, boolean create) {
31 Mailbox ret = instances.get(path);
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)));
37 ret = new FileBasedMailbox(new File(path));
39 instances.put(path, ret);
42 } catch (Exception e) {
43 Log.error(FileBasedMailbox.class, e);
48 // Instance //////////////////////////////////////////////////////////////////////////////
51 private FileLock lock;
53 private int uidValidity;
55 // Helpers //////////////////////////////////////////////////////////////////////////////
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]));
64 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
69 File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
70 lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
73 Log.warn(this, "warning: blocking waiting for a lock on " + path);
74 lock = new RandomAccessFile(lockfile, "rw").getChannel().lock();
75 if (lock == null) throw new IOException("unable to lock FileBasedMailbox: " + path);
77 lockfile.deleteOnExit();
80 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
82 String[] files = path.list();
83 for(int i=0; i<files.length; i++) {
85 if (files[i].indexOf('.') <= 0) continue;
86 files[i] = files[i].substring(0, files[i].indexOf('.'));
87 int n = Integer.parseInt(files[i]);
88 if (n>=uidNext) uidNext = n;
89 } catch(Exception e) { Log.error(this, e); }
93 public String[] sort(String[] s) {
98 public String[] files() {
99 String[] s = path.list(filter);
100 Arrays.sort(s, comparator);
104 private static Comparator<String> comparator = new Comparator<String>() {
105 public int compare(String a, String b) {
106 if (a.indexOf('.')==-1) return a.compareTo(b);
107 if (b.indexOf('.')==-1) return a.compareTo(a);
108 int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
109 int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
110 return ai<bi ? -1 : ai>bi ? 1 : 0;
114 public Mailbox.Iterator iterator() { return new Iterator(); }
115 public String[] children() {
117 String[] list = sort(path.list());
118 for(int i=0; i<list.length; i++) {
119 File f = new File(path.getAbsolutePath() + slash + list[i]);
120 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
122 return (String[])vec.copyInto(new String[vec.size()]);
125 public int uidValidity() { return uidValidity; }
127 // UGLY: Apple Mail doesn't like UID=0, so we add one
128 public int uidNext() { return uidNext+1; }
130 public synchronized void insert(Message message, int flags) {
132 String name, fullname; File target, f;
133 for(int i = uidNext; ; i++) {
135 fullname = path.getAbsolutePath() + slash + name;
136 target = new File(fullname);
137 f = new File(target.getCanonicalPath() + "-");
138 if (!f.exists() && !target.exists()) break;
139 Log.error(this, "aieeee!!!! target of insert() already exists: " + target.getAbsolutePath());
141 Stream stream = new Stream(new FileOutputStream(f));
142 message.getStream().transcribe(stream);
144 f.renameTo(new File(fullname));
146 f = new File(fullname);
147 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
148 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
149 } catch (IOException e) { throw new MailException.IOException(e); }
150 Log.info(this, path + " <= " + message.summary());
155 private static FilenameFilter filter =
156 new FilenameFilter() { public boolean accept(File dir, String name) {
157 return name.endsWith(".");
160 private class Iterator extends Mailbox.Default.Iterator {
162 String[] files = files();
163 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
164 public boolean done() { return cur >= files.length; }
165 public boolean next() { cur++; return !done(); }
166 public boolean recent() { return false; }
167 public int nntpNumber() { return cur+1; } // FIXME: lame
168 public int imapNumber() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
170 // UGLY: Apple Mail doesn't like UID=0, so we add one
171 public int uid() { return done() ? -1 : 1+Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
173 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
174 public int getFlags() {
175 return file().lastModified()==MAGIC_DATE ? 0 : Flag.SEEN;
177 public void setFlags(int flags) {
179 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
180 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
183 public Headers head() { return done() ? null : new Headers(new Fountain.File(file())); }
184 public Message cur() { return Message.newMessage(new Fountain.File(file())); }
187 public static class Servlet extends HttpServlet {
188 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
189 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
190 String basename = request.getRequestURI();
191 PrintWriter pw = new PrintWriter(response.getWriter());
192 pw.println("<html>");
194 pw.println(" <frameset rows='30%,*'>");
195 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
196 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
197 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
198 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
200 pw.println(" <frameset cols='150,*'>");
201 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
202 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
204 pw.println(" </frameset>");
205 pw.println("</html>");
209 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
210 String frame = request.getParameter("frame");
211 String basename = request.getRequestURI();
213 if (frame == null) { frames(request, response, true); return; }
214 if (frame.equals("top")) { frames(request, response, false); return; }
215 if (frame.equals("banner")) { banner(request, response); return; }
216 if (frame.equals("topleft")) { return; }
218 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
219 ServletContext cx = getServletContext();
220 String path = cx.getRealPath(request.getServletPath());
221 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
222 if (mbox == null) throw new IOException("no such mailbox: " + path);
224 Vec msgs = new Vec();
225 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
226 String[] s = new String[4];
227 Message m = it.cur();
228 s[0] = (m.from==null?"":m.from.toString(true));
230 s[2] = (m.date + "").trim().replaceAll(" "," ");
231 s[3] = it.imapNumber() + "";
235 msgs.copyInto(messages = new String[msgs.size()][]);
237 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
238 if ("topright".equals(frame)) { topright(request, response, messages); return; }
241 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
243 PrintWriter pw = new PrintWriter(response.getWriter());
244 pw.println("<html>");
245 pw.println(" <head>");
246 pw.println(" <style>");
247 pw.println(" body { margin: 10px; }");
248 pw.println(" pre {");
249 pw.println(" font-family: monospace;");
250 pw.println(" background-color: #F0F0E0;");
251 pw.println(" color: rgb(0, 0, 0);");
252 pw.println(" padding: 5px;");
253 pw.println(" margin: 0px;");
254 pw.println(" overflow: auto;");
255 //pw.println(" width: 80%;");
256 //pw.println(" border-style: solid;");
257 //pw.println(" border-width: 1px;");
259 pw.println(" </style>");
260 pw.println(" </head>");
261 pw.println(" <body>");
262 if (request.getParameter("msgnum") != null) {
263 int target = Integer.parseInt(request.getParameter("msgnum"));
264 Mailbox.Iterator it = mbox.iterator();
266 if (it.imapNumber() == target)
268 if (it.cur() != null) {
269 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
270 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
271 Headers h = it.cur().headers;
272 pw.println(" Subject: " + it.cur().subject +"<br>");
273 pw.println(" From: " + it.cur().from +"<br>");
274 pw.println(" Date: " + it.cur().date +"<br>");
276 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
277 String key = (String)e.nextElement();
278 if (key==null || key.length()==0 || key.equals("from") ||
279 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
280 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
281 String val = h.get(key);
282 for(int i=key.length(); i<15; i++)pw.print(" ");
287 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
288 StringBuffer tgt = new StringBuffer();
289 it.cur().getBody().getStream().transcribe(tgt);
290 pw.println(tgt.toString());
291 pw.println(" </pre></td></tr></table>");
294 pw.println(" </body>");
295 pw.println("</html>");
300 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
301 String basename = request.getServletPath();
302 String realpath = getServletContext().getRealPath(basename);
304 MailingList list = MailingList.getMailingList(realpath);
305 list.banner(request, response);
307 banner(request, response);
310 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
311 PrintWriter pw = new PrintWriter(response.getWriter());
312 String basename = request.getRequestURI();
313 pw.println("<html>");
314 pw.println(" <head>");
315 pw.println(" <style>");
316 pw.println(" TH, TD, P, LI {");
317 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
318 pw.println(" font-size: 12px; ");
319 pw.println(" text-decoration:none; ");
321 pw.println(" body { margin: 10px; }");
322 pw.println(" a:link { color: #000; text-decoration: none; }");
323 pw.println(" a:active { color: #f00; text-decoration: none; }");
324 pw.println(" a:visited { color: #777; text-decoration: none; }");
325 pw.println(" a:hover { color: #000; text-decoration: none; }");
326 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
327 pw.println(" </style>");
328 pw.println(" </head>");
329 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
330 pw.println(" <script>");
331 pw.println(" var chosen = null;");
332 pw.println(" var all = [];");
333 pw.println(" function doKey(x) {");
334 pw.println(" if (chosen == null) { choose(all[0]); return; }");
335 pw.println(" switch(x) {");
336 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
337 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
340 pw.println(" function choose(who) {");
341 pw.println(" who.style.background = '#ffc';");
342 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
343 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
344 pw.println(" chosen = who;");
346 pw.println(" </script>");
347 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
348 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
350 banner(request, response);
351 pw.println(" </td></tr>");
352 pw.println(" <tr><td>");
353 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
355 for(int i=0; i<messages.length; i++) {
357 String[] m = messages[i];
358 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
359 "onmouseover='this.style.color=\"blue\"' "+
360 "onmouseout='this.style.color=\"black\"' "+
361 "onclick='choose(this);'>");
362 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
363 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
364 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
366 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
368 pw.println(" </table>");
369 pw.println(" </td></tr>");
370 pw.println(" </table></div>");
371 pw.println(" </body>");
372 pw.println("</html>");