Beispiel #1
0
        //----------------------------------------------------------------------------------------------------
        // parse message and queue for dispatch on the game thread

        void OnMessage(WebSocket ws, byte[] data, bool isText)
        {
            try
            {
                if (isText == false)
                {
                    throw new Exception("Unable to process binary messages");
                }

                var json    = Encoding.UTF8.GetString(data);
                var message = json.FromJson <Message>();

                if (message == null || message.q == null)
                {
                    throw new Exception("Failed to parse message");
                }

                UniumComponent.Log(string.Format("[sock:{0}] {1}", mSocket.ID, json));

                lock ( mMessageQueue )
                {
                    mMessageQueue.Add(message);
                }
            }
            catch (Exception e)
            {
                mSocketMessage.Error(ResponseCode.BadRequest);
                UniumComponent.Warn(string.Format("[sock:{0}] {1}", mSocket.ID, e.Message));
            }
        }
    //----------------------------------------------------------------------------------------------------

    void Awake()
    {
        // there can be only one!

        if (Singleton != null && Singleton != this)
        {
            Destroy(this.gameObject);
            return;
        }

        // and always one

        DontDestroyOnLoad(transform.gameObject);
        Singleton = this;

        // keep game running when editor does not have focus - needed as we need to dispatch on the game thread (which would be paused otherwise)

        if (RunInBackground)
        {
            Application.runInBackground = true;
        }

        var root = Path.Combine(Application.streamingAssetsPath, StaticFiles != null ? StaticFiles : "");

        HandlerFile.Mount("persistent", Application.persistentDataPath);
        HandlerFile.Mount("streaming", Application.streamingAssetsPath);
        HandlerFile.Mount("root", root);


        Application.logMessageReceivedThreaded += HandlerUtils.LogMessage;
        Events.Singleton.BindEvents();
    }
    //----------------------------------------------------------------------------------------------------

    void OnDisable()
    {
        if (Singleton == this)
        {
            Application.logMessageReceivedThreaded -= HandlerUtils.LogMessage;
            Events.Singleton.UnbindEvents();

            StopServer();
            Singleton = null;
        }
    }
Beispiel #4
0
 public void Dispatch(RequestAdapter request)
 {
     try
     {
         Handler(request, RelativePath(request));
     }
     catch (Exception e)
     {
         request.Reject(ResponseCode.BadRequest);
         UniumComponent.Error(e.Message);
     }
 }
        public static void HandleBind(RequestAdapter req, string path)
        {
            if (sMatchQuery.IsMatch(path) == false)
            {
                req.Reject(ResponseCode.BadRequest);
                return;
            }

            // select events

            var query = new Query(path + "=event", Unium.Root).Select();


            // bind

            var bound   = 0;
            var target  = query.SearchPath.Target;
            var adapter = req as RequestAdapterSocket;

            foreach (var obj in query.Selected)
            {
                try
                {
                    var eventInfo = obj.GetType().GetEvent(target);

                    if (eventInfo != null)
                    {
                        adapter.Socket.Bind(adapter.Message, obj, eventInfo);
                        bound++;
                    }
                }
                catch (Exception e)
                {
                    UniumComponent.Warn(string.Format("Failed to get bind to event '{0}' - {1}", target, e.Message));
                }
            }


            // not found if none bound

            if (bound == 0)
            {
                req.Reject(ResponseCode.NotFound);
                return;
            }
        }
Beispiel #6
0
        static IEnumerator TakeScreenshot(RequestAdapter req, string path)
        {
            // save screenshot

            var filename = Path.Combine(HandlerFile.GetPath("persistent"), "screenshot.png");

            #if UNITY_5
            Application.CaptureScreenshot(filename);
            #else
            ScreenCapture.CaptureScreenshot(filename);
            #endif

            UniumComponent.Log("Screenshot '" + filename + "'");

            // screenshots don't happen immediately, so defer a redirect for a small amount of time

            yield return(new WaitForSeconds(1.0f));

            req.Redirect("/file/persistent/screenshot.png?cb=" + Util.RandomString());
        }
