home *** CD-ROM | disk | FTP | other *** search
/ 404 Jogos / CLJG.iso / Diversos / Beez.swf / scripts / mochi / MochiServices.as < prev   
Encoding:
Text File  |  2008-09-03  |  16.3 KB  |  548 lines

  1. package mochi
  2. {
  3.    import flash.display.DisplayObject;
  4.    import flash.display.Loader;
  5.    import flash.display.MovieClip;
  6.    import flash.display.Sprite;
  7.    import flash.events.Event;
  8.    import flash.events.IOErrorEvent;
  9.    import flash.events.StatusEvent;
  10.    import flash.events.TimerEvent;
  11.    import flash.net.LocalConnection;
  12.    import flash.net.URLRequest;
  13.    import flash.system.Security;
  14.    import flash.utils.Timer;
  15.    import flash.utils.getTimer;
  16.    
  17.    public class MochiServices
  18.    {
  19.       
  20.       private static var _container:Object;
  21.       
  22.       private static var _connected:Boolean = false;
  23.       
  24.       private static var _swfVersion:String;
  25.       
  26.       private static var _sendChannel:LocalConnection;
  27.       
  28.       private static var _rcvChannelName:String;
  29.       
  30.       private static var _gatewayURL:String = "http://www.mochiads.com/static/lib/services/services.swf";
  31.       
  32.       private static var _clip:MovieClip;
  33.       
  34.       private static var _loader:Loader;
  35.       
  36.       private static var _id:String;
  37.       
  38.       private static var _listenChannel:LocalConnection;
  39.       
  40.       private static var _timer:Timer;
  41.       
  42.       private static var _sendChannelName:String;
  43.       
  44.       private static var _startTime:Number;
  45.       
  46.       private static var _connecting:Boolean = false;
  47.       
  48.       public static var onError:Object;
  49.       
  50.       private static var _listenChannelName:String = "__mochiservices";
  51.       
  52.       private static var _rcvChannel:LocalConnection;
  53.        
  54.       
  55.       public function MochiServices()
  56.       {
  57.          super();
  58.       }
  59.       
  60.       public static function isNetworkAvailable() : Boolean
  61.       {
  62.          return Security.sandboxType != "localWithFile";
  63.       }
  64.       
  65.       public static function send(methodName:String, args:Object = null, callbackObject:Object = null, callbackMethod:Object = null) : void
  66.       {
  67.          if(_connected)
  68.          {
  69.             _sendChannel.send(_sendChannelName,"onReceive",{
  70.                "methodName":methodName,
  71.                "args":args,
  72.                "callbackID":_clip._nextcallbackID
  73.             });
  74.          }
  75.          else
  76.          {
  77.             if(_clip == null || !_connecting)
  78.             {
  79.                onError("NotConnected");
  80.                handleError(args,callbackObject,callbackMethod);
  81.                flush(true);
  82.                return;
  83.             }
  84.             _clip._queue.push({
  85.                "methodName":methodName,
  86.                "args":args,
  87.                "callbackID":_clip._nextcallbackID
  88.             });
  89.          }
  90.          if(_clip != null)
  91.          {
  92.             if(_clip._callbacks != null && _clip._nextcallbackID != null)
  93.             {
  94.                _clip._callbacks[_clip._nextcallbackID] = {
  95.                   "callbackObject":callbackObject,
  96.                   "callbackMethod":callbackMethod
  97.                };
  98.                ++_clip._nextcallbackID;
  99.             }
  100.          }
  101.       }
  102.       
  103.       public static function get connected() : Boolean
  104.       {
  105.          return _connected;
  106.       }
  107.       
  108.       private static function flush(error:Boolean) : void
  109.       {
  110.          var request:Object = null;
  111.          var callback:Object = null;
  112.          if(_clip != null)
  113.          {
  114.             if(_clip._queue != null)
  115.             {
  116.                while(_clip._queue.length > 0)
  117.                {
  118.                   request = _clip._queue.shift();
  119.                   callback = null;
  120.                   if(request != null)
  121.                   {
  122.                      if(request.callbackID != null)
  123.                      {
  124.                         callback = _clip._callbacks[request.callbackID];
  125.                      }
  126.                      delete _clip._callbacks[request.callbackID];
  127.                      if(error && callback != null)
  128.                      {
  129.                         handleError(request.args,callback.callbackObject,callback.callbackMethod);
  130.                      }
  131.                   }
  132.                }
  133.             }
  134.          }
  135.       }
  136.       
  137.       private static function init(id:String, clip:Object) : void
  138.       {
  139.          _id = id;
  140.          if(clip != null)
  141.          {
  142.             _container = clip;
  143.             loadCommunicator(id,_container);
  144.          }
  145.       }
  146.       
  147.       public static function get childClip() : Object
  148.       {
  149.          return _clip;
  150.       }
  151.       
  152.       public static function get id() : String
  153.       {
  154.          return _id;
  155.       }
  156.       
  157.       public static function stayOnTop() : void
  158.       {
  159.          _container.addEventListener(Event.ENTER_FRAME,MochiServices.bringToTop,false,0,true);
  160.          if(_clip != null)
  161.          {
  162.             _clip.visible = true;
  163.          }
  164.       }
  165.       
  166.       public static function getVersion() : String
  167.       {
  168.          return "1.32";
  169.       }
  170.       
  171.       public static function disconnect() : void
  172.       {
  173.          if(_connected || _connecting)
  174.          {
  175.             if(_clip != null)
  176.             {
  177.                if(_clip.parent != null)
  178.                {
  179.                   if(_clip.parent is Sprite)
  180.                   {
  181.                      Sprite(_clip.parent).removeChild(_clip);
  182.                      _clip = null;
  183.                   }
  184.                }
  185.             }
  186.             _connecting = _connected = false;
  187.             flush(true);
  188.             try
  189.             {
  190.                _listenChannel.close();
  191.                _rcvChannel.close();
  192.             }
  193.             catch(error:Error)
  194.             {
  195.             }
  196.          }
  197.          if(_timer != null)
  198.          {
  199.             try
  200.             {
  201.                _timer.stop();
  202.             }
  203.             catch(error:Error)
  204.             {
  205.             }
  206.          }
  207.       }
  208.       
  209.       public static function allowDomains(server:String) : String
  210.       {
  211.          var hostname:String = null;
  212.          Security.allowDomain("*");
  213.          Security.allowInsecureDomain("*");
  214.          if(server.indexOf("http://") != -1)
  215.          {
  216.             hostname = String(server.split("/")[2].split(":")[0]);
  217.             Security.allowDomain(hostname);
  218.             Security.allowInsecureDomain(hostname);
  219.          }
  220.          return hostname;
  221.       }
  222.       
  223.       public static function doClose() : void
  224.       {
  225.          _container.removeEventListener(Event.ENTER_FRAME,MochiServices.bringToTop);
  226.          if(_clip.parent != null)
  227.          {
  228.             Sprite(_clip.parent).removeChild(_clip);
  229.          }
  230.       }
  231.       
  232.       public static function setContainer(container:Object = null, doAdd:Boolean = true) : void
  233.       {
  234.          if(container != null)
  235.          {
  236.             if(container is Sprite)
  237.             {
  238.                _container = container;
  239.             }
  240.          }
  241.          if(doAdd)
  242.          {
  243.             if(_container is Sprite)
  244.             {
  245.                Sprite(_container).addChild(_clip);
  246.             }
  247.          }
  248.       }
  249.       
  250.       private static function onStatus(event:StatusEvent) : void
  251.       {
  252.          switch(event.level)
  253.          {
  254.             case "error":
  255.                _connected = false;
  256.                _listenChannel.connect(_listenChannelName);
  257.          }
  258.       }
  259.       
  260.       private static function initComChannels() : void
  261.       {
  262.          if(!_connected)
  263.          {
  264.             _sendChannel.addEventListener(StatusEvent.STATUS,MochiServices.onStatus);
  265.             _sendChannel.send(_sendChannelName,"onReceive",{"methodName":"handshakeDone"});
  266.             _sendChannel.send(_sendChannelName,"onReceive",{
  267.                "methodName":"registerGame",
  268.                "id":_id,
  269.                "clip":_container,
  270.                "version":getVersion()
  271.             });
  272.             _rcvChannel.addEventListener(StatusEvent.STATUS,MochiServices.onStatus);
  273.             _clip.onReceive = function(pkg:Object):void
  274.             {
  275.                var method:*;
  276.                var obj:Object;
  277.                var methodName:String = null;
  278.                var cb:String = String(pkg.callbackID);
  279.                var cblst:Object = this.client._callbacks[cb];
  280.                if(!cblst)
  281.                {
  282.                   return;
  283.                }
  284.                method = cblst.callbackMethod;
  285.                methodName = "";
  286.                obj = cblst.callbackObject;
  287.                if(Boolean(obj) && typeof method == "string")
  288.                {
  289.                   methodName = method;
  290.                   if(obj[method] != null)
  291.                   {
  292.                      method = obj[method];
  293.                   }
  294.                   else
  295.                   {
  296.                      trace("Error: Method  " + method + " does not exist.");
  297.                   }
  298.                }
  299.                if(method != undefined)
  300.                {
  301.                   try
  302.                   {
  303.                      method.apply(obj,pkg.args);
  304.                   }
  305.                   catch(error:Error)
  306.                   {
  307.                      trace("Error invoking callback method \'" + methodName + "\': " + error.toString());
  308.                   }
  309.                }
  310.                else if(obj != null)
  311.                {
  312.                   try
  313.                   {
  314.                      obj(pkg.args);
  315.                   }
  316.                   catch(error:Error)
  317.                   {
  318.                      trace("Error invoking method on object: " + error.toString());
  319.                   }
  320.                }
  321.                delete this.client._callbacks[cb];
  322.             };
  323.             _clip.onError = function():void
  324.             {
  325.                MochiServices.onError("IOError");
  326.             };
  327.             _rcvChannel.connect(_rcvChannelName);
  328.             trace("connected!");
  329.             _connecting = false;
  330.             _connected = true;
  331.             _listenChannel.close();
  332.             while(_clip._queue.length > 0)
  333.             {
  334.                _sendChannel.send(_sendChannelName,"onReceive",_clip._queue.shift());
  335.             }
  336.          }
  337.       }
  338.       
  339.       private static function listen() : void
  340.       {
  341.          _listenChannel = new LocalConnection();
  342.          _listenChannel.client = _clip;
  343.          _clip.handshake = function(args:Object):void
  344.          {
  345.             MochiServices.comChannelName = args.newChannel;
  346.          };
  347.          _listenChannel.allowDomain("*","localhost");
  348.          _listenChannel.allowInsecureDomain("*","localhost");
  349.          _listenChannel.connect(_listenChannelName);
  350.          trace("Waiting for MochiAds services to connect...");
  351.       }
  352.       
  353.       private static function handleError(args:Object, callbackObject:Object, callbackMethod:Object) : void
  354.       {
  355.          if(args != null)
  356.          {
  357.             if(args.onError != null)
  358.             {
  359.                args.onError.apply(null,["NotConnected"]);
  360.             }
  361.             if(args.options != null && args.options.onError != null)
  362.             {
  363.                args.options.onError.apply(null,["NotConnected"]);
  364.             }
  365.          }
  366.          if(callbackMethod != null)
  367.          {
  368.             args = {};
  369.             args.error = true;
  370.             args.errorCode = "NotConnected";
  371.             if(callbackObject != null && callbackMethod is String)
  372.             {
  373.                try
  374.                {
  375.                   callbackObject[callbackMethod](args);
  376.                }
  377.                catch(error:Error)
  378.                {
  379.                }
  380.             }
  381.             else if(callbackMethod != null)
  382.             {
  383.                try
  384.                {
  385.                   callbackMethod.apply(args);
  386.                }
  387.                catch(error:Error)
  388.                {
  389.                }
  390.             }
  391.          }
  392.       }
  393.       
  394.       public static function get clip() : Object
  395.       {
  396.          return _container;
  397.       }
  398.       
  399.       public static function set comChannelName(val:String) : void
  400.       {
  401.          if(val != null)
  402.          {
  403.             if(val.length > 3)
  404.             {
  405.                _sendChannelName = val + "_fromgame";
  406.                _rcvChannelName = val;
  407.                initComChannels();
  408.             }
  409.          }
  410.       }
  411.       
  412.       private static function loadCommunicator(id:String, clip:Object) : MovieClip
  413.       {
  414.          var f:Function;
  415.          var req:URLRequest;
  416.          var clipname:String = "_mochiservices_com_" + id;
  417.          if(_clip != null)
  418.          {
  419.             return _clip;
  420.          }
  421.          if(!MochiServices.isNetworkAvailable())
  422.          {
  423.             return null;
  424.          }
  425.          MochiServices.allowDomains(_gatewayURL);
  426.          _clip = createEmptyMovieClip(clip,clipname,10336,false);
  427.          _loader = new Loader();
  428.          _timer = new Timer(1000,0);
  429.          _startTime = getTimer();
  430.          _timer.addEventListener(TimerEvent.TIMER,connectWait);
  431.          _timer.start();
  432.          f = function(ev:Object):void
  433.          {
  434.             _clip._mochiad_ctr_failed = true;
  435.             trace("MochiServices could not load.");
  436.             MochiServices.disconnect();
  437.             MochiServices.onError("IOError");
  438.          };
  439.          _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,f);
  440.          req = new URLRequest(_gatewayURL);
  441.          _loader.load(req);
  442.          _clip.addChild(_loader);
  443.          _clip._mochiservices_com = _loader;
  444.          _sendChannel = new LocalConnection();
  445.          _clip._queue = [];
  446.          _rcvChannel = new LocalConnection();
  447.          _rcvChannel.allowDomain("*","localhost");
  448.          _rcvChannel.allowInsecureDomain("*","localhost");
  449.          _rcvChannel.client = _clip;
  450.          _clip._nextcallbackID = 0;
  451.          _clip._callbacks = {};
  452.          listen();
  453.          return _clip;
  454.       }
  455.       
  456.       public static function bringToTop(e:Event) : void
  457.       {
  458.          if(MochiServices.clip != null)
  459.          {
  460.             if(MochiServices.childClip != null)
  461.             {
  462.                try
  463.                {
  464.                   if(MochiServices.clip.numChildren > 1)
  465.                   {
  466.                      MochiServices.clip.setChildIndex(MochiServices.childClip,MochiServices.clip.numChildren - 1);
  467.                   }
  468.                }
  469.                catch(errorObject:Error)
  470.                {
  471.                   trace("Warning: Depth sort error.");
  472.                   _container.removeEventListener(Event.ENTER_FRAME,MochiServices.bringToTop);
  473.                }
  474.             }
  475.          }
  476.       }
  477.       
  478.       public static function connect(id:String, clip:Object, onError:Object = null) : void
  479.       {
  480.          if(clip is DisplayObject)
  481.          {
  482.             if(!_connected && _clip == null)
  483.             {
  484.                trace("MochiServices Connecting...");
  485.                _connecting = true;
  486.                init(id,clip);
  487.             }
  488.          }
  489.          else
  490.          {
  491.             trace("Error, MochiServices requires a Sprite, Movieclip or instance of the stage.");
  492.          }
  493.          if(onError != null)
  494.          {
  495.             MochiServices.onError = onError;
  496.          }
  497.          else if(MochiServices.onError == null)
  498.          {
  499.             MochiServices.onError = function(errorCode:String):void
  500.             {
  501.                trace(errorCode);
  502.             };
  503.          }
  504.       }
  505.       
  506.       public static function createEmptyMovieClip(parent:Object, name:String, depth:Number, doAdd:Boolean = true) : MovieClip
  507.       {
  508.          var mc:MovieClip = new MovieClip();
  509.          if(doAdd)
  510.          {
  511.             if(false && Boolean(depth))
  512.             {
  513.                parent.addChildAt(mc,depth);
  514.             }
  515.             else
  516.             {
  517.                parent.addChild(mc);
  518.             }
  519.          }
  520.          try
  521.          {
  522.             parent[name] = mc;
  523.          }
  524.          catch(e:Error)
  525.          {
  526.             throw new Error("MochiServices requires a clip that is an instance of a dynamic class.  If your class extends Sprite or MovieClip, you must make it dynamic.");
  527.          }
  528.          mc["_name"] = name;
  529.          return mc;
  530.       }
  531.       
  532.       public static function connectWait(e:TimerEvent) : void
  533.       {
  534.          if(getTimer() - _startTime > 10000)
  535.          {
  536.             if(!_connected)
  537.             {
  538.                _clip._mochiad_ctr_failed = true;
  539.                trace("MochiServices could not load.");
  540.                MochiServices.disconnect();
  541.                MochiServices.onError("IOError");
  542.             }
  543.             _timer.stop();
  544.          }
  545.       }
  546.    }
  547. }
  548.