]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/template/MailTemplate.java
add: mail templates support
[gigi.git] / src / org / cacert / gigi / output / template / MailTemplate.java
1 package org.cacert.gigi.output.template;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.io.Reader;
6 import java.io.StringReader;
7 import java.io.StringWriter;
8 import java.net.URL;
9 import java.util.Collection;
10 import java.util.Map;
11
12 import org.cacert.gigi.email.SendMail;
13 import org.cacert.gigi.localisation.Language;
14
15 public class MailTemplate extends Template {
16
17     public static final String SUBJECT_TAG = "[SomeCA.org] ";
18
19     private TemplateBlock subjectBlock;
20
21     public MailTemplate(URL u) {
22         super(u);
23     }
24
25     public MailTemplate(Reader r) {
26         super(r);
27     }
28
29     @Override
30     protected ParseResult parse(Reader r) throws IOException {
31         StringBuilder strb = new StringBuilder();
32         int ct = 0;
33         int c;
34         while ((c = r.read()) > 0) {
35             if (c == '\n') {
36                 ct++;
37                 if (ct == 2) {
38                     break;
39                 }
40             } else {
41                 ct = 0;
42             }
43             strb.append((char) c);
44         }
45         String[] lines = strb.toString().split("\n");
46         for (int i = 0; i < lines.length; i++) {
47             String[] lineParts = lines[i].split(": ", 2);
48             if (lineParts.length != 2) {
49                 throw new IOException("Mail template header malformed.");
50             }
51             if (lineParts[0].equals("Subject")) {
52                 subjectBlock = parseContent(new StringReader(lineParts[1])).getBlock(null);
53             }
54         }
55         if (subjectBlock == null) {
56             throw new IOException("Mail template without subject line.");
57         }
58         return parseContent(r);
59     }
60
61     public void sendMail(Language l, Map<String, Object> vars, String to) throws IOException {
62         tryReload();
63         vars.put(Outputable.OUT_KEY_PLAIN, true);
64
65         String body = runTemplate(this, l, vars);
66         String subject = runTemplate(subjectBlock, l, vars);
67
68         SendMail.getInstance().sendMail(to, SUBJECT_TAG + subject, body, "support@cacert.org", null, null, null, null, false);
69     }
70
71     private static String runTemplate(Outputable toRun, Language l, Map<String, Object> vars) {
72         StringWriter sw = new StringWriter();
73         PrintWriter pw = new PrintWriter(sw);
74         toRun.output(pw, l, vars);
75         pw.close();
76         return sw.toString();
77     }
78
79     @Override
80     public void addTranslations(Collection<String> s) {
81         subjectBlock.addTranslations(s);
82         super.addTranslations(s);
83     }
84
85 }