Anonymous avatar Anonymous committed aa6f284

Рефакторинг. Больше проверок.
Таймаут на инициализацию при детекции сети. При превышении - ошибка.
Префикс сети в имени файла для снэпшота данных для mock сети.
Проверка доступности регистрации as3 коллбеков в ExternalInterafce.

Comments (0)

Files changed (12)

.idea/modules.xml

   <component name="ProjectModuleManager">
     <modules>
       <module fileurl="file://$PROJECT_DIR$/as3snapi-core/as3snapi-core.iml" filepath="$PROJECT_DIR$/as3snapi-core/as3snapi-core.iml" />
-      <module fileurl="file://$PROJECT_DIR$/core/as3snapi-core.iml" filepath="$PROJECT_DIR$/core/as3snapi-core.iml" />
       <module fileurl="file://$PROJECT_DIR$/as3snapi-sandbox/as3snapi-sandbox.iml" filepath="$PROJECT_DIR$/as3snapi-sandbox/as3snapi-sandbox.iml" />
-      <module fileurl="file://$PROJECT_DIR$/sandbox/as3snapi-sandbox.iml" filepath="$PROJECT_DIR$/sandbox/as3snapi-sandbox.iml" />
-      <module fileurl="file://$PROJECT_DIR$/as3snapi-sandbox/sandbox.iml" filepath="$PROJECT_DIR$/as3snapi-sandbox/sandbox.iml" />
     </modules>
   </component>
 </project>

as3snapi-core/src/as3snapi/ConnectionFactory.as

 import as3snapi.base.INetworkModuleContext;
 import as3snapi.base.features.IFeatureConfigGetter;
 import as3snapi.base.features.asyncinit.AsyncInitHandler;
-import as3snapi.base.features.asyncinit.IAsyncInitHandler;
 import as3snapi.base.features.asyncinit.IFeatureAsyncInit;
 import as3snapi.base.features.flashvars.FlashVars;
 import as3snapi.base.features.flashvars.IFeatureFlashVarsGetter;
 import as3snapi.utils.bus.BusImpl;
 import as3snapi.utils.bus.IMutableBus;
 
+import flash.utils.clearTimeout;
+import flash.utils.setTimeout;
+
 public class ConnectionFactory implements IConnectionFactory {
 
+    private static const CRITICAL_TIMEOUT:int = 2000;
+
     private var flashVars:FlashVars;
     private var networkModules:Vector.<INetworkModule> = new <INetworkModule>[];
     private var networkConfigs:Vector.<INetworkConfig> = new <INetworkConfig>[];
                 }
             }
         }
-        handler.onFail("");
+        handler.onFail("Detection fail");
     }
 
     private function doConnect(networkModule:INetworkModule, context:INetworkModuleContext, handler:INetworkConnectHandler):void {
         logFeatures(bus);
         var connection:NetworkConnection = new NetworkConnection(bus, context.getConfig());
 
-        //TODO Возможно стоит избавиться от кастинга
+        // таймаут
+        var timerId:uint = setTimeout(onTimeout, CRITICAL_TIMEOUT);
+        function onTimeout():void {
+            handler.onFail("Connection timeout");
+            handler = null;
+        }
+
         var log:IFeatureLog = bus.getFeature(IFeatureLog);
         if (bus.hasFeature(IFeatureAsyncInit)) {
-            log.log("Init: AsyncInit.init()...");
-            //TODO: таймаут
-            var initHandler:IAsyncInitHandler = new AsyncInitHandler(function (result:Object):void {
-                log.log("Init: ready.");
-                handler.onSuccess(connection);
-            }, function (result:Object):void {
-                handler.onFail(result);
-            });
+            log.log("IFeatureAsyncInit#init()...");
             var feature:IFeatureAsyncInit = bus.getFeature(IFeatureAsyncInit);
-            feature.init(initHandler);
+            feature.init(new AsyncInitHandler(onReady, onFail));
             bus.disable(IFeatureAsyncInit);
         } else {
+            onReady();
+        }
+
+        function onReady(result:Object = null):void {
+            clearTimeout(timerId);
             log.log("Init: ready.");
-            handler.onSuccess(connection);
+            if (handler != null) {
+                handler.onSuccess(connection);
+            }
+        }
+
+        function onFail(result:Object):void {
+            log.log("Init: fail.");
+            clearTimeout(timerId);
+            if (handler != null) {
+                handler.onFail(result);
+            }
         }
     }
 
     private function logFlashVars(bus:IMutableBus):void {
         var log:IFeatureLog = bus.getFeature(IFeatureLog);
-        log.log("FLASHVARS: ");
+        log.log("FlashVars: ");
         log.log("" + flashVars);
     }
 
             features.push(EnumUtils.getShortClassName(featureClass));
         }
         features.sort();
