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