Example #1
0
        public Task SendPushNotificationAsync(IPushState state, String sessionToken, CancellationToken cancellationToken)
        {
            var command = new AVCommand("/push",
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: AVPushEncoder.Instance.Encode(state));

            return(AVClient.AVCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
        public Task RevokeAsync(string sessionToken, CancellationToken cancellationToken)
        {
            var command = new AVCommand("/logout",
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: new Dictionary <string, object>());

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
Example #3
0
        public Task RequestPasswordResetAsync(string email, CancellationToken cancellationToken)
        {
            var command = new AVCommand("/requestPasswordReset",
                                        method: "POST",
                                        data: new Dictionary <string, object> {
                { "email", email }
            });

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
        public Task <IObjectState> GetSessionAsync(string sessionToken, CancellationToken cancellationToken)
        {
            var command = new AVCommand("/sessions/me",
                                        method: "GET",
                                        sessionToken: sessionToken,
                                        data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
            }));
        }
        public Task <IObjectState> UpgradeToRevocableSessionAsync(string sessionToken, CancellationToken cancellationToken)
        {
            var command = new AVCommand("/upgradeToRevocableSession",
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: new Dictionary <string, object>());

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
            }));
        }
        public Task DeleteAsync(IObjectState state,
                                string sessionToken,
                                CancellationToken cancellationToken)
        {
            var command = new AVCommand(string.Format("/classes/{0}/{1}",
                                                      state.ClassName, state.ObjectId),
                                        method: "DELETE",
                                        sessionToken: sessionToken,
                                        data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
        public Task <FileState> SaveAsync(FileState state,
                                          Stream dataStream,
                                          String sessionToken,
                                          IProgress <AVUploadProgressEventArgs> progress,
                                          CancellationToken cancellationToken = default(CancellationToken))
        {
            if (state.Url != null)
            {
                // !isDirty
                return(Task <FileState> .FromResult(state));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                var tcs = new TaskCompletionSource <FileState>();
                tcs.TrySetCanceled();
                return(tcs.Task);
            }

            var oldPosition = dataStream.Position;
            var command     = new AVCommand("/files/" + state.Name,
                                            method: "POST",
                                            sessionToken: sessionToken,
                                            contentType: state.MimeType,
                                            stream: dataStream);

            return(commandRunner.RunCommandAsync(command,
                                                 uploadProgress: progress,
                                                 cancellationToken: cancellationToken).OnSuccess(uploadTask =>
            {
                var result = uploadTask.Result;
                var jsonData = result.Item2;
                cancellationToken.ThrowIfCancellationRequested();

                return new FileState
                {
                    Name = jsonData["name"] as string,
                    Url = new Uri(jsonData["url"] as string, UriKind.Absolute),
                    MimeType = state.MimeType
                };
            }).ContinueWith(t =>
            {
                // Rewind the stream on failure or cancellation (if possible)
                if ((t.IsFaulted || t.IsCanceled) && dataStream.CanSeek)
                {
                    dataStream.Seek(oldPosition, SeekOrigin.Begin);
                }
                return t;
            }).Unwrap());
        }
Example #8
0
        public Task <IObjectState> GetUserAsync(string sessionToken, CancellationToken cancellationToken)
        {
            IDictionary <string, object> data = new Dictionary <string, object>()
            {
                { "session_token", sessionToken }
            };
            var command = new AVCommand("/login",
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: data);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
            }));
        }
        public Task <IObjectState> FetchAsync(IObjectState state,
                                              string sessionToken,
                                              CancellationToken cancellationToken)
        {
            var command = new AVCommand(string.Format("/classes/{0}/{1}",
                                                      Uri.EscapeDataString(state.ClassName),
                                                      Uri.EscapeDataString(state.ObjectId)),
                                        method: "GET",
                                        sessionToken: sessionToken,
                                        data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
            }));
        }
