Commits

Eugene Veretennikov committed 6c953ed

Черновая поддержка Facebook

  • Participants
  • Parent commits 7ba9b81

Comments (0)

Files changed (8)

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

+package as3snapi.networks.fbcom {
+import as3snapi.base.INetworkConfig;
+import as3snapi.base.NetworkConfigBase;
+
+public class ConfigFbcom extends NetworkConfigBase implements INetworkConfig {
+    public function ConfigFbcom() {
+    }
+}
+}

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

+package as3snapi.networks.fbcom {
+import as3snapi.api.feautures.social.SocialFeaturesInstallHelper;
+import as3snapi.base.INetworkModule;
+import as3snapi.base.INetworkModuleContext;
+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 static const SHORT_NETWORK_ID:String = "fb";
+
+    private var shortNetworkId:String;
+
+    public function ModuleFbcom(shortNetworkId:String = null) {
+        this.shortNetworkId = shortNetworkId || SHORT_NETWORK_ID;
+    }
+
+    public function isAvailable(context:INetworkModuleContext):Boolean {
+        var config:ConfigVkcom = context.getConfig() as ConfigVkcom
+        if (config == null) {
+            return false;
+        }
+        try {
+            var js:IFeatureJavaScript = context.getJavaScript();
+            if (js.isAvailable() && js.call("function(){return !!FB}")) {
+                return true;
+            }
+        } catch (e:Error) {
+            return false;
+        }
+        return false;
+    }
+
+    public function install(context:INetworkModuleContext):void {
+        var bus:IMutableBus = context.getBus();
+        var state:FbcomState = new FbcomState(context);
+
+        var js:IFeatureJavaScript = context.getJavaScript();
+        if (js.isAvailable()) {
+            context.log("Using JavaScript driver");
+        } else {
+            throw new Error();
+        }
+
+        var apiCore:FbcomApiImpl = new FbcomApiImpl(state, context, shortNetworkId);
+        bus.addFeature(IFeatureFbcomApiCore, apiCore);
+        SocialFeaturesInstallHelper.installBasicFeatures(bus, apiCore);
+        //TODO:bus.addFeature(IFeatureAsyncInit, apiCore);
+    }
+}
+}

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

+package as3snapi.networks.fbcom.features {
+public interface IFeatureFbcomApiCore {
+}
+}

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

+package as3snapi.networks.fbcom.impl {
+import as3snapi.api.feautures.social.IFeatureNetworkId;
+import as3snapi.api.feautures.social.IFeatureUserId;
+import as3snapi.api.feautures.social.invites.IFeatureInvitePopup;
+import as3snapi.api.feautures.social.profiles.IFeatureProfiles;
+import as3snapi.api.feautures.social.profiles.IProfile;
+import as3snapi.api.feautures.social.profiles.IProfilesHandler;
+import as3snapi.api.feautures.social.profiles.Profile;
+import as3snapi.api.feautures.social.uids.IFeatureAppFriendUids;
+import as3snapi.api.feautures.social.uids.IFeatureFriendUids;
+import as3snapi.api.feautures.social.uids.IIdsHandler;
+import as3snapi.base.INetworkModuleContext;
+import as3snapi.base.features.javascript.JavaScriptUtils;
+import as3snapi.networks.fbcom.features.IFeatureFbcomApiCore;
+
+public class FbcomApiImpl implements IFeatureFbcomApiCore,
+        IFeatureNetworkId,
+//        IFeatureAppId,
+        IFeatureUserId,
+//        IFeatureRefererId,
+        IFeatureInvitePopup,
+        IFeatureProfiles,
+        IFeatureAppFriendUids,
+        IFeatureFriendUids
+//        IFeatureAsyncInit
+{
+    //TODO: рефакторинг, оптимизация
+
+    private var shortNetworkId:String;
+    private var state:FbcomState;
+
+    private var jsUtils:JavaScriptUtils;
+
+    public function FbcomApiImpl(state:FbcomState, context:INetworkModuleContext, shortNetworkId:String) {
+        this.state = state;
+        this.jsUtils = context.getJavaScriptUtils();
+        this.shortNetworkId = shortNetworkId;
+        jsUtils.callSmart("FB.Canvas.setSize");
+    }
+
+    public function getShortNetworkId():String {
+        return shortNetworkId;
+    }
+
+    public function getUserId():String {
+        return state.userID;
+    }
+
+    public function getProfiles(uids:Array, handler:IProfilesHandler):void {
+        if (uids == null || uids.length <= 0) {
+            handler.onSuccess([]);
+            return;
+        }
+        jsUtils.callSmart("FB.api", "?ids=" + uids.join(',') + "&fields=id,link,name,gender", function (result:Object, ...rest):void {
+            var profiles:Array = [];
+            for each(var p:Object in result) {
+                profiles.push(parseProfile(p));
+            }
+            handler.onSuccess(profiles);
+        });
+// Меделнный вариант, по запросу на каждый профиль
+//        var profiles:Array = [];
+//
+//        function next():void {
+//            if (uids != null && uids.length > 0) {
+//                var uid:Object = uids.pop();
+//                jsUtils.callSmart("FB.api", uid, function (profile:Object, ...rest):void {
+//                    profiles.push(parseProfile(profile))
+//                    next();
+//                });
+//            } else {
+//                handler.onSuccess(profiles);
+//            }
+//        }
+//
+//        next();
+    }
+
+    private static const GENDERS:Object = {"male":"m", "female":"f"};
+
+    private function parseProfile(u:Object, ...rest):IProfile {
+        var profile:Profile = new Profile();
+        profile.userId = u.id;
+        profile.profileUrl = u.link;
+        profile.fullName = u.name;
+        profile.avatar = getImageUrl(profile.userId, 'square');
+        profile.photos = [
+            getImageUrl(profile.userId, 'small'),
+            getImageUrl(profile.userId, 'square'),
+            getImageUrl(profile.userId, 'normal'),
+            getImageUrl(profile.userId, 'large')
+        ];
+        profile.gender = GENDERS[u.gender];
+        profile.setRawData(u);
+        return profile;
+    }
+
+    public static var GRAPH_URL:String = 'https://graph.facebook.com';
+    public static var API_URL:String = 'https://api.facebook.com';
+
+    protected function getImageUrl(id:String, type:String = null):String {
+        return GRAPH_URL
+                + '/'
+                + id
+                + '/picture'
+                + (type != null ? '?type=' + type : '');
+    }
+
+    public function showInvitePopup():void {
+        //TODO: Invite message
+        jsUtils.callSmart("FB.ui", {"method":'apprequests', message:"TODO: Invite message in FbcomApiImpl.", filters:['app_non_users']}, callback);
+
+        function callback(result:Object):void {
+
+        }
+    }
+
+    public function getFriendUids(handler:IIdsHandler):void {
+        jsUtils.callSmart("FB.api", "me/friends", function (friends:Object, ...rest):void {
+            handler.onSuccess(friends.data.map(function (it:*, ...rest):* {
+                return it.id;
+            }));
+        });
+    }
+
+    public function getAppFriendUids(handler:IIdsHandler):void {
+        jsUtils.callSmart("FB.api", {"method":"friends.getAppUsers"}, function (friends:Array, ...rest):void {
+            handler.onSuccess(friends);
+        });
+    }
+
+    public function getInviter():void {
+        jsUtils.callSmart("FB.api", "/me/apprequests", function (apprequests:Object, ...rest):void {
+            //TODO inviter id
+//            try {
+//                var reqVar:Object = (apprequests as Array)[0];
+//                var requesterId:String = reqVar ? reqVar.from.id : '';
+//                callback(requesterId);
+//            } catch (e:Error) {
+//                callback(null);
+//            }
+        });
+    }
+}
+}

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

