Example #1
0
        private void WebsocketClient_OnMessage(string obj)
        {
            var estimatedData = AVClient.DeserializeJsonString(obj);
            var cmd           = estimatedData["cmd"].ToString();

            if (!AVIMNotice.noticeFactories.Keys.Contains(cmd))
            {
                return;
            }
            var registerNoticeInterface = AVIMNotice.noticeFactories[cmd];
            var notice = registerNoticeInterface.Restore(estimatedData);

            if (noticeHandlers == null)
            {
                return;
            }
            if (!noticeHandlers.Keys.Contains(cmd))
            {
                return;
            }

            var handler = noticeHandlers[cmd];

            handler(notice);
        }
        public Task <AVInstallation> GetAsync(CancellationToken cancellationToken)
        {
            AVInstallation cachedCurrent;

            cachedCurrent = CurrentInstallation;

            if (cachedCurrent != null)
            {
                return(Task <AVInstallation> .FromResult(cachedCurrent));
            }

            return(taskQueue.Enqueue(toAwait => {
                return toAwait.ContinueWith(t => {
                    object temp;
                    AVClient.ApplicationSettings.TryGetValue("CurrentInstallation", out temp);
                    var installationDataString = temp as string;
                    AVInstallation installation = null;
                    if (installationDataString != null)
                    {
                        var installationData = AVClient.DeserializeJsonString(installationDataString);
                        installation = AVObject.CreateWithoutData <AVInstallation>(null);
                        installation.HandleFetchResult(AVObjectCoder.Instance.Decode(installationData, AVDecoder.Instance));
                    }
                    else
                    {
                        installation = AVObject.Create <AVInstallation>();
                        installation.SetIfDifferent("installationId", installationIdController.Get().ToString());
                    }

                    CurrentInstallation = installation;
                    return installation;
                });
            }, cancellationToken));
        }
Example #3
0
        public Task <AVConfig> GetCurrentConfigAsync()
        {
            return(taskQueue.Enqueue(toAwait => toAwait.ContinueWith(_ => {
                if (currentConfig == null)
                {
                    return storageController.LoadAsync().OnSuccess(t => {
                        object tmp;
                        t.Result.TryGetValue(CurrentConfigKey, out tmp);

                        string propertiesString = tmp as string;
                        if (propertiesString != null)
                        {
                            var dictionary = AVClient.DeserializeJsonString(propertiesString);
                            currentConfig = new AVConfig(dictionary);
                        }
                        else
                        {
                            currentConfig = new AVConfig();
                        }

                        return currentConfig;
                    });
                }

                return Task.FromResult(currentConfig);
            }), CancellationToken.None).Unwrap());
        }
