adds the service app which I forgot

This commit is contained in:
Timothy Prepscius 2013-08-13 20:51:31 -04:00
parent 76fe04658b
commit 0d5f66ab84
15 changed files with 2127 additions and 0 deletions

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mailiverse.Core"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mailiverse.Ext.BouncyCastle"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mailiverse.Ext.JordanZimmerman"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mailiverse.Ext.Json"/>
<classpathentry kind="lib" path="lib/plugin.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
java/app/service/.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Mailiverse.App.Service</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

1
java/app/service/lib Symbolic link
View File

@ -0,0 +1 @@
../../lib

View File

@ -0,0 +1,17 @@
package app.service;
import java.applet.Applet;
import netscape.javascript.JSObject;
import core.callback.Callback;
public class JSApplet extends Applet
{
public Object getWindow(Callback callback)
{
return JSObject.getWindow(this);
}
}

View File

@ -0,0 +1,509 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import core.constants.ConstantsMailJson;
import core.constants.ConstantsClient;
import core.constants.ConstantsSettings;
import core.constants.ConstantsStorage;
import core.util.JSON_;
import core.util.JSON_.JSONException;
import core.util.LogNull;
import core.util.LogOut;
import core.util.Pair;
import core.util.Strings;
import mail.client.Client;
import mail.client.model.Body;
import mail.client.model.Conversation;
import mail.client.model.Folder;
import mail.client.model.Header;
import mail.client.model.Identity;
import mail.client.model.Mail;
import mail.client.model.Original;
import mail.client.model.Settings;
@Export()
public class JSClient implements Exportable
{
static LogNull log = new LogNull(JSClient.class);
Client client;
public JSClient (Client client)
{
this.client = client;
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#buildAddressList(java.lang.String)
*/
public List<Identity> buildAddressList(String addresses)
{
return client.getMaster().getAddressBook().parseAddressString(addresses);
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#getDaysLeft(java.lang.Object)
*/
public void getDaysLeft (Object callback) throws Exception
{
client.getHttpDelegate().execute(
"POST",
ConstantsClient.WEB_SERVER_TOMCAT + "DaysLeft",
null, false, false, Strings.toBytes(client.getMaster().getIdentity().getEmail()), new JSResult<String>(callback)
);
}
public void flushStore () throws IOException
{
try
{
log.debug("flushStore");
client.getMaster().getCacheManager().flush();
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public void updateStore () throws IOException
{
try
{
log.debug("flushStore");
client.getMaster().getCacheManager().update();
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public void debugStore () throws IOException
{
try
{
log.debug("debugStore");
client.getMaster().getCacheManager().debug();
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public String getSignatureHTML ()
{
String signature = client.getMaster().getCacheManager().getSettings().get(ConstantsSettings.SIGNATURE, "");
return ("\r\n\r\n" + signature + "\r\n").replaceAll("\r\n", "<br>");
}
public Body calculateReplyBody (MailI mail)
{
return calculateReplyBody(mail.deref());
}
public Body calculateReplyBody (Mail mail)
{
return client.getMaster().getActions().calculateSignaturedReplyBody(mail);
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#sendMail(mail.client.core.Conversation, mail.client.core.Mail)
*/
public void sendMail(Conversation conversation, Mail mail)
{
try
{
client.getMaster().getActions().sendMail(conversation, mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public void sendMail(Conversation conversation, MailI mail)
{
sendMail(conversation, mail.deref());
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#saveMail(mail.client.core.Conversation, mail.client.core.Mail)
*/
public void saveMail(Conversation conversation, Mail mail)
{
try
{
client.getMaster().getActions().saveMail(conversation, mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public void saveMail(Conversation conversation, MailI mail)
{
saveMail(conversation, mail.deref());
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#deleteMail(mail.client.core.Conversation, mail.client.core.Mail)
*/
public void deleteMail(Conversation conversation, Mail mail)
{
try
{
client.getMaster().getActions().deleteMail(conversation,mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public void deleteMail(Conversation conversation, MailI mail)
{
deleteMail(conversation, mail.deref());
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#reindexConversation(mail.client.core.Conversation)
*/
public void reindexConversation(Conversation conversation)
{
try
{
client.getMaster().getActions().reindexConversation(conversation);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#deleteConversation(mail.client.core.Conversation)
*/
public void deleteConversation(Conversation conversation)
{
try
{
client.getMaster().getActions().deleteConversation(conversation);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#checkMail()
*/
public void checkMail ()
{
log.debug("checkMail");
try
{
client.getMaster().getArrivalsMonitor().check();
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#getFolders()
*/
public String[] getSystemFolders ()
{
log.debug("getFolders");
List<String> result = new ArrayList<String>();
List<Folder> folders = client.getMaster().getIndexer().getSystemFolders();
for (Folder f : folders)
if (f.isLoaded())
result.add(f.getId().toString());
return result.toArray(new String[0]);
}
public String[] getUserFolders ()
{
log.debug("getFolders");
List<String> result = new ArrayList<String>();
List<Folder> folders = client.getMaster().getIndexer().getUserFolders();
for (Folder f : folders)
if (f.isLoaded())
result.add(f.getId().toString());
return result.toArray(new String[0]);
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#getFolder(java.lang.String)
*/
public Folder getSystemFolder (String folder)
{
log.debug("getSystemFolder");
List<Folder> folders = client.getMaster().getIndexer().getSystemFolders();
for (Folder f : folders)
if (f.isLoaded())
if (f.getId().toString() == folder)
return f;
return null;
}
public Folder getUserFolder (String folder)
{
log.debug("getUserFolder");
List<Folder> folders = client.getMaster().getIndexer().getUserFolders();
for (Folder f : folders)
if (f.isLoaded())
if (f.getId().toString() == folder)
return f;
return null;
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#replyTo(mail.client.core.Conversation, mail.client.core.Mail, mail.client.core.Body)
*/
public Mail replyTo (Conversation conversation, Mail mail)
{
try
{
return client.getMaster().getActions().replyTo(conversation, mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public MailI replyTo (Conversation conversation, MailI mail)
{
return new MailI(replyTo(conversation, mail.deref()));
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#replyToAll(mail.client.core.Conversation, mail.client.core.Mail, mail.client.core.Body)
*/
public Mail replyToAll (Conversation conversation, Mail mail)
{
try
{
return client.getMaster().getActions().replyToAll(conversation, mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public MailI replyToAll (Conversation conversation, MailI mail)
{
return new MailI(replyToAll(conversation, mail.deref()));
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#forward(mail.client.core.Conversation, mail.client.core.Mail)
*/
public Mail forward (Conversation conversation, Mail mail)
{
try
{
return client.getMaster().getActions().forward(conversation, mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public MailI forward (Conversation conversation, MailI mail)
{
return new MailI(forward(conversation, mail.deref()));
}
public Object[] newMail ()
{
try
{
Pair<Conversation,Mail> pair = client.getMaster().getActions().newMail();
return new Object[] { pair.first, pair.second };
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#getAddressList()
*/
public Identity[] getAddressList ()
{
try
{
return client.getMaster().getAddressBook().getAddressList().toArray(new Identity[0]);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public Original getOriginal(Mail mail)
{
try
{
log.debug("getOriginal: ",new Date());
String originalKey = mail.getHeader().getOriginalKey();
return client.getMaster().getStore().getOriginal(originalKey);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public Original getOriginal(MailI mail)
{
return getOriginal(mail.deref());
}
public void loadAttachments(Mail mail)
{
try
{
log.debug("loadAttachments: ",new Date());
client.getMaster().getStore().loadAttachments(mail);
}
catch (Exception e)
{
log.exception(e);
throw new RuntimeException(e);
}
}
public void loadAttachments(MailI mail)
{
loadAttachments(mail.deref());
}
/* (non-Javadoc)
* @see app.service.JSAppletInterface#getMinimalJSONForConversations(java.lang.Object[])
*/
public String getMinimalJSONForConversations (Object[] conversations) throws JSONException
{
Object a = JSON_.newArray();
for (Object o : conversations)
{
Conversation c = (Conversation)o;
Object json;
try
{
json = JSON_.newObject();
JSON_.put(json, "loaded", JSON_.newBoolean(c.isLoaded()));
if (c.isLoaded())
{
List<String> shortNames = new ArrayList<String>(c.getHeader().getAuthors().size());
for (Identity i : c.getHeader().getAuthors())
shortNames.add(i.getShortName());
Header h = c.getHeader();
JSON_.put(json, "participants", JSON_.newString(Strings.concat(shortNames,", ")));
JSON_.put(json, "numItems", JSON_.newNumber(c.getNumItems()));
JSON_.put(json, "subject", JSON_.newString(h.getSubject()!=null?h.getSubject():"No subject"));
JSON_.put(json, "brief", JSON_.newString(h.getBrief()!=null?h.getBrief():"No brief"));
JSON_.put(json, "date",JSON_.newString(c.getHeader().getRelativeDate()));
JSON_.put(json, "state", JSON_.newString(c.getHeader().getTransportState().toString()));
}
}
catch (Exception e)
{
log.debug("this " + c + " header " + c.getHeader());
log.exception(e);
json = JSON_.newObject();
JSON_.put(json, "loaded", JSON_.newBoolean(false));
}
JSON_.add(a,json);
}
return a.toString();
}
public void newUserFolder ()
{
client.getMaster().getIndexer().newUserFolder("New Folder");
}
public void deleteUserFolder (String userFolder)
{
client.getMaster().getIndexer().deleteUserFolder(getUserFolder(userFolder));
}
public void addToUserFolder(String userFolder, Conversation conversation)
{
client.getMaster().getIndexer().addToUserFolder(
getUserFolder(userFolder), conversation
);
}
public void removeFromUserFolder(String userFolder, Conversation conversation)
{
client.getMaster().getIndexer().removeFromUserFolder(
getUserFolder(userFolder), conversation
);
}
public Settings getSettings ()
{
return client.getMaster().getCacheManager().getSettings();
}
}

View File

@ -0,0 +1,55 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import core.util.LogNull;
import mail.client.EventDispatcher;
import mail.client.EventPropagator;
@Export()
public class JSEventPropagator extends EventDispatcher implements Exportable
{
static LogNull log = new LogNull (JSEventPropagator.class);
Object delegate;
public JSEventPropagator ()
{
}
@Override
protected void doSignal (String event, Object... parameters)
{
super.doSignal(event, parameters);
try
{
if (!event.equals(EventPropagator.INVOKE))
if (delegate != null)
JSInvoker.invoke(delegate,
"signal",
new Object[] {
event,
(parameters != null && parameters.length > 0) ?
parameters[0] :
null
}
);
}
catch (Exception e)
{
log.exception(e);
}
}
public void setDelegate (Object delegate)
{
this.delegate = delegate;
}
}

View File

@ -0,0 +1,114 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import com.google.gwt.core.client.JsArray;
import java.io.IOException;
import core.callback.Callback;
import core.callback.CallbackDefault;
import core.util.Base64;
import core.util.HttpDelegate;
import core.util.LogNull;
import core.util.Strings;
@Export()
public class JSHttpDelegate extends HttpDelegate implements Exportable
{
static LogNull log = new LogNull(JSHttpDelegate.class);
Object delegate;
public JSHttpDelegate (Object delegate)
{
this.delegate = delegate;
}
public void doExecute (String action, String url, String[][] headers, boolean binaryInput, boolean binaryOutput, byte[] contents, Callback callback) throws Exception
{
try
{
JSInvoker.invoke (
delegate,
"executeURL",
new Object[] {
action, url, headers, binaryInput, binaryOutput,
binaryInput ?
((contents!=null) ? Base64.encode(contents) : null) :
((contents!=null) ? Strings.toString(contents) : null),
new CallbackDefault(url, binaryOutput) {
@Override
public void onSuccess(Object...arguments) throws Exception
{
String data = (String)arguments[0];
JsArray jsHeaders = (JsArray) arguments[1];
String[][] headers = new String[jsHeaders.length()][];
for (int i=0; i<jsHeaders.length(); ++i)
{
JsArray header = jsHeaders.get(i).cast();
headers[i] = new String[] {
header.get(0).toString(),
header.get(1).toString()
} ;
}
String url = V(0);
boolean binaryOutput = V(1);
log.debug("doExecute callback ",url,binaryOutput);
if (data == null)
{
log.debug("failed to acquire resource", url);
next(new IOException("Failed to acquire resource"));
}
else
{
log.debug("succeeded in acquiring resource", url);
if (binaryOutput)
{
byte[] bin = data != null ? Base64.decode(data) : null;
next(bin, headers);
}
else
{
next(data, headers);
}
}
}
}.setReturn(callback)
}
);
}
catch (Throwable e)
{
callback.invoke(e);
}
}
@Override
public void execute (String action, String url, String[][] headers, boolean binaryInput, boolean binaryOutput, byte[] contents, Callback callback)
{
log.debug("JSHttpDelegate.execute ",url);
try
{
doExecute (action, url, headers, binaryInput, binaryOutput, contents, callback);
}
catch (Exception e)
{
callback.invoke(e);
}
}
}

View File

@ -0,0 +1,23 @@
package app.service;
import netscape.javascript.JSObject;
public class JSInvoker
{
public static Object invoke(Object o, String f, Object[] args)
{
JSObject js = (JSObject)o;
return js.call(f, args);
}
public static Object getMember(Object o, String member)
{
JSObject js = (JSObject)o;
return js.getMember(member);
}
public static Object wrap(Object o)
{
return o;
}
}

View File

@ -0,0 +1,249 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import mail.auth.MailServerAuthenticatorNoThread;
import mail.client.EventPropagator;
import org.json.JSONObject;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import core.callback.Callback;
import core.callback.CallbackWithVariables;
import core.constants.ConstantsClient;
import core.io.IoChain;
import core.util.HttpDelegate;
import core.util.LogNull;
import core.util.LogOut;
@Export()
public class JSRefill implements Exportable
{
static LogNull log = new LogNull(JSSignUp.class);
Main main;
JSRefill (Main main)
{
this.main = main;
}
static class RefillInfo {
public static enum Storage { Mailiverse, Dropbox };
String email;
JSResult<Boolean> callback;
String paymentMethod;
String stripeCardNumber, stripeCardExpMonth, stripeCardExpYear, stripeCardCVC;
String stripeTransactionID;
String bitpayToken;
String amount;
RefillInfo (
String email, String amount,
JSResult<Boolean> callback
)
{
this.email = email;
this.callback = callback;
this.amount = amount;
}
void initializeStripe (
String stripeCardNumber, String stripeCardCVC, String stripeCardExpMonth, String stripeCardExpYear
)
{
this.paymentMethod = "stripe";
this.stripeCardNumber = stripeCardNumber;
this.stripeCardCVC = stripeCardCVC;
this.stripeCardExpMonth = stripeCardExpMonth;
this.stripeCardExpYear = stripeCardExpYear;
}
void initializeBitPay (String bitpayToken)
{
this.paymentMethod = "bitpay";
this.bitpayToken = bitpayToken;
}
}
public void makePayment (
String name,
String amount,
String paymentMethod,
Object paymentDetails,
Object callback
)
{
log.debug("refill", name, amount, paymentMethod);
RefillInfo info = new RefillInfo(
name, amount,
new JSResult<Boolean>(callback)
);
if (paymentMethod.equals("stripe"))
info.initializeStripe(
JSInvoker.getMember(paymentDetails, "number").toString(),
JSInvoker.getMember(paymentDetails, "cvc").toString(),
JSInvoker.getMember(paymentDetails, "month").toString(),
JSInvoker.getMember(paymentDetails, "year").toString()
);
else
if (paymentMethod.equals("bitpay"))
info.initializeBitPay(
JSInvoker.getMember(paymentDetails, "token").toString()
);
main.eventPropagator.signal(
EventPropagator.INVOKE,
new Callback() {
public void invoke(Object... arguments)
{
refill_step_requestPaymentStripeStep1((RefillInfo)arguments[0]);
}
},
info
);
}
public void test (String user, Object callback) throws Exception
{
log.debug("test");
JSResult<Object> result = new JSResult<Object>(callback);
String url = ConstantsClient.MAIL_SERVER_WEBSOCKET;
MailServerAuthenticatorNoThread.testCreate_(
user,
new JSStreamSessionWebSocket(url, main.delegate)
).addCallback(result).invoke();
}
protected void refill_step_requestPayment(RefillInfo info)
{
refill_step_requestPaymentStripeStep1(info);
}
protected void refill_step_requestPaymentStripeStep1(RefillInfo info)
{
final String stripePublishableKey = "YOUR_STRIPE_TOKEN";
log.debug("refill_step_requestPaymentStripeStep1");
try
{
String url =
"https://api.stripe.com/v1/tokens?" +
"card[number]=" + info.stripeCardNumber +
"&card[exp_month]=" + info.stripeCardExpMonth +
"&card[exp_year]=" + info.stripeCardExpYear +
"&card[cvc]=" + info.stripeCardCVC +
"&key=" + stripePublishableKey +
"&_method=POST";
JSHttpDelegate http = new JSHttpDelegate(main.delegate);
http.execute(
HttpDelegate.GET, url, null,
false, false, null,
new CallbackWithVariables(info) {
public void invoke(Object... arguments)
{
log.debug("signUp_step_requestPaymentStripeStep1 callback");
RefillInfo info = V(0);
try
{
if (arguments[0] instanceof Exception)
throw (Exception)arguments[0];
String response = (String)arguments[0];
JSONObject o = new JSONObject(response);
String stripeTransactionID = o.getString("id");
info.stripeTransactionID = stripeTransactionID;
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Requested CreditCard Stripe Token." });
refill_step_requestPaymentStripeStep2(info);
}
catch (Exception e)
{
e.printStackTrace();
info.callback.invoke(new Exception("Could not request Stripe token, no charge was made."));
}
}
});
}
catch (Exception e)
{
e.printStackTrace();
info.callback.invoke(e);
}
}
protected void refill_step_requestPaymentStripeStep2(RefillInfo info)
{
log.debug("refil_step_requestPaymentStripeStep2");
try
{
String url =
ConstantsClient.WEB_SERVER_TOMCAT + "StripePayment" +
"?email=" + info.email +
"&stripeTransactionID=" + info.stripeTransactionID +
"&amount=" + info.amount;
JSHttpDelegate http = new JSHttpDelegate(main.delegate);
http.execute(HttpDelegate.GET, url, null, false, false, null, new CallbackWithVariables(info) {
public void invoke(Object... arguments)
{
log.debug("signUp_step_requestPaymentStripeStep2 callback");
RefillInfo info = V(0);
try
{
if (arguments[0] instanceof Exception)
throw (Exception)arguments[0];
String response = (String)arguments[0];
JSONObject o = new JSONObject(response);
if (o.has("error"))
{
throw new Exception(o.getJSONObject("error").getString("message"));
}
else
{
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[]
{ "Purchase succeeded.\n\n" + "Please save the reciept: "+ o.getString("id") }
);
}
refill_finish(info);
}
catch (Exception e)
{
e.printStackTrace();
info.callback.invoke(e);
}
}
});
}
catch (Exception e)
{
e.printStackTrace();
info.callback.invoke(e);
}
}
protected void refill_finish(RefillInfo info)
{
log.debug("signUp_finish");
info.callback.invoke(true);
log.debug("signUp_finish_finished");
}
}

View File

@ -0,0 +1,125 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import core.callback.Callback;
import core.exceptions.PublicMessageException;
import core.util.LogNull;
import core.util.LogOut;
@Export()
public class JSResult<T> extends Callback implements Exportable
{
static LogNull log = new LogNull(JSResult.class);
boolean finished;
T o;
Exception e;
Object callback;
public JSResult ()
{
finished = false;
}
public JSResult (Object callback)
{
this();
this.callback = callback;
}
/* (non-Javadoc)
* @see app.service.JSResultInterface#hasException()
*/
public boolean hasException ()
{
return e != null;
}
/* (non-Javadoc)
* @see app.service.JSResultInterface#hasObject()
*/
public boolean hasObject ()
{
return o != null;
}
/* (non-Javadoc)
* @see app.service.JSResultInterface#isFinished()
*/
public synchronized boolean isFinished ()
{
return finished;
}
/* (non-Javadoc)
* @see app.service.JSResultInterface#getObject()
*/
public Object getObject ()
{
return JSInvoker.wrap(o);
}
/* (non-Javadoc)
* @see app.service.JSResultInterface#getException()
*/
public Object getException ()
{
return JSInvoker.wrap(
e != null ?
new PublicMessageException(e.getMessage()) :
null
);
}
public synchronized void setObject (T o)
{
this.o = o;
finished = true;
}
public synchronized void setException (Exception e)
{
this.e = e;
finished = true;
}
@SuppressWarnings("unchecked")
@Override
public void invoke(Object... arguments)
{
log.debug("invoke",arguments[0]);
if (arguments[0] instanceof Exception)
setException((Exception)arguments[0]);
else
setObject((T)arguments[0]);
if (callback != null)
{
try
{
JSInvoker.invoke(callback, "invoke", new Object[] {this});
}
catch (Exception e)
{
log.error(e);
throw new RuntimeException(e);
}
}
}
/* (non-Javadoc)
* @see app.service.JSResultInterface#getCallback()
*/
public Object getCallback()
{
return callback;
}
}

View File

@ -0,0 +1,585 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import java.security.NoSuchAlgorithmException;
import core.srp.client.SRPClientListener;
import java.util.Date;
import core.util.SecureRandom;
import key.auth.KeyServerAuthenticatorNoThread;
import mail.auth.MailServerAuthenticatorNoThread;
import mail.client.EventPropagator;
import core.constants.ConstantsDropbox;
import core.util.Base64;
import org.json.JSONObject;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import core.callback.Callback;
import core.callback.CallbackChain;
import core.callback.CallbackDefault;
import core.callback.CallbackWithVariables;
import core.constants.ConstantsS3;
import core.constants.ConstantsEnvironmentKeys;
import core.constants.ConstantsClient;
import core.constants.ConstantsStorage;
import core.constants.ConstantsVersion;
import core.crypt.CryptorRSAFactory;
import core.crypt.KeyPairFromPassword;
import core.io.IoChain;
import core.util.Environment;
import core.util.HttpDelegate;
import core.util.JSON_;
import core.util.JSON_.JSONException;
import core.util.LogNull;
import core.util.Pair;
import core.util.Strings;
@Export()
public class JSSignUp implements Exportable, SRPClientListener
{
static LogNull log = new LogNull(JSSignUp.class);
static SecureRandom random = new SecureRandom();
Main main;
JSSignUp (Main main)
{
this.main = main;
}
public void requestAuthorizationToken (Object callback)
{
JSResult<String> result = new JSResult<String>(callback);
try
{
String url =
"https://api.dropbox.com/1/oauth/request_token" +
"?oauth_consumer_key=" + ConstantsClient.DROPBOX_APPKEY +
"&oauth_signature_method=PLAINTEXT" +
"&oauth_signature=" + ConstantsClient.DROPBOX_APPSECRET + "%26" +
"&oauth_nonce=\"" + (new Date()).getTime() + "\"";
JSHttpDelegate http = new JSHttpDelegate(main.delegate);
http.execute(HttpDelegate.GET, url, null, false, false, null, new CallbackWithVariables(result) {
public void invoke(Object... arguments)
{
JSResult<String> result = (JSResult<String>)V(0);
try
{
if (arguments[0] instanceof Exception)
throw (Exception)arguments[0];
String response = (String)arguments[0];
String token=null, tokenSecret=null;
String[] parts = response.split("&");
for (String part : parts)
{
String[] keyValue = part.split("=");
String key = keyValue[0];
String value = keyValue[1];
if (key.equalsIgnoreCase("oauth_token_secret"))
tokenSecret = value;
else
if (key.equalsIgnoreCase("oauth_token"))
token = value;
}
Object o = JSON_.newObject();
JSON_.put(o, "key", JSON_.newString(token));
JSON_.put(o, "secret", JSON_.newString(tokenSecret));
result.invoke(o.toString());
}
catch (Exception e)
{
result.invoke(e);
}
}
});
}
catch (Exception e)
{
result.invoke(e);
}
}
public void test (String user, Object callback) throws Exception
{
log.debug("test");
JSResult<Object> result = new JSResult<Object>(callback);
String url = ConstantsClient.MAIL_SERVER_WEBSOCKET;
MailServerAuthenticatorNoThread.testCreate_(
user,
new JSStreamSessionWebSocket(url, main.delegate)
).addCallback(result).invoke();
}
static class SignUpInfo {
public static enum Storage { Mailiverse, Dropbox };
String name, password, captchaToken;
Environment serverEnvironment, clientEnvironment, completeEnvironment;
JSResult<Boolean> callback;
KeyPairFromPassword keyPair;
Storage storage;
String storageRegion;
String dropboxAppKey, dropboxAppSecret;
String dropboxAuthToken, dropboxAuthSecret;
String dropboxUserToken, dropboxUserSecret;
String awsBucketName, awsBucketRegion;
String awsWriteAccessKey, awsWriteSecretKey;
String awsReadWriteAccessKey, awsReadWriteSecretKey;
String smtpPassword;
byte[] publicKey;
byte[] privateKey;
String stripeCardNumber, stripeCardExpMonth, stripeCardExpYear, stripeCardCVC;
String stripeTransactionID;
int paymentAmount = 1;
SignUpInfo (
String name, String password, String captchaToken,
JSResult<Boolean> callback
)
{
this.name = name;
this.password = password;
this.captchaToken = captchaToken;
this.callback = callback;
this.smtpPassword = "" + Math.abs(random.nextLong());
}
void intializeStorageDropbox (
String appKey, String appSecret,
String authToken, String authSecret
)
{
this.storage = Storage.Dropbox;
this.dropboxAppKey = appKey;
this.dropboxAppSecret = appSecret;
this.dropboxAuthToken = authToken;
this.dropboxAuthSecret = authSecret;
}
void initializeStorageMailiverse (String storageRegion)
{
this.storage = Storage.Mailiverse;
this.storageRegion = storageRegion;
}
public void setDropboxInfo (String userToken, String userSecret)
{
this.dropboxUserToken = userToken;
this.dropboxUserSecret = userSecret;
}
public void setAWSInfo (
String awsBucketName, String awsBucketRegion,
String awsWriteAccessKey, String awsWriteSecretKey,
String awsReadWriteAccessKey, String awsReadWriteSecretKey)
{
this.awsBucketName = awsBucketName;
this.awsBucketRegion = awsBucketRegion;
this.awsWriteAccessKey = awsWriteAccessKey;
this.awsWriteSecretKey = awsWriteSecretKey;
this.awsReadWriteAccessKey = awsReadWriteAccessKey;
this.awsReadWriteSecretKey = awsReadWriteSecretKey;
}
public void calculateRSA (Callback callback) throws NoSuchAlgorithmException
{
new CryptorRSAFactory().generate(2048, new CallbackDefault() {
@Override
public void onSuccess(Object... arguments) throws Exception {
Pair<byte[], byte[]> pair = (Pair<byte[], byte[]>)arguments[0];
publicKey = pair.first;
privateKey = pair.second;
callback.invoke();
}
}.setReturn(callback)
);
}
public void calculateEnvironmentDropbox ()
{
String handler = ConstantsStorage.HANDLER_DROPBOX;
String prefix = handler + "/";
serverEnvironment = new Environment();
serverEnvironment.put(ConstantsEnvironmentKeys.CONFIGURATION_VERSION, ConstantsVersion.CONFIGURATION);
serverEnvironment.put(ConstantsEnvironmentKeys.HANDLER, handler);
serverEnvironment.put(ConstantsEnvironmentKeys.SMTP_PASSWORD, smtpPassword);
serverEnvironment.put(prefix + ConstantsDropbox.DropboxUserPrefix, name);
serverEnvironment.put(prefix + ConstantsDropbox.DropboxAppKey, dropboxAppKey);
serverEnvironment.put(prefix + ConstantsDropbox.DropboxAppSecret, dropboxAppSecret);
serverEnvironment.put(prefix + ConstantsDropbox.DropboxTokenKey, dropboxUserToken);
serverEnvironment.put(prefix + ConstantsDropbox.DropboxTokenSecret, dropboxUserSecret);
serverEnvironment.put(
ConstantsEnvironmentKeys.PUBLIC_ENCRYPTION_KEY,
Base64.encode(publicKey)
);
clientEnvironment = new Environment();
clientEnvironment.put(ConstantsEnvironmentKeys.CONFIGURATION_VERSION, ConstantsVersion.CONFIGURATION);
clientEnvironment.put(ConstantsEnvironmentKeys.HANDLER, handler);
clientEnvironment.put(ConstantsEnvironmentKeys.SMTP_PASSWORD, smtpPassword);
clientEnvironment.put(prefix + ConstantsDropbox.DropboxUserPrefix, name);
clientEnvironment.put(prefix + ConstantsDropbox.DropboxAppKey, dropboxAppKey);
clientEnvironment.put(prefix + ConstantsDropbox.DropboxAppSecret, dropboxAppSecret);
clientEnvironment.put(prefix + ConstantsDropbox.DropboxTokenKey, dropboxUserToken);
clientEnvironment.put(prefix + ConstantsDropbox.DropboxTokenSecret, dropboxUserSecret);
clientEnvironment.put(
ConstantsEnvironmentKeys.PUBLIC_ENCRYPTION_KEY,
Base64.encode(publicKey)
);
clientEnvironment.put(
ConstantsEnvironmentKeys.PRIVATE_DECRYPTION_KEY,
Base64.encode(privateKey)
);
completeEnvironment = new Environment();
completeEnvironment.put(ConstantsEnvironmentKeys.CONFIGURATION_VERSION, ConstantsVersion.CONFIGURATION);
completeEnvironment.addChildEnvironment(ConstantsEnvironmentKeys.SERVER_ENVIRONMENT, serverEnvironment);
completeEnvironment.addChildEnvironment(ConstantsEnvironmentKeys.CLIENT_ENVIRONMENT, clientEnvironment);
}
public void calculateEnvironmentAWS ()
{
String handler = ConstantsStorage.HANDLER_S3;
String prefix = handler + "/";
serverEnvironment = new Environment();
serverEnvironment.put(ConstantsEnvironmentKeys.CONFIGURATION_VERSION, ConstantsVersion.CONFIGURATION);
serverEnvironment.put(ConstantsEnvironmentKeys.HANDLER, handler);
serverEnvironment.put(ConstantsEnvironmentKeys.SMTP_PASSWORD, smtpPassword);
serverEnvironment.put(prefix + ConstantsS3.AWSAccessKeyId, awsWriteAccessKey);
serverEnvironment.put(prefix + ConstantsS3.AWSSecretKey, awsWriteSecretKey);
serverEnvironment.put(prefix + ConstantsS3.AWSBucketName, awsBucketName);
serverEnvironment.put(prefix + ConstantsS3.AWSBucketRegion, awsBucketRegion);
serverEnvironment.put(
ConstantsEnvironmentKeys.PUBLIC_ENCRYPTION_KEY,
Base64.encode(publicKey)
);
clientEnvironment = new Environment();
clientEnvironment.put(ConstantsEnvironmentKeys.CONFIGURATION_VERSION, ConstantsVersion.CONFIGURATION);
clientEnvironment.put(ConstantsEnvironmentKeys.HANDLER, handler);
clientEnvironment.put(ConstantsEnvironmentKeys.SMTP_PASSWORD, smtpPassword);
clientEnvironment.put(prefix + ConstantsS3.AWSAccessKeyId, awsReadWriteAccessKey);
clientEnvironment.put(prefix + ConstantsS3.AWSSecretKey, awsReadWriteSecretKey);
clientEnvironment.put(prefix + ConstantsS3.AWSBucketName, awsBucketName);
clientEnvironment.put(prefix + ConstantsS3.AWSBucketRegion, awsBucketRegion);
clientEnvironment.put(
ConstantsEnvironmentKeys.PUBLIC_ENCRYPTION_KEY,
Base64.encode(publicKey)
);
clientEnvironment.put(
ConstantsEnvironmentKeys.PRIVATE_DECRYPTION_KEY,
Base64.encode(privateKey)
);
completeEnvironment = new Environment();
completeEnvironment.put(ConstantsEnvironmentKeys.CONFIGURATION_VERSION, ConstantsVersion.CONFIGURATION);
completeEnvironment.addChildEnvironment(ConstantsEnvironmentKeys.SERVER_ENVIRONMENT, serverEnvironment);
completeEnvironment.addChildEnvironment(ConstantsEnvironmentKeys.CLIENT_ENVIRONMENT, clientEnvironment);
}
public void calculateEnvironment ()
{
if (storage == Storage.Dropbox)
calculateEnvironmentDropbox();
else
if (storage == Storage.Mailiverse)
calculateEnvironmentAWS();
}
};
public void signUp (
String storage,
String storageInfo,
String name, String password, String captchaToken,
String dropboxUserKey, String dropboxUserSecret,
Object callback
) throws JSONException
{
log.debug("signUp", name, password, captchaToken, dropboxUserKey, dropboxUserSecret);
SignUpInfo info = new SignUpInfo(
name, password, captchaToken,
new JSResult<Boolean>(callback)
);
if (storage.equals("dropbox"))
info.intializeStorageDropbox(ConstantsClient.DROPBOX_APPKEY, ConstantsClient.DROPBOX_APPSECRET, dropboxUserKey, dropboxUserSecret);
else
if (storage.equals("mailiverse"))
info.initializeStorageMailiverse(JSON_.getString(JSON_.parse(storageInfo), "region"));
CallbackChain signUpChain = new CallbackChain();
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_createRSA");
SignUpInfo info = (SignUpInfo)V(0);
info.calculateRSA(callback);
}
});
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_genKeyPair");
SignUpInfo info = (SignUpInfo)V(0);
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Creating verification key pair." });
info.keyPair = new KeyPairFromPassword(info.password);
info.keyPair.generate_().addCallback(callback).invoke();
}
});
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_createStorage");
SignUpInfo info = (SignUpInfo)V(0);
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Creating storage space." });
signUp_step_requestAccess(info, callback);
}
});
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_createEnvironments");
SignUpInfo info = V(0);
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Calculating environments." });
info.calculateEnvironment();
callback.invoke();
}
});
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_createUser");
SignUpInfo info = V(0);
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Creating user account." });
createUser(
info.name, info.keyPair, info.captchaToken,
callback
);
}
});
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_enableServer");
SignUpInfo info = V(0);
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Enabling server." });
putServerEnvironment(
info.name, info.keyPair, info.serverEnvironment,
callback
);
}
});
signUpChain.addCallback(new CallbackDefault(info) {
public void onSuccess(Object... arguments) throws Exception {
log.debug("signUp_step_enableServer");
SignUpInfo info = V(0);
JSInvoker.invoke(info.callback.getCallback(), "progress", new Object[] { "Enabling client." });
putClientEnvironment(
info.name, info.keyPair, info.completeEnvironment,
callback
);
}
});
signUpChain.addCallback(new CallbackWithVariables(info) {
@Override
public void invoke(Object... arguments) {
SignUpInfo info = (SignUpInfo)V(0);
info.callback.invoke(arguments);
}
});
main.eventPropagator.signal(
EventPropagator.INVOKE,
signUpChain
);
}
//------------------------------------------------------------------------------------------
protected void signUp_step_requestAccess (SignUpInfo info, Callback callback)
{
if (info.storage == SignUpInfo.Storage.Mailiverse)
signUp_step_requestMailiverseBucket(info, callback);
else
if (info.storage == SignUpInfo.Storage.Dropbox)
signUp_step_requestDropboxAccessToken(info, callback);
}
protected void signUp_step_requestMailiverseBucket (SignUpInfo info, Callback callback)
{
log.debug("signUp_step_requestMailiverseBucket");
String url =
ConstantsClient.WEB_SERVER_TOMCAT + "CreateBucket" +
"?email=" + info.name + "&captcha=" + info.captchaToken + "&region=" + info.storageRegion;
JSHttpDelegate http = new JSHttpDelegate(main.delegate);
http.execute(HttpDelegate.GET, url, null, false, false, null,
new CallbackDefault(info) {
public void onSuccess(Object... arguments)
{
log.debug("signUp_step_requestMailiverseBucket callback");
SignUpInfo info = V(0);
String response = (String)arguments[0];
String awsBucketName=null, awsBucketRegion=null,
awsWriteAccessKey=null, awsWriteSecretKey=null,
awsReadWriteAccessKey=null, awsReadWriteSecretKey=null;
String[] parts = response.split("&");
for (String part : parts)
{
String[] keyValue = part.split("!");
String key = keyValue[0];
String value = keyValue[1];
if (key.equalsIgnoreCase("writeAccessKey"))
awsWriteAccessKey = value;
else
if (key.equalsIgnoreCase("writeSecretKey"))
awsWriteSecretKey = value;
else
if (key.equalsIgnoreCase("readWriteAccessKey"))
awsReadWriteAccessKey = value;
else
if (key.equalsIgnoreCase("readWriteSecretKey"))
awsReadWriteSecretKey = value;
else
if (key.equalsIgnoreCase("bucketName"))
awsBucketName = value;
else
if (key.equalsIgnoreCase("bucketRegion"))
awsBucketRegion = value;
}
info.setAWSInfo(awsBucketName, awsBucketRegion, awsWriteAccessKey, awsWriteSecretKey, awsReadWriteAccessKey, awsReadWriteSecretKey);
next();
}
}.setReturn(callback)
);
}
protected void signUp_step_requestDropboxAccessToken (SignUpInfo info, Callback callback)
{
log.debug("signUp_step_requestAccessToken");
String url =
"https://api.dropbox.com/1/oauth/access_token" +
"?oauth_consumer_key=" + info.dropboxAppKey +
"&oauth_token=" + info.dropboxAuthToken + "&" +
"&oauth_signature_method=PLAINTEXT" +
"&oauth_signature=" + info.dropboxAppSecret + "%26" + info.dropboxAuthSecret +
"&oauth_nonce=\"" + (new Date()).getTime() + "\"";
JSHttpDelegate http = new JSHttpDelegate(main.delegate);
http.execute(HttpDelegate.GET, url, null, false, false, null,
new CallbackDefault(info) {
public void onSuccess(Object... arguments)
{
log.debug("signUp_step_requestAccessToken callback");
SignUpInfo info = V(0);
String response = (String)arguments[0];
String token=null, tokenSecret=null;
String[] parts = response.split("&");
for (String part : parts)
{
String[] keyValue = part.split("=");
String key = keyValue[0];
String value = keyValue[1];
if (key.equalsIgnoreCase("oauth_token_secret"))
tokenSecret = value;
else
if (key.equalsIgnoreCase("oauth_token"))
token = value;
}
info.setDropboxInfo(token, tokenSecret);
next();
}
}.setReturn(callback)
);
}
protected void createUser (String user, KeyPairFromPassword keyPair, String token, Callback callback) throws Exception
{
String url = ConstantsClient.MAIL_SERVER_WEBSOCKET;
MailServerAuthenticatorNoThread.create_(
user, keyPair, token,
new JSStreamSessionWebSocket(url, main.delegate)
).setReturn(callback).invoke();
}
protected void putServerEnvironment (String user, KeyPairFromPassword keyPair, Environment environment, Callback callback) throws Exception
{
String url = ConstantsClient.MAIL_SERVER_WEBSOCKET;
MailServerAuthenticatorNoThread.put_(
user, keyPair, environment,
new JSStreamSessionWebSocket(url, main.delegate),
JSSignUp.this
).setReturn(callback).invoke(environment);
}
protected void putClientEnvironment (String user, KeyPairFromPassword keyPair, Environment environment, Callback callback)
{
try
{
String url = ConstantsClient.KEY_SERVER_WEBSOCKET;
KeyServerAuthenticatorNoThread.put_(
user, keyPair, environment,
new JSStreamSessionWebSocket(url, main.delegate),
JSSignUp.this
).setReturn(callback).invoke(environment);
}
catch (Exception e)
{
callback.invoke(e);
}
}
public void onSRPStep (String event)
{
main.eventPropagator.signal("onAuthenticationStep", event);
}
}

View File

@ -0,0 +1,129 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import java.util.ArrayList;
import java.util.List;
import core.io.IoChain;
import core.io.IoChainFinishedException;
import core.util.LogNull;
import core.util.Strings;
@Export
public class JSStreamSessionWebSocket extends IoChain implements Exportable
{
static LogNull log = new LogNull(JSStreamSessionWebSocket.class);
boolean isOpen = false;
Object delegate;
Object socket;
List<byte[]> queued = new ArrayList<byte[]>();
public JSStreamSessionWebSocket(String url, Object delegate)
{
super(null);
this.delegate = delegate;
log.debug("JSStreamSessionWebSocket", url, delegate);
try
{
socket = JSInvoker.invoke(
delegate,
"socketConstruct",
new Object[] {
this,
url
}
);
}
catch (Exception e)
{
// work around a gwt-exporter thing, which I don't feel like fixing now
log.error(e);
}
}
@Override
public void send(byte[] data) throws Exception
{
log.debug("send:", data, data != null ? Strings.toString(data) : null);
if (data != null)
queued.add(data);
if (isOpen)
{
while (!queued.isEmpty())
{
byte[] bytes = queued.get(0);
queued.remove(0);
log.debug("sending:", bytes);
JSInvoker.invoke(
delegate,
"socketSend",
new Object[] {
socket,
Strings.toString(bytes)
}
);
}
}
}
public void onMessage (String packet)
{
try
{
log.debug("onMessage",packet);
receive(packet.getBytes());
log.debug("after recieve");
}
catch (Throwable e)
{
e.printStackTrace();
}
}
public void onEvent (String event) throws Exception
{
log.debug("onEvent", event);
if (event.equals("onOpen"))
{
isOpen = true;
send(null);
}
if (event.equals("onClose"))
{
onException(new IoChainFinishedException());
}
}
@Override
public void onException (Exception e)
{
super.onException(e);
}
@Override
public void close () throws Exception
{
if (delegate != null)
JSInvoker.invoke(
delegate,
"socketClose",
new Object[] {
socket
}
);
}
}

View File

@ -0,0 +1,88 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import java.io.IOException;
import mail.client.model.Attachments;
import mail.client.model.Body;
import mail.client.model.Header;
import mail.client.model.Identity;
import mail.client.model.Mail;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
@Export
public class MailI implements Exportable
{
Mail o;
public MailI (Mail o)
{
this.o = o;
}
public Mail deref ()
{
return o;
}
public boolean equals(MailI rhs)
{
return o == rhs.o || o.equals(rhs.o);
}
public Header getHeader()
{
return o.getHeader();
}
public void setHeader(Header header)
{
o.setHeader(header);
}
public Body getBody()
{
return o.getBody();
}
public void setBody(Body body)
{
o.setBody(body);
}
public void setBody(String text, String html)
{
o.setBody(text, html);
}
public Identity[] calculateReplyTo()
{
return o.calculateReplyTo();
}
public Body calculateReply(String signature) throws IOException
{
return o.calculateReply(signature);
}
public Attachments getAttachments()
{
return o.getAttachments();
}
public void setAttachments(Attachments attachments)
{
o.setAttachments(attachments);
}
public boolean isLoaded()
{
return o.isLoaded();
}
}

View File

@ -0,0 +1,191 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import app.service.JSClient;
import app.service.JSEventPropagator;
import app.service.JSHttpDelegate;
import app.service.JSRefill;
import app.service.JSResult;
import app.service.JSSignUp;
import app.service.JSStreamSessionWebSocket;
import mail.client.Client;
import mail.client.Events;
import core.callback.Callback;
import core.callback.CallbackChain;
import core.callback.CallbackDefault;
import core.constants.ConstantsClient;
import core.crypt.KeyPairFromPassword;
import core.srp.client.SRPClientListener;
import core.util.Environment;
import core.util.LogNull;
import core.util.LogOut;
import key.auth.KeyServerAuthenticatorNoThread;
@Export()
@SuppressWarnings("serial")
public class Main extends JSApplet implements Exportable, SRPClientListener
{
static LogNull log = new LogNull (Main.class);
static String VERSION_STRING = "M";
Object delegate;
JSEventPropagator eventPropagator;
public Main ()
{
eventPropagator = new JSEventPropagator();
eventPropagator.signal ("Loaded");
eventPropagator.add(
"Loaded", null,
new CallbackDefault () {
@Override
public void onSuccess(Object... arguments) throws Exception
{
Object window = getWindow(this);
JSInvoker.invoke(window, "onMailiverseServiceLoaded", null);
}}
);
}
/* (non-Javadoc)
* @see app.service.MainInterface#setDelegate(java.lang.Object)
*/
public void setDelegate (Object delegate)
{
log.debug("setDelegate");
this.delegate = delegate;
eventPropagator.setDelegate(delegate);
}
/* (non-Javadoc)
* @see app.service.MainInterface#garbageCollect()
*/
public void garbageCollect ()
{
System.gc();
}
/* (non-Javadoc)
* @see app.service.MainInterface#dispatchEvents()
*/
public void dispatchEvents ()
{
try
{
eventPropagator.dispatchEvents();
}
catch (Exception e)
{
log.exception(e);
}
}
/* (non-Javadoc)
* @see app.service.MainInterface#getSignUp()
*/
public JSSignUp getSignUp ()
{
return new JSSignUp(this);
}
/* (non-Javadoc)
* @see app.service.MainInterface#getRefill()
*/
public JSRefill getRefill ()
{
return new JSRefill(this);
}
public JSDelete getDelete ()
{
return new JSDelete(this);
}
//----------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see app.service.MainInterface#authenticate(java.lang.String, java.lang.String)
*/
public void authenticate (String user, String password)
{
authenticate_(user, password).invoke();
}
public Callback authenticate_ (String user, String password)
{
KeyPairFromPassword keyPair = new KeyPairFromPassword(password);
CallbackChain chain = new CallbackChain();
return chain
.addCallback(keyPair.generate_())
.addCallback(io_(user))
.addCallback(start_(user))
.addCallback(propagate_());
}
public Callback io_ (String user)
{
return new CallbackDefault(user) {
public void onSuccess(Object... arguments) throws Exception {
String user = V(0);
KeyPairFromPassword keyPair = (KeyPairFromPassword)arguments[0];
KeyServerAuthenticatorNoThread.get_(
user, keyPair,
new JSStreamSessionWebSocket(ConstantsClient.KEY_SERVER_WEBSOCKET, delegate),
Main.this
).setReturn(callback).invoke();
}
};
}
public void onSRPStep (String event)
{
eventPropagator.signal("onAuthenticationStep", event);
}
public Callback start_ (String user)
{
return new CallbackDefault(user) {
@Override
public void onSuccess(Object... arguments) throws Exception {
String user = V(0);
Environment env = (Environment)arguments[0];
JSClient client = new JSClient(
Client.start(
env, user,
new JSHttpDelegate(delegate),
eventPropagator
)
);
callback.invoke(client);
}
};
}
public Callback propagate_()
{
return new Callback () {
public void invoke(Object...arguments)
{
JSResult<Client> result = new JSResult<Client>();
result.invoke(arguments[0]);
eventPropagator.signal(Events.Login, result);
}
};
}
}

View File

@ -0,0 +1,13 @@
/**
* Author: Timothy Prepscius
* License: GPLv3 Affero + keep my name in the code!
*/
package app.service;
public class ServiceAppletRunnable
{
public static void main (String[] args) throws Exception
{
Main main = new Main();
}
}