-        log.log("FEATURES: ");
+        log.log("Features: ");
         log.log(features.join("\n"));
     }
 

as3snapi-core/src/as3snapi/base/features/javascript/FeatureJavaScript.as

     public function addCallback(functionName:String, closure:Function):void {
         ExternalInterface.addCallback(functionName, closure);
     }
+
+    public function isCallbacksAvailable():Boolean {
+        if (ExternalInterface.available) {
+            try {
+                var fn:String = "testCallback" + Math.random();
+                ExternalInterface.addCallback(fn, function (...rest):void {
+                });
+                ExternalInterface.addCallback(fn, null);
+                return true;
+            } catch (e:Error) {
+                return false;
+            }
+        }
+        return false;
+    }
 }
 }

as3snapi-core/src/as3snapi/base/features/javascript/IFeatureJavaScript.as

 
     function addCallback(functionName:String, closure:Function):void;
 
+    function isCallbacksAvailable():Boolean;
 }
 }

as3snapi-core/src/as3snapi/networks/mailru/ModuleMailru.as

         if (config == null) {
             return false;
         }
+        if (!config.getPrivateKey()) {
+            context.log("WARNING Mail.ru Config : empty privateKey");
+            return false;
+        }
         try {
             var js:IFeatureJavaScript = context.getJavaScript();
             if (js.isAvailable() && js.call("function(){return !!mailru}")) {

as3snapi-core/src/as3snapi/networks/mock/MockDataCapture.as

     public function saveFile(fname:String = null):void {
         var fileReference:FileReference = new FileReference();
         var encodedData:String = JsonUtils.encode(data);
-        var defaultFileName:String = fname || ("user" + data.userId + ".json");
+        var defaultFileName:String = fname || ((data.shortNetworkId || "") + "-" + data.userId + ".json");
         fileReference.save(encodedData, defaultFileName);
     }
 

as3snapi-core/src/as3snapi/networks/mock/ModuleMock.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.flashvars.FlashVars;
 import as3snapi.networks.mock.features.IFeatureMockApi;
 import as3snapi.networks.mock.impl.MockApiImpl;
     public function ModuleMock() {
     }
 
-
     public function isAvailable(context:INetworkModuleContext):Boolean {
         var flashVars:FlashVars = context.getFlashVars();
         return flashVars.isEmpty() && (context.getConfig() is ConfigMock);
         var api:MockApiImpl = new MockApiImpl(context);
         bus.addFeature(IFeatureMockApi, api);
         SocialFeaturesInstallHelper.installBasicFeatures(bus, api);
+        bus.addFeature(IFeatureAsyncInit, api);
     }
 }
 }

as3snapi-core/src/as3snapi/networks/odnoklassnikiru/ModuleOdnoklassnikiru.as

         if (config == null) {
             return false;
         }
+        if (!config.getSecretKey()) {
+            context.log("WARNING Odnoklassniki.ru Config : empty secretKey");
+            return false;
+        }
 
         var flashVars:FlashVars = context.getFlashVars();
         var apiServer:String = flashVars.getString('api_server');

as3snapi-core/src/as3snapi/networks/vkcom/ModuleVkcom.as

 
         var js:IFeatureJavaScript = context.getJavaScript();
 //        if (js.isAvailable()) {
-        if (jsCallbacksAvailable(js)) {
+        if (js.isCallbacksAvailable()) {
             context.log("Using JavaScript driver");
             bus.addFeature(IFeatureVkcomRequester, new VkcomRequesterJs(state, context));
             bus.addFeature(IFeatureVkcomMethods, new VkcomMethodsJs(state, context));
         bus.addFeature(IFeatureVkcomApiCore, apiCore);
         SocialFeaturesInstallHelper.installBasicFeatures(bus, apiCore);
     }
-
-    private function jsCallbacksAvailable(js:IFeatureJavaScript):Boolean {
-        if (js.isAvailable()) {
-            try {
-                var fn:String = "testVkCallback" + getTimer();
-                js.addCallback(fn, function (...rest):void {
-                });
-                js.addCallback(fn, null);
-                return true;
-            } catch (e:Error) {
-                return false;
-            }
-        }
-        return false;
-    }
 }
 }
 

as3snapi-sandbox/src/SandboxMain.mxml

     <s:VGroup width="100%" height="100%">
         <s:HGroup width="100%">
             <s:Button label="Settings" click="button1_clickHandler(event)"/>
+            <s:Button label="Capture mock snapshot" click="button2_clickHandler(event)"/>
         </s:HGroup>
