Commits

Eugene Veretennikov  committed 1706180

Инициализация Facrebook API из ActionScript. Мелкие правки.

  • Participants
  • Parent commits 24a36e2

Comments (0)

Files changed (9)

File as3snapi-core/src/as3snapi/ConnectionFactory.as

 
 public class ConnectionFactory implements IConnectionFactory {
 
-    private static const CRITICAL_TIMEOUT:int = 2000;
+    private static const CRITICAL_TIMEOUT:int = 60000;
 
     private var flashVars:FlashVars;
     private var networkModules:Vector.<INetworkModule> = new <INetworkModule>[];
 
         // таймаут
         var timerId:uint = setTimeout(onTimeout, CRITICAL_TIMEOUT);
+
         function onTimeout():void {
             handler.onFail("Connection timeout");
             handler = null;

File as3snapi-core/src/as3snapi/networks/fbcom/ConfigFbcom.as

 import as3snapi.base.NetworkConfigBase;
 
 public class ConfigFbcom extends NetworkConfigBase implements INetworkConfig {
-    public function ConfigFbcom() {
+    private var appId:String;
+
+    /**
+     * @param appId опционально если FB.init и FB.login выполняется в iframe
+     */
+    public function ConfigFbcom(appId:String = null) {
+        this.appId = appId;
+    }
+
+    public function getAppId():String {
+        return appId;
     }
 }
 }

File as3snapi-core/src/as3snapi/networks/fbcom/ModuleFbcom.as

 import as3snapi.api.feautures.social.SocialFeaturesInstallHelper;
 import as3snapi.base.INetworkModule;
 import as3snapi.base.INetworkModuleContext;
+import as3snapi.base.features.asyncinit.IFeatureAsyncInit;
 import as3snapi.base.features.javascript.IFeatureJavaScript;
 import as3snapi.networks.fbcom.features.IFeatureFbcomApiCore;
 import as3snapi.networks.fbcom.impl.FbcomApiImpl;
 import as3snapi.networks.fbcom.impl.FbcomState;
-import as3snapi.networks.vkcom.ConfigVkcom;
 import as3snapi.utils.bus.IMutableBus;
 
 public class ModuleFbcom implements INetworkModule {
     }
 
     public function isAvailable(context:INetworkModuleContext):Boolean {
-        var config:ConfigVkcom = context.getConfig() as ConfigVkcom
+        var config:ConfigFbcom = context.getConfig() as ConfigFbcom;
         if (config == null) {
             return false;
         }
+        if (config.getAppId() == null && context.getFlashVars().isEmpty()) {
+            context.log("WARNING Facebook appId is null")
+        }
         try {
             var js:IFeatureJavaScript = context.getJavaScript();
             if (js.isAvailable() && js.call("function(){return !!FB}")) {
         var apiCore:FbcomApiImpl = new FbcomApiImpl(state, context, shortNetworkId);
         bus.addFeature(IFeatureFbcomApiCore, apiCore);
         SocialFeaturesInstallHelper.installBasicFeatures(bus, apiCore);
-        //TODO:bus.addFeature(IFeatureAsyncInit, apiCore);
+        bus.addFeature(IFeatureAsyncInit, apiCore);
     }
 }
 }

File as3snapi-core/src/as3snapi/networks/fbcom/features/IFeatureFbcomApiCore.as

 package as3snapi.networks.fbcom.features {
 public interface IFeatureFbcomApiCore {
+    function getSignedRequest():String;
+
+    function getAccessToken():String;
+
+    function getExpiresIn():Number;
 }
 }

File as3snapi-core/src/as3snapi/networks/fbcom/impl/FbcomApiImpl.as

 import as3snapi.api.feautures.social.uids.IFeatureFriendUids;
 import as3snapi.api.feautures.social.uids.IIdsHandler;
 import as3snapi.base.INetworkModuleContext;
+import as3snapi.base.features.asyncinit.IAsyncInitHandler;
+import as3snapi.base.features.asyncinit.IFeatureAsyncInit;
 import as3snapi.base.features.javascript.JavaScriptUtils;
+import as3snapi.networks.fbcom.ConfigFbcom;
 import as3snapi.networks.fbcom.features.IFeatureFbcomApiCore;
 
 public class FbcomApiImpl implements IFeatureFbcomApiCore,
         IFeatureInvitePopup,
         IFeatureProfiles,
         IFeatureAppFriendUids,
-        IFeatureFriendUids
-//        IFeatureAsyncInit
-{
+        IFeatureFriendUids,
+        IFeatureAsyncInit {
     //TODO: рефакторинг, оптимизация
 
     private var shortNetworkId:String;
     private var state:FbcomState;
 
     private var jsUtils:JavaScriptUtils;
+    private var config:ConfigFbcom;
 
     public function FbcomApiImpl(state:FbcomState, context:INetworkModuleContext, shortNetworkId:String) {
+        this.config = ConfigFbcom(context.getConfig());
         this.state = state;
         this.jsUtils = context.getJavaScriptUtils();
         this.shortNetworkId = shortNetworkId;
         return state.userID;
     }
 
+    public function getSignedRequest():String {
+        return state.signedRequest;
+    }
+
+    public function getAccessToken():String {
+        return state.accessToken;
+    }
+
+    public function getExpiresIn():Number {
+        return state.expiresIn;
+    }
+
+    public function init(handler:IAsyncInitHandler):void {
+        if (state.hasUserId()) {
+            handler.onSuccess("ok");
+            return;
+        }
+
+        if (config.getAppId() == null) {
+            handler.onFail("appId is null");
+            return;
+        }
+        jsUtils.callSmart("FB.init", {
+            appId:config.getAppId(), // App ID
+            status:true, // check login status
+            cookie:true, // enable cookies to allow the server to access the session
+            xfbml:true  // parse XFBML
+        });
+
+        function getLoginStatus():void {
+            jsUtils.callSmart("FB.getLoginStatus", function (response:*):void {
+                if (response.status == 'connected') {
+                    ready(response.authResponse);
+                } else if (response.status == 'not_authorized') {
+                    // the user is logged in to Facebook,
+                    // but has not authenticated your app
+                    login();
+                } else {
+                    // the user isn't logged in to Facebook.
+                    login();
+                }
+            });
+        }
+
+        function login():void {
+            jsUtils.callSmart("FB.login", function (response:*):void {
+                if (response.authResponse) {
+                    ready(response.authResponse);
+                } else {
+                    //User cancelled login or did not fully authorize.
+                    handler.onFail("cancelled")
+                }
+            });
+        }
+
+        function ready(authResponse:Object):void {
+            state.accessToken = authResponse.accessToken;
+            state.signedRequest = authResponse.signedRequest;
+            state.userID = authResponse.userID;
+            state.expiresIn = authResponse.expiresIn;
+            handler.onSuccess("ok");
+        }
+
+        getLoginStatus();
+    }
+
+
     public function getProfiles(uids:Array, handler:IProfilesHandler):void {
         if (uids == null || uids.length <= 0) {
             handler.onSuccess([]);

File as3snapi-core/src/as3snapi/networks/fbcom/impl/FbcomState.as

 public class FbcomState {
     public var userID:String;
     public var accessToken:String;
-    private var signedRequest:String;
+    public var signedRequest:String;
+    public var expiresIn:Number;
 
     public function FbcomState(context:INetworkModuleContext) {
         var flashVars:FlashVars = context.getFlashVars();
         accessToken = flashVars.getString("accessToken")
         signedRequest = flashVars.getString("signedRequest")
     }
+
+    public function hasUserId():Boolean {
+        return userID != null;
+    }
 }
 }

File as3snapi-sandbox/html-template/iframe_fb.html

 
 <script>
     $(document).ready(function () {
-        FB.init({
-            appId:'147449281941936', // App ID
-            status:true, // check login status
-            cookie:true, // enable cookies to allow the server to access the session
-            xfbml:true  // parse XFBML
-        });
-
-        FB.Event.subscribe('auth.login', function (response) {
-            // do something with response
-            getLoginStatus()
-        });
-        getLoginStatus();
+        initFlash({});
     });
 
-    function getLoginStatus() {
-        FB.getLoginStatus(function (response) {
-            if (response.status === 'connected') {
-                // the user is logged in and has authenticated your
-                // app, and response.authResponse supplies
-                // the user's ID, a valid access token, a signed
-                // request, and the time the access token
-                // and signed request each expire
-                var uid = response.authResponse.userID;
-                var accessToken = response.authResponse.accessToken;
-
-                initFlash(response.authResponse);
-            } else if (response.status === 'not_authorized') {
-                // the user is logged in to Facebook,
-                // but has not authenticated your app
-                login();
-            } else {
-                // the user isn't logged in to Facebook.
-                login();
-            }
-        });
-    }
-
-    function logout() {
-        FB.logout(function (response) {
-            // user is now logged out
-            alert("logout")
-        });
-    }
-
-    function login() {
-        FB.login(function (response) {
-            if (response.authResponse) {
-                console.log('Welcome!  Fetching your information.... ');
-                FB.api('/me', function (response) {
-                    console.log('Good to see you, ' + response.name + '.');
-                });
-            } else {
-                console.log('User cancelled login or did not fully authorize.');
-            }
-        });
-    }
-
     function initFlash(flashVars) {
         var params = []
         for (var k in flashVars) {
         }
     }
 
+    // JavaScript start
+    //    $(document).ready(function () {
+    //        FB.init({
+    //            appId:'147449281941936', // App ID
+    //            status:true, // check login status
+    //            cookie:true, // enable cookies to allow the server to access the session
+    //            xfbml:true  // parse XFBML
+    //        });
+    //
+    //        FB.Event.subscribe('auth.login', function (response) {
+    //            // do something with response
+    //            getLoginStatus()
+    //        });
+    //        getLoginStatus();
+    //    });
+    //
+    //    function getLoginStatus() {
+    //        FB.getLoginStatus(function (response) {
+    //            if (response.status === 'connected') {
+    //                // the user is logged in and has authenticated your
+    //                // app, and response.authResponse supplies
+    //                // the user's ID, a valid access token, a signed
+    //                // request, and the time the access token
+    //                // and signed request each expire
+    //                var uid = response.authResponse.userID;
+    //                var accessToken = response.authResponse.accessToken;
+    //
+    //                initFlash(response.authResponse);
+    //            } else if (response.status === 'not_authorized') {
+    //                // the user is logged in to Facebook,
+    //                // but has not authenticated your app
+    //                login();
+    //            } else {
+    //                // the user isn't logged in to Facebook.
+    //                login();
+    //            }
+    //        });
+    //    }
+    //
+    //    function logout() {
+    //        FB.logout(function (response) {
+    //            // user is now logged out
+    //            alert("logout")
+    //        });
+    //    }
+    //
+    //    function login() {
+    //        FB.login(function (response) {
+    //            if (response.authResponse) {
+    //                console.log('Welcome!  Fetching your information.... ');
+    //                FB.api('/me', function (response) {
+    //                    console.log('Good to see you, ' + response.name + '.');
+    //                });
+    //            } else {
+    //                console.log('User cancelled login or did not fully authorize.');
+    //            }
+    //        });
+    //    }
+    //
+    //    function initFlash(flashVars) {
+    //        var params = []
+    //        for (var k in flashVars) {
+    //            params.push(encodeURIComponent(k) + "=" + encodeURIComponent(flashVars[k]))
+    //        }
+    //        flashVars = params.join("&");
+    //
+    //        var flashId = 'flash-app';
+    //        var data = 'as3snapi-sandbox.swf';
+    //
+    //        var attr = {name:flashId, data:data, width:760, height:660};
+    //        var param = {
+    //            allowscriptaccess:'always',
+    //            allownetworking:'all',
+    //            allowfullscreen:true,
+    //            wmode:'opaque',
+    //            flashvars:flashVars
+    //        }
+    //        if (swfobject.hasFlashPlayerVersion('11.0.0')) {
+    //            swfobject.createSWF(attr, param, flashId);
+    //        } else {
+    //            attr.data = 'http://swfobject.googlecode.com/svn/trunk/swfobject/expressInstall.swf';
+    //            swfobject.showExpressInstall(att, {}, flash.id);
+    //        }
+    //    }
+
+
 </script>
 
 </body>

File as3snapi-sandbox/src/sandbox/AppController.as

 import as3snapi.base.plugins.logs.BusModuleLogHook;
 import as3snapi.networks.fbcom.ConfigFbcom;
 import as3snapi.networks.fbcom.ModuleFbcom;
+import as3snapi.networks.fbcom.features.IFeatureFbcomApiCore;
 import as3snapi.networks.mailru.ConfigMailru;
 import as3snapi.networks.mailru.ModuleMailru;
 import as3snapi.networks.mock.ConfigMock;
                     new ConfigVkcom(),
                     new ConfigMailru(props.MAILRU_PRIVATE_KEY),
                     new ConfigOdnoklassnikiru(props.ODNOKLASSNIKI_SECRET_KEY),
-                    new ConfigFbcom(),
+                    new ConfigFbcom(props.FACEBOOK_APP_ID),
                     new ConfigMock().setData(mockData)//.setDataUrl("mock.json.html"),
                 ],
                 new <INetworkModule>[
         logLine();
         log(result);
         log("FAIL");
+        log("Check 'WARNINGS' in log.");
         log("Click 'settings' and check application keys.");
     }
 
             //log("IFeatureVkUiApi - UNSUPPORTED");
         }
 
+        var fFbApi:IFeatureFbcomApiCore = connection.getFeature(IFeatureFbcomApiCore)
+        if (fFbApi != null) {
+            log("IFeatureFbcomApiCore.getAccessToken: " + fFbApi.getAccessToken());
+            log("IFeatureFbcomApiCore.getSignedRequest: " + fFbApi.getSignedRequest());
+            log("IFeatureFbcomApiCore.getExpiresIn: " + fFbApi.getExpiresIn());
+        } else {
+//            log("IFeatureFbcomApiCore - UNSUPPORTED");
+        }
+
         log("Start async tests..");
 
         var asyncs:Array = [

File as3snapi-sandbox/src/sandbox/Settings.as

 
     public var MAILRU_PRIVATE_KEY:String;
     public var ODNOKLASSNIKI_SECRET_KEY:String;
+    public var FACEBOOK_APP_ID:String;
 
     public var keys:Array = [
         "MAILRU_PRIVATE_KEY",
-        "ODNOKLASSNIKI_SECRET_KEY"
+        "ODNOKLASSNIKI_SECRET_KEY",
+        "FACEBOOK_APP_ID",
     ];
 
     public function Settings() {