Beispiel #7
0
        List <object> ActionInvoke()
        {
            var actionName = SearchPath.Target;

            if (string.IsNullOrEmpty(actionName))
            {
                UniumComponent.Warn("No function name given for Invoke() call");
                return(null);
            }

            var strArgs = SearchPath.Arguments;

            object[] cachedValues = new object[strArgs.Length];
            Type[]   cachedTypes  = new Type[strArgs.Length];
            object[] args         = new object[strArgs.Length];


            var results = new List <object>();


            foreach (var current in Selected)
            {
                try
                {
                    // find something to invoke - either a method, event or field/property with an Invoke function (e.g. UnityEvent or Button)

                    var target     = current;
                    var targetType = target.GetType();
                    var method     = null as MethodInfo;
                    var multicast  = null as MulticastDelegate;

                    var member     = targetType.GetMember(actionName);
                    var memberType = member.Length > 0 ? member[0].MemberType : 0;

                    if ((memberType & MemberTypes.Method) == MemberTypes.Method)
                    {
                        method = targetType.GetMethods().Where(m => m.Name == actionName && m.GetParameters().Length == args.Length).FirstOrDefault();
                    }
                    else if ((memberType & MemberTypes.Event) == MemberTypes.Event)
                    {
                        var field = targetType.GetField(actionName, BindingFlags.Instance | BindingFlags.NonPublic);
                        multicast = field == null ? null : field.GetValue(target) as MulticastDelegate;

                        if (multicast != null)
                        {
                            var delegateList = multicast.GetInvocationList();
                            method = delegateList.Length > 0 ? delegateList[0].Method : null;
                        }
                    }
                    else if ((memberType & MemberTypes.Field) == MemberTypes.Field)
                    {
                        var field = targetType.GetField(actionName);
                        target = field == null  ? null : field.GetValue(target);
                        method = target == null ? null : target.GetType().GetMethod("Invoke");
                    }
                    else if ((memberType & MemberTypes.Property) == MemberTypes.Property)
                    {
                        var prop = targetType.GetProperty(actionName);
                        target = prop == null   ? null : prop.GetValue(target, null);
                        method = target == null ? null : target.GetType().GetMethod("Invoke");
                    }

                    // if we didn't find anything invokable then skip this object

                    if (method == null)
                    {
                        continue;
                    }

                    // otherwise, convert arguments passed in to the appropriate types

                    if (strArgs != null)
                    {
                        var argInfo = method.GetParameters();

                        if (argInfo.Length != strArgs.Length)
                        {
                            //Unium.Instance.Log.Warn( "Can't invoke function {0} - parameters do not match", func );
                            continue;
                        }

                        for (int i = 0; i < args.Length; i++)
                        {
                            // convert string to value

                            var argType = argInfo[i].ParameterType;

                            if (argType != cachedTypes[i])
                            {
                                cachedTypes[i]  = argType;
                                cachedValues[i] = ConvertType.FromString(strArgs[i], argType);
                            }

                            args[i] = cachedValues[i];
                        }
                    }

                    // invoke method

                    object result = null;

                    if (multicast != null)
                    {
                        result = multicast.DynamicInvoke(args);
                    }
                    else
                    {
                        result = method.Invoke(target, args);
                    }

                    results.Add(result);
                }
                catch (Exception e)
                {
                    if (UniumComponent.IsDebug)
                    {
                        UniumComponent.Warn(string.Format("Failed to invoke '{0}' - {1}", actionName, e.Message));
                    }
                }
            }

            return(results);
        }
Beispiel #8
0
        List <object> ActionSet()
        {
            var fieldName     = SearchPath.Target;
            var valueAsString = SearchPath.Arguments != null && SearchPath.Arguments.Length > 0 ? SearchPath.Arguments[0] : null;

            if (string.IsNullOrEmpty(fieldName))
            {
                UniumComponent.Warn("No field name given for Set() call");
                return(null);
            }

            if (valueAsString == null)
            {
                UniumComponent.Warn("No field value given for Set() call");
            }

            var results = new List <object>();

            object cachedValue = null;
            Type   cachedType  = null;
            bool   cacheValid  = false;

            foreach (var obj in Selected)
            {
                try
                {
                    // set value

                    var objType = obj.GetType();

                    // set field

                    var fieldInfo = objType.GetField(fieldName);

                    if (fieldInfo != null)
                    {
                        // convert to type

                        if (fieldInfo.FieldType != cachedType)
                        {
                            cachedType  = fieldInfo.FieldType;
                            cachedValue = ConvertType.FromString(valueAsString, cachedType);
                            cacheValid  = true;
                        }

                        if (cacheValid)
                        {
                            fieldInfo.SetValue(obj, cachedValue);
                            results.Add(fieldInfo.GetValue(obj));
                        }

                        continue;
                    }

                    // set property

                    var propInfo = objType.GetProperty(fieldName);

                    if (propInfo != null && propInfo.CanWrite)
                    {
                        // convert to type

                        if (propInfo.PropertyType != cachedType)
                        {
                            cachedType  = propInfo.PropertyType;
                            cachedValue = ConvertType.FromString(valueAsString, cachedType);
                            cacheValid  = true;
                        }

                        if (cacheValid)
                        {
                            propInfo.SetValue(obj, cachedValue, null);
                            results.Add(propInfo.GetValue(obj, null));
                        }
                    }
                }
                catch (Exception e)
                {
                    cacheValid = false;

                    if (UniumComponent.IsDebug)
                    {
                        UniumComponent.Warn(string.Format("Failed to set value for field '{0}' - {1}", fieldName, e.Message));
                    }
                }
            }

            return(results);
        }
        List <object> ActionInvoke()
        {
            var functionName = SearchPath.Target;

            if (string.IsNullOrEmpty(functionName))
            {
                UniumComponent.Warn("No function name given for Invoke() call");
                return(null);
            }

            var strArgs = SearchPath.Arguments;

            object[] cachedValues = new object[strArgs.Length];
            Type[]   cachedTypes  = new Type[strArgs.Length];
            object[] args         = new object[strArgs.Length];


            var results = new List <object>();


            foreach (var obj in Selected)
            {
                try
                {
                    // get function pointer

                    var type   = obj.GetType();
                    var method = type.GetMethod(functionName);

                    if (method == null)
                    {
                        continue;
                    }

                    // convert arguments

                    if (strArgs != null)
                    {
                        var argInfo = method.GetParameters();

                        if (argInfo.Length != strArgs.Length)
                        {
                            //Unium.Instance.Log.Warn( "Can't invoke function {0} - parameters do not match", func );
                            continue;
                        }

                        for (int i = 0; i < args.Length; i++)
                        {
                            // convert string to value

                            var argType = argInfo[i].ParameterType;

                            if (argType != cachedTypes[i])
                            {
                                cachedTypes[i]  = argType;
                                cachedValues[i] = ConvertType.FromString(strArgs[i], argType);
                            }

                            args[i] = cachedValues[i];
                        }
                    }

                    // invoke method

                    var result = method.Invoke(obj, args);
                    results.Add(result);
                }
                catch (Exception e)
                {
                    if (UniumComponent.IsDebug)
                    {
                        UniumComponent.Warn(string.Format("Failed to invoke '{0}' - {1}", functionName, e.Message));
                    }
                }
            }

            return(results);
        }