Example #10
0
        public Task <IObjectState> LogInWithParametersAsync(string relativeUrl, IDictionary <string, object> data,
                                                            CancellationToken cancellationToken)
        {
            var command = new AVCommand(string.Format("/{0}", relativeUrl),
                                        method: "POST",
                                        data: data);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
        public Task <AVConfig> FetchConfigAsync(String sessionToken, CancellationToken cancellationToken)
        {
            var command = new AVCommand("/config",
                                        method: "GET",
                                        sessionToken: sessionToken,
                                        data: null);

            return(AVClient.AVCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(task => {
                cancellationToken.ThrowIfCancellationRequested();
                return new AVConfig(task.Result.Item2);
            }).OnSuccess(task => {
                cancellationToken.ThrowIfCancellationRequested();
                CurrentConfigController.SetCurrentConfigAsync(task.Result);
                return task;
            }).Unwrap());
        }
        private Task <IDictionary <string, object> > FindAsync(string className,
                                                               IDictionary <string, object> parameters,
                                                               string sessionToken,
                                                               CancellationToken cancellationToken)
        {
            var command = new AVCommand(string.Format("/classes/{0}?{1}",
                                                      Uri.EscapeDataString(className),
                                                      AVClient.BuildQueryString(parameters)),
                                        method: "GET",
                                        sessionToken: sessionToken,
                                        data: null);

            return(AVClient.AVCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return t.Result.Item2;
            }));
        }
