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