-        <ui:MainPanel width="100%" height="100%"/>
+        <ui:MainPanel id="mainPanel" width="100%" height="100%"/>
     </s:VGroup>
 
     <fx:Script><![CDATA[
         import mx.events.FlexEvent;
         import mx.managers.PopUpManager;
 
+        import sandbox.AppController;
         import sandbox.ui.PropsDlg;
 
+        private var appController:AppController;
+
         private function creationCompleteHandler(event:FlexEvent):void {
+            appController = new AppController(mainPanel);
+            appController.connect();
+            //TODO:            loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
+        }
 
-        }
+        //private function uncaughtErrorHandler(event:UncaughtErrorEvent):void {
+        //    log(event.error);
+        //}
 
         private function button1_clickHandler(event:MouseEvent):void {
             var propsDlg:PropsDlg = new PropsDlg();
             PopUpManager.addPopUp(propsDlg, this, true);
             PopUpManager.centerPopUp(propsDlg);
         }
+
+        private function button2_clickHandler(event:MouseEvent):void {
+            appController.captureMockSnapshot();
+        }
         ]]></fx:Script>
 </s:Application>

as3snapi-sandbox/src/sandbox/AppController.as

 
     public function onFail(result:Object):void {
         logLine();
+        log(result);
         log("FAIL");
-        log(result);
+        log("Click 'settings' and check application keys.");
     }
 
     public function onSuccess(connection:INetworkConnection):void {
         log("READY");
         logLine();
         try {
-            addBtn("Capture mock data", function (e:MouseEvent):void {
-                var mockCapture:MockDataCapture = new MockDataCapture(connection.getBus());
-                mockCapture.capture(function (data:Object):void {
-                    Alert.show("Captured", "Mock data", Alert.OK, view, function (e:CloseEvent):void {
-                        mockCapture.saveFile();
-                    });
-                }, function (r:Object):void {
-                    log(r);
-                });
-            });
             testBus(connection);
         } catch (e:Error) {
             log(e.getStackTrace());
     }
 
     private function testBus(connection:INetworkConnection):void {
+        //TODO: Привести в более компактный/читабельный вид
 
         var fNetworkInfo:IFeatureNetworkId = connection.getFeature(IFeatureNetworkId)
         if (fNetworkInfo != null) {
             //log("IFeatureVkUiApi - UNSUPPORTED");
         }
 
+        log("Start async tests..");
+
         var asyncs:Array = [
             function ():void {
                 var feature:IFeatureSelfProfile = connection.getFeature(IFeatureSelfProfile)
             },
         ];
 
-        log("Start async test..");
-        next();
-
         function next():void {
             logLine();
             if (asyncs.length > 0) {
                 log("Async test finished.");
             }
         }
+
+        next();
     }
 
     private function addBtn(label:String, clickHandler:Function):void {
         b.addEventListener(MouseEvent.CLICK, clickHandler);
         view.btns.addElement(b);
     }
+
+    public function captureMockSnapshot():void {
+        if (connection == null) {
+            Alert.show("Network not detected.\nData not available.");
+        } else {
+            var mockCapture:MockDataCapture = new MockDataCapture(connection.getBus());
+            mockCapture.capture(function (data:Object):void {
+                Alert.show("Captured", "Mock data", Alert.OK, view,
+                        function (e:CloseEvent):void {
+                            mockCapture.saveFile();
+                        });
+            }, function (r:Object):void {
+                log(r);
+            });
+        }
+    }
 }
 }

as3snapi-sandbox/src/sandbox/ui/MainPanel.mxml

 <?xml version="1.0"?>
 <s:VGroup xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
-          xmlns:containers="library://ns.adobe.com/flex/mx"
-          creationComplete="creationCompleteHandler(event)">
+          xmlns:containers="library://ns.adobe.com/flex/mx">
 
     <s:ButtonBar dataProvider="{pages}"/>
     <containers:ViewStack id="pages" creationPolicy="all" width="100%" height="100%">
         public var appFriendsProfiles:IList;
         [Bindable]
         public var profiles:IList = new ArrayList();
-        private var appController:AppController;
-
-        private function creationCompleteHandler(event:FlexEvent):void {
-//TODO:            loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
-            appController = new AppController(this);
-            appController.connect();
-//            setTimeout(function(){throw new Error("");},1000);
-        }
-
-        //        private function uncaughtErrorHandler(event:UncaughtErrorEvent):void {
-        //            log(event.error);
-        //        }
 
         public function log(msg:*):void {
             logTxt.text = logTxt.text + FeatureLogTrace.universalDump(msg) + "\n";
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.