Example #13
0
        public Task <IObjectState> SignUpAsync(IObjectState state,
                                               IDictionary <string, IAVFieldOperation> operations,
                                               CancellationToken cancellationToken)
        {
            var objectJSON = AVObject.ToJSONObjectForSaving(operations);

            var command = new AVCommand("/classes/_User",
                                        method: "POST",
                                        data: objectJSON);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = true;
                });
                return serverState;
            }));
        }
        public Task <T> CallFunctionAsync <T>(String name,
                                              IDictionary <string, object> parameters,
                                              string sessionToken,
                                              CancellationToken cancellationToken)
        {
            var command = new AVCommand(string.Format("/functions/{0}", Uri.EscapeUriString(name)),
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: NoObjectsEncoder.Instance.Encode(parameters) as IDictionary <string, object>);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var decoded = AVDecoder.Instance.Decode(t.Result.Item2) as IDictionary <string, object>;
                if (!decoded.ContainsKey("result"))
                {
                    return default(T);
                }
                return (T)AVClient.ConvertTo <T>(decoded["result"]);
            }));
        }
        public Task TrackAppOpenedAsync(string pushHash,
                                        string sessionToken,
                                        CancellationToken cancellationToken)
        {
            IDictionary <string, object> data = new Dictionary <string, object> {
                { "at", DateTime.Now }
            };

            if (pushHash != null)
            {
                data["push_hash"] = pushHash;
            }

            var command = new AVCommand("/events/AppOpened",
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: PointerOrLocalIdEncoder.Instance.Encode(data) as IDictionary <string, object>);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
Example #16
0
        public Task <IObjectState> LogInAsync(string username,
                                              string password,
                                              CancellationToken cancellationToken)
        {
            var data = new Dictionary <string, object> {
                { "username", username },
                { "password", password }
            };

            var command = new AVCommand(string.Format("/login?{0}", AVClient.BuildQueryString(data)),
                                        method: "GET",
                                        data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
        public Task TrackEventAsync(string name,
                                    IDictionary <string, string> dimensions,
                                    string sessionToken,
                                    CancellationToken cancellationToken)
        {
            IDictionary <string, object> data = new Dictionary <string, object> {
                { "at", DateTime.Now },
                { "name", name },
            };

            if (dimensions != null)
            {
                data["dimensions"] = dimensions;
            }

            var command = new AVCommand("/events/" + name,
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: PointerOrLocalIdEncoder.Instance.Encode(data) as IDictionary <string, object>);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
        public Task <IObjectState> SaveAsync(IObjectState state,
                                             IDictionary <string, IAVFieldOperation> operations,
                                             string sessionToken,
                                             CancellationToken cancellationToken)
        {
            var objectJSON = AVObject.ToJSONObjectForSaving(operations);

            var command = new AVCommand((state.ObjectId == null ?
                                         string.Format("/classes/{0}", Uri.EscapeDataString(state.ClassName)) :
                                         string.Format("/classes/{0}/{1}", Uri.EscapeDataString(state.ClassName), state.ObjectId)),
                                        method: (state.ObjectId == null ? "POST" : "PUT"),
                                        sessionToken: sessionToken,
                                        data: objectJSON);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
Example #19
0
        public Task <IObjectState> LogInAsync(string authType,
                                              IDictionary <string, object> data,
                                              CancellationToken cancellationToken)
        {
            var authData = new Dictionary <string, object>();

            authData[authType] = data;

            var command = new AVCommand("/users",
                                        method: "POST",
                                        data: new Dictionary <string, object> {
                { "authData", authData }
            });

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
Example #20
0
        public Task <Tuple <HttpStatusCode, IDictionary <string, object> > > RunCommandAsync(AVCommand command,
                                                                                             IProgress <AVUploadProgressEventArgs> uploadProgress     = null,
                                                                                             IProgress <AVDownloadProgressEventArgs> downloadProgress = null,
                                                                                             CancellationToken cancellationToken = default(CancellationToken))
        {
            return(httpClient.ExecuteAsync(command, uploadProgress, downloadProgress, cancellationToken).OnSuccess(t => {
                cancellationToken.ThrowIfCancellationRequested();

                var response = t.Result;
                var contentString = response.Item2;
                int responseCode = (int)response.Item1;

                if (AVClient.httpDebugLog)
                {
                    AVClient.LogTracker("Response Code: " + responseCode);
                    AVClient.LogTracker("Response Body: " + contentString);
                }
                if (responseCode >= 500)
                {
                    // Server error, return InternalServerError.
                    throw new AVException(AVException.ErrorCode.InternalServerError, response.Item2);
                }
                else if (contentString != null)
                {
                    IDictionary <string, object> contentJson = null;
                    try {
                        if (contentString.StartsWith("["))
                        {
                            var arrayJson = Json.Parse(contentString);
                            contentJson = new Dictionary <string, object> {
                                { "results", arrayJson }
                            };
                        }
                        else
                        {
                            contentJson = Json.Parse(contentString) as IDictionary <string, object>;
                        }
                    } catch (Exception e) {
                        throw new AVException(AVException.ErrorCode.OtherCause,
                                              "Invalid response from server", e);
                    }
                    if (responseCode < 200 || responseCode > 299)
                    {
                        int code = (int)(contentJson.ContainsKey("code") ? (long)contentJson["code"] : (int)AVException.ErrorCode.OtherCause);
                        string error = contentJson.ContainsKey("error") ?
                                       contentJson["error"] as string :
                                       contentString;
                        throw new AVException((AVException.ErrorCode)code, error);
                    }
                    return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1,
                                                                                     contentJson);
                }
                return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1, null);
            }));
        }
        private IList <Task <IDictionary <string, object> > > ExecuteBatchRequest(IList <object> requests,
                                                                                  string sessionToken,
                                                                                  CancellationToken cancellationToken)
        {
            var tasks     = new List <Task <IDictionary <string, object> > >();
            int batchSize = requests.Count;
            var tcss      = new List <TaskCompletionSource <IDictionary <string, object> > >();

            for (int i = 0; i < batchSize; ++i)
            {
                var tcs = new TaskCompletionSource <IDictionary <string, object> >();
                tcss.Add(tcs);
                tasks.Add(tcs.Task);
            }

            var command = new AVCommand("/batch",
                                        method: "POST",
                                        sessionToken: sessionToken,
                                        data: new Dictionary <string, object> {
                { "requests", requests }
            });

            commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).ContinueWith(t => {
                if (t.IsFaulted || t.IsCanceled)
                {
                    foreach (var tcs in tcss)
                    {
                        if (t.IsFaulted)
                        {
                            tcs.TrySetException(t.Exception);
                        }
                        else if (t.IsCanceled)
                        {
                            tcs.TrySetCanceled();
                        }
                    }
                    return;
                }

                var resultsArray = AVClient.As <IList <object> >(t.Result.Item2["results"]);
                int resultLength = resultsArray.Count;
                if (resultLength != batchSize)
                {
                    foreach (var tcs in tcss)
                    {
                        tcs.TrySetException(new InvalidOperationException(
                                                "Batch command result count expected: " + batchSize + " but was: " + resultLength + "."));
                    }
                    return;
                }

                for (int i = 0; i < batchSize; ++i)
                {
                    var result = resultsArray[i] as Dictionary <string, object>;
                    var tcs    = tcss[i];

                    if (result.ContainsKey("success"))
                    {
                        tcs.TrySetResult(result["success"] as IDictionary <string, object>);
                    }
                    else if (result.ContainsKey("error"))
                    {
                        var error      = result["error"] as IDictionary <string, object>;
                        long errorCode = (long)error["code"];
                        tcs.TrySetException(new AVException((AVException.ErrorCode)errorCode, error["error"] as string));
                    }
                    else
                    {
                        tcs.TrySetException(new InvalidOperationException(
                                                "Invalid batch command response."));
                    }
                }
            });

            return(tasks);
        }