Skip to content

Instantly share code, notes, and snippets.

@calimaborges
Created August 27, 2014 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calimaborges/97705c49a55718223968 to your computer and use it in GitHub Desktop.
Save calimaborges/97705c49a55718223968 to your computer and use it in GitHub Desktop.
Cocoon Facebook Work In Progress
if (!(typeof window.CocoonJS === 'undefined' || window.CocoonJS === null)) { // BEGIN - CHECK FOR COCOONJS
(function() {
// The CocoonJS and CocoonJS.Social must exist before creating the extension.
if (typeof window.CocoonJS === 'undefined' || window.CocoonJS === null) throw("The CocoonJS object must exist and be valid before creating the extension types.");
if (typeof window.CocoonJS.Social === 'undefined' || window.CocoonJS.Social === null) throw("The CocoonJS.Social object must exist and be valid before creating the extension types.");
/**
* @class
* @constructor
* Represents a type that mimics the original Facebook API with the addition of the possibility to
* retrieve an abstract high level interface API to handle a SocialGamingService (APIs defined by Ludei).
*/
CocoonJS.Social.FacebookExtension = function (){
this.nativeExtensionName = "IDTK_SRV_FACEBOOK";
this.extensionName = "Social.Facebook";
this.nativeExtensionObjectAvailable = CocoonJS.nativeExtensionObjectAvailable && typeof window.ext[this.nativeExtensionName] !== 'undefined';
this.Event = new CocoonJS.Social.FacebookEvent(this.nativeExtensionObjectAvailable);
var me = this;
if (this.nativeExtensionObjectAvailable) {
this.onFacebookSessionStateChanged = new CocoonJS.EventHandler(this.nativeExtensionName, this.extensionName, "onFacebookSessionStateChanged");
CocoonJS.Social.Facebook = this; //the object it's being created but the addEventListener needs it now
this.onFacebookSessionStateChanged.addEventListener(function(session, error) {
var data = fromCocoonFBSessionToFBAPISession(session,error);
if (session.state == 0) {
me.Event.notify("auth.login", data);
}
me.Event.notify("auth.authResponseChange", data);
me.Event.notify("auth.statusChange", data);
});
}
return this;
};
CocoonJS.Social.FacebookExtension.prototype = {
_currentSession: null,
_appId: null,
_socialService: null,
/**
* Initialize the SDK with your app ID. This will let you make calls against the Facebook API. All FB.API methods must be called after FB.init.
* @param {object} options. Check available options here: https://developers.facebook.com/docs/reference/javascript/FB.init/
*/
init: function(options) {
if (!options || !options.appId) {
throw "appId must be specified!";
}
this._appId = options.appId;
if (this.nativeExtensionObjectAvailable) {
console && console.log("Making native call: init with options " + JSON.stringify(options));
CocoonJS.makeNativeExtensionObjectFunctionCall(this.nativeExtensionName, "init", [options], true);
}
else {
FB.init(options);
}
var me = this;
this.Event.subscribe("auth.authResponseChange", function(session) {
me._currentSession = session;
if (session.authResponse && !session.authResponse.user){
me.api("me?fields=username", function(response) {
me._currentSession.authResponse.user = response;
});
}
});
},
/**
* Return a CocoonJS SocialGaming interface for the Facebook Extension
* You can use the Facebook extension in two ways, with the official SDK API equivalent or with the CocoonJS Social API abstraction
* @see CocoonJS.Social.SocialGamingService
* @returns {CocoonJS.Social.SocialGamingService}
*/
getSocialInterface: function() {
if (!this._appId) {
throw "You must call init() before getting the Social Interface";
}
if (!this._socialService) {
this._socialService = new CocoonJS.Social.SocialGamingServiceFacebook(this);
}
return this._socialService;
},
/**
* Authenticate the user
* By default, calling login will attempt to authenticate the user with only the basic permissions.
* If you want one or more additional permissions, call login with an option object,
* and set the scope parameter with a comma-separated list of the permissions you wish to request from the user
* @param {object} login options
* @params {function} callback The callback function with received session data or error.
*/
login: function(callback, options) {
var me = this;
if (this.nativeExtensionObjectAvailable) {
CocoonJS.makeNativeExtensionObjectFunctionCall(this.nativeExtensionName, "login", [options, function(response, error) {
me._currentSession = fromCocoonFBSessionToFBAPISession(response,error);
if (callback) {
callback(me._currentSession);
}
}], true);
}
else {
FB.login(function(response){
me._currentSession = response;
if (callback)
callback(response);
}, options);
}
},
};
CocoonJS.Social.FacebookEvent = function(nativeAvailable ) {
this.nativeExtensionObjectAvailable = nativeAvailable;
return this;
};
CocoonJS.Social.FacebookEvent.prototype = {
/**
* Global Events to which you can subscribe:
* auth.login - fired when the auth status changes from unknown to connected
* auth.authResponseChange - fired when the authResponse changes
* auth.statusChange - fired when the status changes
* @param name Name of the event
* @param callback The handler function
*/
subscribe: function(name, callback){
if (this.nativeExtensionObjectAvailable)
{
var eventKey = name + 'listeners';
this[eventKey] = this[eventKey] || [];
this[eventKey].push(callback);
}
else if (!navigator.isCocoonJS)
{
FB.Event.subscribe(name,callback);
}
},
/**
* Removes handlers on events so that it no longer invokes your callback when the event fires.
* @param name Name of the event.
* @param callback The handler function.
*/
unsubscribe: function(name, callback) {
if (this.nativeExtensionObjectAvailable)
{
var eventKey = name + 'listeners';
var array = this[eventKey];
if (array) {
var index = array.indexOf(callback);
if (index !== -1) {
array.splice(index,1);
}
}
}
else if (!navigator.isCocoonJS)
{
FB.Event.unsubscribe(name,callback);
}
},
/**
* @ignore
*/
notify: function(name, param) {
var eventKey = name + 'listeners';
var array = this[eventKey];
if (array) {
for (var i = 0; i< array.length; ++i) {
array[i](param);
}
}
}
};
CocoonJS.Social.Facebook = new CocoonJS.Social.FacebookExtension();
/**
* @ignore
*/
function fromCocoonFBStatusToFBAPIState(state) {
if (state === 0) {
return "connected";
}
else if (state === 1) {
return "not_authorized";
}
else {
return "unknown";
}
}
/**
* @ignore
*/
function fromCocoonFBSessionToFBAPISession(response, error) {
var authResponse = null;
if (response.state === 0) {
authResponse = {
accessToken: response.accessToken,
expirationDate: response.expirationDate,
userID: response.user ? response.userID : null,
permissions: response.permissions,
user: response.user
}
}
return {
status: fromCocoonFBStatusToFBAPIState(response.state),
authResponse: authResponse,
error: error
}
};
console && console.log("CHEGAMOS AQUI - DE VERDADE");
})();
} // END - CHECK FOR COCOONJS
cr.plugins_.CJSExtended = function(runtime)
{
this.runtime = runtime;
};
(function ()
{
var pluginProto = cr.plugins_.CJSExtended.prototype;
pluginProto.Type = function(plugin)
{
this.plugin = plugin;
this.runtime = plugin.runtime;
};
var typeProto = pluginProto.Type.prototype;
typeProto.onCreate = function()
{
};
var fbAppID = null;
var fbScoreImageURL = null;
var fbScore = null;
var fbUserID = null;
var fbUsername = null;
pluginProto.Instance = function(type)
{
this.type = type;
this.runtime = type.runtime;
};
var instanceProto = pluginProto.Instance.prototype;
instanceProto.onCreate = function()
{
this.socialService = null;
this.socialServiceAvailable = false;
var self = this;
if (!this.runtime.isCocoonJs)
{
cr.logexport("[Construct 2 - CocoonJS Extended] CocoonJS Extended plugin not supported on this platform - the object will not be created");
console && console.error("[CocoonJS Extended] Not CocoonJS");
return;
}
fbAppID = this.properties[0];
this.socialService = CocoonJS["Social"]["Facebook"];
this.socialServiceAvailable = !!this.socialService["nativeExtensionObjectAvailable"];
this.socialService.init({
appId: fbAppID
});
// var socialInterface = this.socialService.getSocialInterface();
// console && console.log("Social Interface: " + JSON.stringify(socialInterface));
this.socialService.login(function(currentSession) {
console && console.log("Session: " + JSON.stringify(currentSession));
}, {});
var that = this;
var counter = 0;
this.socialService.Event.subscribe("auth.authResponseChange", function (session, error) {
console && console.error('CHEGOU: ' + JSON.stringify(session));
console && console.error('CHEGOU: ' + JSON.stringify(error));
if (error) {
counter++;
console && console.error('Trying again...' + counter);
if (counter < 5) {
that.socialService.login(function(currentSession) {
console && console.log("Session: " + JSON.stringify(currentSession));
}, {});
}
}
});
};
instanceProto.onDestroy = function () {};
instanceProto.saveToJSON = function () {
return {
};
};
instanceProto.loadFromJSON = function (o) {
};
instanceProto.draw = function(ctx) {};
instanceProto.drawGL = function (glw) {};
function Cnds() {};
Cnds.prototype.IsFBAvailable = function ()
{
return this.socialServiceAvailable;
};
Cnds.prototype.IsFBLoggedIn = function ()
{
if (!this.socialServiceAvailable) {
return false;
}
return this.socialService["isLoggedIn"]();
};
Cnds.prototype.OnFBLoginSuccess = function ()
{
return true;
};
Cnds.prototype.OnFBLoginFail = function ()
{
return true;
};
Cnds.prototype.OnFBLogout = function ()
{
return true;
};
Cnds.prototype.OnFBScoreReceived = function ()
{
return true;
};
Cnds.prototype.OnFBScoreUnavailable = function ()
{
return true;
};
Cnds.prototype.OnFBScoreSubmitSuccess = function ()
{
return true;
};
Cnds.prototype.OnFBScoreSubmitFail = function ()
{
return true;
};
Cnds.prototype.OnFBLeaderboardSucceeded = function ()
{
return true;
};
Cnds.prototype.OnFBLeaderboardFailed = function ()
{
return true;
};
Cnds.prototype.OnFBLeaderboardClose = function ()
{
return true;
};
Cnds.prototype.OnFBReady = function ()
{
return true;
};
Cnds.prototype.IsFBReady = function ()
{
if (!this.socialServiceAvailable) {
return false;
}
return this.socialService["isInitialized"]();
};
Cnds.prototype.OnFBInitFail = function ()
{
return true;
};
Cnds.prototype.OnFBLeaderboardScore = function ()
{
return true;
};
pluginProto.cnds = new Cnds();
function Acts() {};
Acts.prototype.FBLogin = function ()
{
console && console.log("[Construct 2 - CocoonJS Extended] Logging in.");
if (!this.socialServiceAvailable) {
console && console.error("[Construct 2 - CocoonJS Extended] Can't login to Facebook. CocoonJS Extended not available.");
return;
}
if (this.socialService["isLoggedIn"]()) {
return;
}
this.socialService["requestLogin"]();
};
Acts.prototype.FBLogout = function ()
{
console && console.log("[Construct 2 - CocoonJS Extended] Logging out.");
if (!this.socialServiceAvailable || !this.socialService["isLoggedIn"]()) {
console && console.error("[Construct 2 - CocoonJS Extended] Service unavailable.");
return;
}
this.socialService["requestLogout"]();
};
Acts.prototype.FBSubmitScore = function (score_)
{
console && console.log("[Construct 2 - CocoonJS Extended] Submitting score: " + score_);
if (!this.socialServiceAvailable || !this.socialService["isLoggedIn"]()) {
console && console.error("[Construct 2 - CocoonJS Extended] Service unavailable.");
return;
}
this.socialService["submitUserScore"](score_);
};
Acts.prototype.FBRequestScore = function ()
{
if (!this.socialServiceAvailable || !this.socialService["isLoggedIn"]()) {
console && console.error("[Construct 2 - CocoonJS Extended] Service unavailable.");
return;
}
this.socialService["requestUserScore"]();
};
Acts.prototype.FBRequestScoreboard = function ()
{
console && console.log("[Construct 2 - CocoonJS Extended] Opened Leaderboard.");
if (!this.socialServiceAvailable || !this.socialService["isLoggedIn"]()) {
console && console.error("[Construct 2 - CocoonJS Extended] Service unavailable.");
return;
}
this.socialService["requestUserAndFriendsScores"]();
};
pluginProto.acts = new Acts();
function Exps() {};
Exps.prototype.FacebookScore = function (ret)
{
ret.set_int(fbScore);
};
Exps.prototype.FacebookImageUrl = function (ret)
{
ret.set_string(fbScoreImageURL);
};
Exps.prototype.FacebookUserID = function (ret)
{
ret.set_int(fbUserID);
};
Exps.prototype.FacebookUsername = function (ret)
{
ret.set_string(fbUsername);
};
Exps.prototype.FacebookRank = function (ret)
{
ret.set_int(fbRank);
};
Exps.prototype.CurrentTimestamp = function (ret)
{
ret.set_int(Math.round(Date.now() / 1000));
};
pluginProto.exps = new Exps();
}());
@HikeNH
Copy link

HikeNH commented Aug 27, 2014

Awesome work so far. The login works ok?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment