Skip to content

Instantly share code, notes, and snippets.

@tong
Last active October 1, 2015 14:08
Show Gist options
  • Save tong/2005771 to your computer and use it in GitHub Desktop.
Save tong/2005771 to your computer and use it in GitHub Desktop.
C2DM test script
package android;
/**
Android Cloud 2 Device Messenger.
*/
class C2DMessenger {
public static inline var C2DM_URL_LOGIN = "https://www.google.com/accounts/ClientLogin";
public static inline var C2DM_URL_SEND = "https://android.apis.google.com/c2dm/send";
/** */
public var data : Dynamic;
/** */
public var registrationId : String;
/** */
public var email : String;
/** */
public var password : String;
/** */
public var source : String;
/** */
public var service : String;
/***/
public var collapse_key : String;
var token : String;
var requestingToken : Bool;
public function new( email : String, password : String, source : String, registrationId : String,
service : String = 'ac2dm', collapse_key : String = "1" ) {
this.email = email;
this.password = password;
this.source = source;
this.registrationId = registrationId;
this.service = service;
this.collapse_key = collapse_key;
requestingToken = false;
}
public function send( data : Dynamic, ?cb : String->Void ) {
if( token == null ) {
if( requestingToken )
return;
getToken(function(t){
if( t == null ) {
trace("Failed to auth");
//TODO
}
token = t;
sendMessage( data, cb );
});
} else {
sendMessage( data, cb );
}
}
function sendMessage( data : Dynamic, ?cb : String->Void ) {
//TODO check data size 1024 max
var r = new haxe.Http( C2DM_URL_SEND );
r.onStatus = function(s:Int) {
//trace("STATUS>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><"+s);
}
r.onError = function(e:String) {
trace("ERROR: "+e);
//TODO
}
r.onData = cb;
for( f in Reflect.fields( data ) ) {
r.setParameter( "data."+f, Reflect.field( data, f ) );
}
r.setParameter( "registration_id", registrationId );
r.setParameter( "collapse_key", collapse_key );
r.setHeader( "Authorization", 'GoogleLogin auth='+token );
r.request(true);
}
function getToken( cb : String->Void ) {
requestingToken = true;
var r = new haxe.Http( C2DM_URL_LOGIN );
r.onData = function(d:String) {
var token = d.split("\n")[2].substr(5);
requestingToken = false;
cb( token );
}
r.onError = function(e:String) {
trace(e);
requestingToken = false;
cb(null);
}
r.onStatus = function(s:Int) {
}
r.setParameter( "accountType", "GOOGLE" );
r.setParameter( "Email", email );
r.setParameter( "Passwd", password );
r.setParameter( "source", source );
r.setParameter( "service", service );
r.request(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment