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