7cc661a8adeb52bf2b47dffd5983943989ba3fe0
[org.ibex.mail.git] / src / org / ibex / mail / MailingList.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;
6 import org.ibex.util.*;
7 import org.ibex.io.*;
8 import org.ibex.mail.target.*;
9 import org.ibex.mail.protocol.*;
10 import java.util.*;
11 import java.io.*;
12 import java.net.*;
13 import javax.servlet.*;
14 import javax.servlet.http.*;
15
16 // TODO: RFC 2919 (List-ID)
17 // TODO: RFC 2142 (*-Request@)
18 // TODO: RFC 2369 (URLs as Meta-Syntax)
19
20 // FEATURE: store interesting/important stuff in sqlite
21 public class MailingList extends Mailbox.MailboxWrapper {
22
23     // FIXME
24     public MailingList(File path, FileBasedMailbox fbm) throws IOException {
25         super(fbm);
26         this.path = path;
27         this.mailbox = fbm;
28         properties = new PropertiesFile(new File(path.getCanonicalPath() + File.separatorChar + "properties"));
29         address = new Address(properties.get("address"));
30         homepage = properties.get("homepage");
31         one_line_description = properties.get("description");
32         message_footer = properties.get("footer");
33     }
34
35     public void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
36         String basename = request.getRequestURL()+"";
37         PrintWriter pw = new PrintWriter(response.getWriter());
38         /*
39         pw.println("<html>");
40         pw.println("  <head>");
41         pw.println("   <style>");
42         pw.println("     TH, TD, P, LI, BODY {");
43         pw.println("         font-family: helvetica, verdana, arial, sans-serif;");
44         pw.println("         font-size: 12px;  ");
45         pw.println("         text-decoration:none; ");
46         pw.println("     }");
47         pw.println("   </style>");
48         pw.println("  </head>");
49         pw.println("  <body>");
50         */
51         String confirm = request.getParameter("confirm");
52         if (confirm != null) {
53             Subscribe sub = (Subscribe)Confirmation.decode(confirm, secret, new Date());
54             String email = sub.email;
55             synchronized(this) {
56                 String path = this.path.getAbsolutePath() + File.separatorChar + "subscribers" + File.separatorChar+sub.email;
57                 if (sub.un) new File(path).delete();
58                 else {
59                     Log.warn(null, "creating " + path);
60                     new FileOutputStream(path).close();
61                 }
62             }
63             pw.println("    <b>successfully "+sub.adj+"d " + email + " to " + properties.get("address"));
64         } else {
65             String action = request.getParameter("action");
66             String email = request.getParameter("email");
67             if (action != null) {
68                 Subscribe sub = new Subscribe(email, request.getRequestURL().toString(), action.equals("unsubscribe"));
69                 sub.signAndSend(new Address(properties.get("owner")),
70                                 secret, new Date());
71                 pw.println("a confirmation email has been sent to " + email +
72                            "; click the enclosed link to confirm your request to " + action);
73             } else {
74                 pw.println("<table width=100% border=0 cellpadding=0 cellspacing=0><tr><td>");
75                 pw.println("    <b>"+properties.get("address")+"</b><br> ");
76                 pw.println("    <i>"+properties.get("description")+"</i> ");
77                 pw.println("</td><td align=right>");
78                 pw.println("<i>access via:</i> ");
79                 if (path.getAbsolutePath().startsWith("/afs/"))
80                     pw.println("<a target=_top href='file:" + path.getAbsolutePath() +"'>[AFS]</a> ");
81                 pw.println("<a target=_top href="+properties.get("nntp")+">[NNTP]</a></tt>");
82                 pw.println("<a target=_top href='mailto:"+properties.get("address")+"'>[SMTP]</a></tt>");
83                 pw.println("<a target=_top href='"+request.getRequestURL()+"'>[HTTP]</a></tt>");
84                 pw.println("</td></tr><tr><td colspan=2 align=right>");
85                 pw.println("    <form action='"+basename+"' method=post name=form1 target=_top>");
86                 pw.println("       <input type=text width=100 value='your@email.com' name=email>");
87                 pw.println("       <input type=hidden name=frame value=banner>");
88                 pw.println("       <select name=action onchange='form1.submit()'>");
89                 pw.println("          <option>--choose action--</option>");
90                 pw.println("          <option>subscribe</option>");
91                 pw.println("          <option>unsubscribe</option>");
92                 pw.println("          <option>preferences</option>");
93                 pw.println("       </select>");
94                 pw.println("    </form>");
95                 pw.println("</td></tr></table>");
96             }
97         }
98         //pw.println("  </body>");
99         //pw.println("</html>");
100         pw.flush();
101     }
102
103     public class Subscribe extends Confirmation {
104         public String email;
105         public String basename;
106         public boolean un;
107         public String adj;
108         public Subscribe(String email, String basename, boolean un) {
109             super(new Address(email), new Date().getTime() + (1000 * 60 * 60 * 24));
110             this.email = email;
111             this.basename = basename;
112             this.un = un;
113             this.adj = un ? "unsubscribe" : "subscribe";
114         }
115         public String getDescription() { return adj + " " + email + " to " + properties.get("address"); }
116         public String getURL(String tail) { return basename + "?frame=banner&confirm="+URLEncoder.encode(tail); }
117     }
118
119     private final File             path;
120     private final PropertiesFile   properties;
121     private final FileBasedMailbox mailbox;
122
123     private final long             secret               = new Random().nextLong();
124     public  final Address          address;
125     public        String           homepage;
126
127     public        String           one_line_description;
128     public        String           message_footer;
129
130     public        int              bounceThreshhold     = 10;
131
132     public static class Subscriber {
133         public Subscriber(Address a) { this.address = a; }
134         public  Address          address;
135     }
136
137
138     // Pooling //////////////////////////////////////////////////////////////////////////////
139
140     public Iterable<Subscriber> subscribers() {
141         return new Iterable<Subscriber>() {
142             public java.util.Iterator<Subscriber> iterator() {
143                 final File subdir = new File(path.getAbsolutePath() + File.separatorChar + "subscribers");
144                 if (!subdir.exists()) subdir.mkdirs();
145                 final String[] subs = !subdir.isDirectory() ? new String[0] : subdir.list();
146                 return new java.util.Iterator<Subscriber>() {
147                     int i=0;
148                     Subscriber prep = null;
149                     public void remove() {
150                         try {
151                             new File(subdir.getAbsolutePath() + File.separatorChar + subs[i++]).delete();
152                         } catch (Exception e) {
153                             Log.error(MailingList.class, e);
154                         }
155                     }
156                     public boolean hasNext() { if (prep==null) prep = next(); return prep!=null; }
157                     public Subscriber next() {
158                         if (prep!=null) { Subscriber ret = prep; prep = null; return ret; }
159                         while(i<subs.length) {
160                             if (subs[i].indexOf('@')==-1) i++;
161                             else try {
162                                     return new Subscriber(new Address(subs[i++]));
163                                 } catch (Exception e) {
164                                     Log.warn(MailingList.class, e);
165                                     continue;
166                                 }
167                         }
168                         return null;
169                     }
170                 };
171             }
172         };
173     }
174     /*
175     private static HashMap<String,MailingList> cache = new HashMap<String,MailingList>();
176     public static MailingList getMailingList(String path) throws IOException { return getMailingList(new File(path)); }
177     public static MailingList getMailingList(File path) throws IOException {
178         if (!path.exists()) path.mkdirs();
179         MailingList ret = cache.get(path.getCanonicalPath());
180         if (ret==null) cache.put(path.getCanonicalPath(), ret = new MailingList(path));
181         return ret;
182     }
183     */
184     // Methods //////////////////////////////////////////////////////////////////////////////
185
186     public void add(Message message) {
187         try {
188             accept(message);
189         } catch (Exception e) { throw new RuntimeException(e); }
190     }
191     public void add(Message message, int flags) { add(message); /* FIXME: flags? */ }
192     public void accept(Message m) throws MailException {
193         try {
194             StringBuffer buf = new StringBuffer();
195             m.getBody().getStream().transcribe(buf);
196             Headers head = new Headers(m.headers,
197                                        new String[] {
198                                            "List-Id", one_line_description + "<"+address+">",
199                                            "Subject", properties.get("prefix") + " " + m.headers.get("Subject")
200                                        });
201             
202             m = Message.newMessage(Fountain.Util.concat(new Fountain[] { head, 
203                                                                          Fountain.Util.create("\r\n"),
204                                                                          Fountain.Util.create(buf.toString()) }));
205             Log.warn(MailingList.class, "archiving list message " + m.subject);
206             mailbox.accept(m);
207             
208             for(Subscriber s : subscribers()) try {
209                     Log.warn(MailingList.class, "  trying " + s.address);
210                     SMTP.enqueue(m.withEnvelope(m.envelopeFrom, s.address));
211                     Log.warn("[list]", "successfully sent to " + s);
212                 } catch (Exception e2) { Log.error("[list]", e2); }
213         } catch (Exception e) { throw new RuntimeException(e); }
214     }
215
216     //public Filter[]     filters  = new Filter[0];
217     //public static class Filter {
218     //    public class EmergencyModerationFilter { }
219     //    public class MaximumLengthFilter { }
220     //    public class SpamFilter { }
221     //    public class MIMETypes { }
222     //    public class MungeReplyTo { }
223     //    public class AnonymizeSender { public boolean uncorrelated; }
224     //}
225 }    
226
227     //public static enum UserType         { Administrator, Moderator, Member }
228     //public static enum SubscriptionType { All, None, Digest, MimeDigest }
229     //public static enum Visibility       { Members, Public, Nobody }
230     //public static enum Action           { Accept, Hold, Reject }
231     //public        Visibility       listVisibility       = Visibility.Nobody;
232     //public        Visibility       membershipVisibility = Visibility.Nobody;
233     //public        Visibility       archiveVisibility    = Visibility.Members;
234     //public        Action           defaultPostingType   = Action.Hold;
235
236         //public  Action           posting = Action.Accept;
237         //public  UserType         type = UserType.Member;
238         //public  SubscriptionType subscription = SubscriptionType.All;
239         //public  boolean          send_copy_of_own_post = false;
240         //public  boolean          filter_duplicates_when_ccd = true;