Example #4
0
 public AVIMMessageNotice(IDictionary <string, object> estimatedData)
     : base(estimatedData)
 {
     this.cid        = estimatedData["cid"].ToString();
     this.fromPeerId = estimatedData["fromPeerId"].ToString();
     this.id         = estimatedData["id"].ToString();
     this.appId      = estimatedData["appId"].ToString();
     this.peerId     = estimatedData["peerId"].ToString();
     this.msg        = AVClient.DeserializeJsonString(estimatedData["msg"].ToString());
 }
        public Task <Tuple <int, IDictionary <string, object> > > RunCommandAsync(AVIMCommand command, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!webSocketClient.IsOpen)
            {
                throw new AVIMException(AVIMException.ErrorCode.CAN_NOT_EXCUTE_COMMAND, "当前连接失效,无法发送指令");
            }
            command = command.IDlize();
            var tcs           = new TaskCompletionSource <Tuple <int, IDictionary <string, object> > >();
            var requestString = command.EncodeJsonString();

            webSocketClient.Send(requestString);
            var requestJson = command.Encode();

            Action <string> onMessage = null;

            onMessage = (response) =>
            {
                var responseJson = AVClient.DeserializeJsonString(response);
                if (responseJson.Keys.Contains("i"))
                {
                    if (requestJson["i"].ToString() == responseJson["i"].ToString())
                    {
                        var result = new Tuple <int, IDictionary <string, object> >(-1, responseJson);
                        if (responseJson.Keys.Contains("code"))
                        {
                            var errorCode = int.Parse(responseJson["code"].ToString());
                            var reason    = string.Empty;
                            int appCode   = 0;
                            //result = new Tuple<int, IDictionary<string, object>>(errorCode, responseJson);
                            if (responseJson.Keys.Contains("reason"))
                            {
                                reason = responseJson["reason"].ToString();
                            }
                            if (responseJson.Keys.Contains("appCode"))
                            {
                                appCode = int.Parse(responseJson["appCode"].ToString());
                            }
                            tcs.SetException(new AVIMException(errorCode, appCode, reason, null));
                        }
                        tcs.SetResult(result);
                        webSocketClient.OnMessage -= onMessage;
                    }
                }
            };
            webSocketClient.OnMessage += onMessage;
            return(tcs.Task);
        }
        public bool HandleNavigation(Uri uri)
        {
            IDictionary <string, string> result;

            if (TryAVOAuthCallbackUrl(uri, out result))
            {
                Action getUserId = () => {
                    try {
                        if (result.ContainsKey("error"))
                        {
                            pendingTask.TrySetException(new AVException(AVException.ErrorCode.OtherCause,
                                                                        string.Format("{0}: {1}", result["error_description"], result["error"])));
                            return;
                        }
                        var parameters = new Dictionary <string, object>();
                        parameters["access_token"] = result["access_token"];
                        parameters["fields"]       = "id";

                        var request = new HttpRequest {
                            Uri = new Uri(MeUrl, "?" + AVClient.BuildQueryString(parameters))
                        };

                        AVClient.PlatformHooks.HttpClient.ExecuteAsync(request, null, null, CancellationToken.None).OnSuccess(t => {
                            var meResult = AVClient.DeserializeJsonString(t.Result.Item2);
                            pendingTask.TrySetResult(GetAuthData(
                                                         meResult["id"] as string,
                                                         result["access_token"] as string,
                                                         (DateTime.Now + TimeSpan.FromSeconds(int.Parse(result["expires_in"])))));
                        }).ContinueWith(t => {
                            if (t.IsFaulted)
                            {
                                pendingTask.TrySetException(t.Exception);
                            }
                        });
                    } catch (Exception e) {
                        pendingTask.TrySetException(e);
                    }
                };
                getUserId();
                return(true);
            }
            return(false);
        }
Example #7
0
        Task <RouterState> fromCloud(CancellationToken cancellationToken)
        {
            string url = string.Format(routerUrl, AVClient.ApplicationId);

            return(AVClient.RequestAsync(uri: new Uri(url),
                                         method: "GET",
                                         headers: null,
                                         data: null,
                                         contentType: "",
                                         cancellationToken: CancellationToken.None).ContinueWith <RouterState>(t =>
            {
                var httpStatus = (int)t.Result.Item1;
                if (httpStatus != 200)
                {
                    throw new AVException(AVException.ErrorCode.ConnectionFailed, "can not reach router.", null);
                }
                try
                {
                    var result = t.Result.Item2;

                    var routerState = AVClient.DeserializeJsonString(result);
                    var expire = DateTime.Now.AddSeconds(long.Parse(routerState["ttl"].ToString()));
                    routerState["expire"] = expire.UnixTimeStampSeconds();

                    AVClient.ApplicationSettings["RouterState"] = Json.Encode(routerState);

                    var routerStateObj = new RouterState()
                    {
                        groupId = routerState["groupId"] as string,
                        server = routerState["server"] as string,
                        secondary = routerState["secondary"] as string,
                        ttl = long.Parse(routerState["ttl"].ToString()),
                    };

                    return routerStateObj;
                }
                catch (Exception exception)
                {
                    return null;
                }
            }));
        }
Example #8
0
        public Task <AVConfig> GetCurrentConfigAsync()
        {
            return(taskQueue.Enqueue(toAwait => toAwait.ContinueWith(_ => {
                if (currentConfig == null)
                {
                    object tmp;
                    AVClient.ApplicationSettings.TryGetValue(CurrentConfigKey, out tmp);

                    string propertiesString = tmp as string;
                    if (propertiesString != null)
                    {
                        var dictionary = AVClient.DeserializeJsonString(propertiesString);
                        currentConfig = new AVConfig(dictionary);
                    }
                    else
                    {
                        currentConfig = new AVConfig();
                    }
                }

                return currentConfig;
            }), CancellationToken.None));
        }