+package as3snapi.networks.fbcom.impl {
+import as3snapi.base.INetworkModuleContext;
+import as3snapi.base.features.flashvars.FlashVars;
+
+public class FbcomState {
+    public var userID:String;
+    public var accessToken:String;
+    private var signedRequest:String;
+
+    public function FbcomState(context:INetworkModuleContext) {
+        var flashVars:FlashVars = context.getFlashVars();
+        userID = flashVars.getString("userID")
+        accessToken = flashVars.getString("accessToken")
+        signedRequest = flashVars.getString("signedRequest")
+    }
+}
+}

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

+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"
+      xmlns:fb="https://www.facebook.com/2008/fbml">
+<head>
+    <title>Facebook App</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+
+    <script type="text/javascript" src="//connect.facebook.net/en_US/all.js"></script>
+    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
+    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
+</head>
+<body>
+<div id="fb-root"></div>
+
+<div id="flash-app"></div>
+
+<fb:login-button show-faces="true" width="200" max-rows="1" scope="publish_actions">
+    Login
+</fb:login-button>
+
+<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();
+    });
+
+    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>
+</html>

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

 import as3snapi.base.INetworkConfig;
 import as3snapi.base.INetworkModule;
 import as3snapi.base.features.log.FeatureLogTrace;
+import as3snapi.base.plugins.IBusModule;
+import as3snapi.base.plugins.logs.BusModuleLogHook;
+import as3snapi.networks.fbcom.ConfigFbcom;
+import as3snapi.networks.fbcom.ModuleFbcom;
 import as3snapi.networks.mailru.ConfigMailru;
 import as3snapi.networks.mailru.ModuleMailru;
 import as3snapi.networks.mock.ConfigMock;
 import as3snapi.networks.vkcom.ModuleVkcom;
 import as3snapi.networks.vkcom.features.IFeatureVkcomApiCore;
 import as3snapi.networks.vkcom.features.IFeatureVkcomApiUi;
-import as3snapi.base.plugins.IBusModule;
-import as3snapi.base.plugins.logs.BusModuleLogHook;
 
 import flash.events.MouseEvent;
 
                     new ConfigVkcom(),
                     new ConfigMailru(props.MAILRU_PRIVATE_KEY),
                     new ConfigOdnoklassnikiru(props.ODNOKLASSNIKI_SECRET_KEY),
+                    new ConfigFbcom(),
                     new ConfigMock().setData(mockData)//.setDataUrl("mock.json.html"),
                 ],
                 new <INetworkModule>[
                     new ModuleVkcom(),
                     new ModuleMailru(),
                     new ModuleOdnoklassnikiru(),
+                    new ModuleFbcom(),
                     new ModuleMock(),
                 ],
                 new <IBusModule>[

File as3stuff.nginx

 server {
 	server_name localhost;
 	listen   80;
+    access_log /var/log/nginx/localhost.access.log;
+    error_log /var/log/nginx/localhost.error.log;
+
+	location /iframe_fb.html {
+	    root /srv/www;
+	    autoindex on;
+	    expires -1;
+	    error_page 405 =200 $uri;
+	}
 
 	location / {
 	    root /srv/www;