updated for new org.ibex.js
[org.ibex.mail.git] / src / org / ibex / mail / target / Script.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.target;
6 import org.ibex.js.*;
7 import org.ibex.util.*;
8 import org.ibex.mail.*;
9 import org.ibex.mail.filter.*;
10 import org.ibex.mail.target.*;
11 import java.io.*;
12 import java.util.*;
13
14 public class Script extends Target {
15
16     private static final JS.Method METHOD = new JS.Method();
17
18     private static Script root = null;
19     private static final String DEFAULT_CONF = File.separatorChar + "etc" + File.separatorChar + "org.ibex.mail.conf";
20     public static Script root() {
21         try {
22             if (root == null) root = new Script(System.getProperty("ibex.mail.conf", DEFAULT_CONF));
23             return root;
24         } catch (Exception e) {
25             Log.error(Script.class, e);
26             return null;
27         }
28     }
29
30     final JS js;
31     private Message m = null;
32     private String filePath = null;
33     public Script(String filePath) throws JSExn, IOException {
34         this.filePath = filePath;
35         js = JSU.cloneWithNewGlobalScope(JSU.fromReader(filePath, 0, new InputStreamReader(new FileInputStream(filePath))),
36                                          new ScriptScope()); }
37
38     private class ScriptScope extends JS.Immutable {
39         ScriptEnv env = new ScriptEnv();
40         public Object get(Object o) {
41             if (o.equals("m")) return m;
42             if (o.equals("ibex")) return env;
43             return null;
44         }
45     }
46
47     public void accept(Message m) throws IOException, MailException {
48         try {
49             new Script(filePath).reallyAccept(m);
50         } catch (JSExn e) {
51             Log.error(this, e);
52             throw new MailException(e.toString());
53         }
54     }
55
56     private synchronized void reallyAccept(Message m) throws IOException, MailException, JSExn {
57         this.m = m;
58         try {
59             Object ret = js.call(null, new JS[] { m });
60             Log.debug(this, "configuration script returned " + ret);
61             if (ret == null) throw new IOException("configuration script returned null");
62             if (ret instanceof Target)      ((Target)ret).accept(m);
63             //else if (ret instanceof Filter) ((Filter)ret).process(m);
64             else throw new IOException("configuration script returned a " + ret.getClass().getName());
65         } catch (JSExn e) {
66             Log.warn(this, e);
67             throw new IOException("configuration script threw an exception");
68         }
69     }
70
71     // FIXME: this should extend org.ibex.core.Ibex
72     public class ScriptEnv extends JS.Obj {
73
74         private PropertyFile prefs = null;
75             /*
76         static {
77             try {
78                 // FIXME
79                 prefs = new PropertyFile(new File("/etc/org.ibex.mail.properties"));
80             } catch (IOException e) {
81                 Log.error(ScriptEnv.class, e);
82             }
83         }
84             */
85
86         /** lets us put multi-level get/put/call keys all in the same method */
87         private class Sub extends JS.Immutable {
88             String key;
89             Sub(String key) { this.key = key; }
90             public void put(JS key, JS val) throws JSExn {
91                 ScriptEnv.this.put(JSU.S(this.key + "." + JSU.toString(key)), val); }
92             public JS get(JS key) throws JSExn {
93                 return ScriptEnv.this.get(JSU.S(this.key + "." + JSU.toString(key))); }
94             public JS call(JS method, JS[] args) throws JSExn {
95                 return ScriptEnv.this.call(JSU.S(this.key + "." + JSU.toString(method)), args);
96             }
97         }
98         private Sub getSub(String s) { return new Sub(s); }
99
100         public JS get(JS name) throws JSExn {
101             //#jsswitch(name)
102             case "math": return ibexMath;
103             case "string": return ibexString;
104             case "date": return METHOD;
105             case "regexp": return METHOD;
106             case "log": return getSub("log");
107             case "log.debug": return METHOD;
108             case "log.info": return METHOD;
109             case "log.warn": return METHOD;
110             case "log.error": return METHOD;
111             case "list": return getSub("list");
112             case "mail": return getSub("mail");
113             case "mail.forward": return METHOD;
114             case "mail.forward2": return METHOD;
115             case "mail.send": return METHOD;
116             case "mail.my": return getSub("mail.my");
117             case "mail.my.prefs": try {
118                     return new org.ibex.js.Directory(new File("/etc/org.ibex.mail.prefs"));
119             } catch (IOException e) { throw new JSExn(e.toString()); }
120             case "mail.my.mailbox":
121                 FileBasedMailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, true);
122                 return root.slash("user", true).slash("megacz", true).slash("newmail", true);
123             //#end
124             if (JSU.toString(name).startsWith("list.")) { return MailingList.getList(JSU.toString(name).substring(5)); }
125             return super.get(name);
126         }
127
128         public JS call(JS name, JS[] args) throws JSExn {
129             final JS a = args.length >= 1 ? args[0] : null;
130             final JS b = args.length >= 2 ? args[1] : null;
131             final JS c = args.length >= 3 ? args[2] : null;
132             final int nargs = args.length;
133             try {
134                 if (name.equals("date")) { return new JSDate(args); }
135                 if (name.equals("mail.send")) {
136                     JS m = (JS)a;
137                     StringBuffer headers = new StringBuffer();
138                     String body = "";
139                     Address from = null, to = null;
140                     for(JS.Enumeration e = m.keys(); e.hasNext();) {
141                         JS key = (JS)e.next();
142                         JS val = m.get(key) == null ? null : m.get(key);
143                         if ("body".equalsIgnoreCase(JSU.toString(key))) body = JSU.toString(val);
144                         else headers.append(key + ": " + val + "\r\n");
145                         if ("from".equalsIgnoreCase(JSU.toString(key))) from = Address.parse(JSU.toString(val));
146                         if ("to".equalsIgnoreCase(JSU.toString(key))) to = Address.parse(JSU.toString(val));
147                     }
148                     Message message = Message.newMessage(new org.ibex.io.Stream(headers.toString() + "\r\n" + body), from, to);
149                     //org.ibex.mail.protocol.SMTP.Outgoing.accept(message);
150                     boolean ok = org.ibex.mail.protocol.SMTP.Outgoing.attempt(message);
151                     if (!ok) throw new JSExn("SMTP server rejected message");
152                     return JSU.T;
153                 }
154                 if (name.equals("mail.forward2")) {
155                     try {
156                         Message m2 = Message.newMessage(new org.ibex.io.Stream(m.toString()),
157                                                         m.envelopeFrom,
158                                                         new Address(a.toString()));
159                         org.ibex.mail.protocol.SMTP.Outgoing.accept(m2);
160                     } catch (Exception e) {
161                         Log.warn(this, e);
162                         throw new JSExn(e.toString());
163                     }
164                     return null;
165                 }
166                 if (name.equals("mail.forward")) { return new Target() {
167                         public void accept(Message m) throws MailException {
168                             try {
169                                 Message m2 = Message.newMessage(new org.ibex.io.Stream(m.toString()),
170                                                          m.envelopeFrom,
171                                                          new Address(a.toString()));
172                                 org.ibex.mail.protocol.SMTP.Outgoing.accept(m2);
173                             } catch (Exception e) {
174                                 throw new MailException(e.toString());
175                             }
176                         }
177                     }; }
178                 if (name.equals("log.debug")) {    JSU.debug(a== null ? "**null**" : a.toString()); return null; }
179                 if (name.equals("log.info")) {     JSU.info(a== null ? "**null**" : a.toString()); return null; }
180                 if (name.equals("log.warn")) {     JSU.warn(a== null ? "**null**" : a.toString()); return null; }
181                 if (name.equals("log.error")) {    JSU.error(a== null ? "**null**" : a.toString()); return null; }
182                 switch (nargs) {
183                 case 1:
184                     if (name.equals("regexp")) {return new JSRegexp(a, null); }
185                     break;
186                 case 2:
187                     if (name.equals("regexp")) {return new JSRegexp(a, b); }
188                 }
189             } catch (Exception e) {
190                 Log.warn(this, "ibex."+name+"() threw: " + e);
191                 Log.warn(this, e);
192                 if (e instanceof JSExn) throw ((JSExn)e);
193                 throw new JSExn("invalid argument for ibex object method "+name+"()");
194             }
195             throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
196         }
197
198         public final JSMath ibexMath = new JSMath() {
199                 public JS get(JS name) throws JSExn {
200                     // FIXME!!!
201                     /*
202                     case "isNaN": return gs.get(name);
203                     case "isFinite": return gs.get(name);
204                     case "NaN": return gs.get(name);
205                     case "Infinity": return gs.get(name);
206                     */
207                     return null;
208                 }
209             };
210         
211         public final JS ibexString = new JS.Immutable() {
212                 public JS get(JS name) throws JSExn {
213                     // FIXME!!!
214                     /*
215                     case "parseInt": return gs.get(JSU.S("parseInt"));
216                     case "parseFloat": return gs.get(JSU.S("parseFloat"));
217                     case "decodeURI": return gs.get(JSU.S("decodeURI"));
218                     case "decodeURIComponent": return gs.get(JSU.S("decodeURIComponent"));
219                     case "encodeURI": return gs.get(JSU.S("encodeURI"));
220                     case "encodeURIComponent": return gs.get(JSU.S("encodeURIComponent"));
221                     case "escape": return gs.get(JSU.S("escape"));
222                     case "unescape": return gs.get(JSU.S("unescape"));
223                     case "fromCharCode": return gs.get(JSU.S("stringFromCharCode"));
224                     */
225                     return null;
226                 }
227             };
228     }
229 }