public AVCommand(AVCommand other) { this.Uri = other.Uri; this.Method = other.Method; this.DataObject = other.DataObject; this.Headers = new List <KeyValuePair <string, string> >(other.Headers); this.Data = other.Data; }
public AVCommand(AVCommand other) { this.Uri = other.Uri; this.Method = other.Method; this.DataObject = other.DataObject; this.Headers = new List<KeyValuePair<string, string>>(other.Headers); this.Data = other.Data; }
public Task DeleteAsync(FileState state, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand("files/" + state.ObjectId, method: "DELETE", sessionToken: sessionToken, data: null); return(commandRunner.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); }
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)); }
public Task DeleteAsync(FileState state, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand("files/" + state.ObjectId, method: "DELETE", sessionToken: sessionToken, data: null); return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); }
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)); }
private Task <AVCommand> PrepareCommand(AVCommand command) { AVCommand newCommand = new AVCommand(command); Task <AVCommand> installationIdTask = installationIdController.GetAsync().ContinueWith(t => { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-Installation-Id", t.Result.ToString())); return(newCommand); }); // TODO (richardross): Inject configuration instead of using shared static here. AVClient.Configuration configuration = AVClient.CurrentConfiguration; newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-Id", configuration.ApplicationId)); newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-Client-Version", AVClient.VersionString)); if (configuration.AdditionalHTTPHeaders != null) { foreach (var header in configuration.AdditionalHTTPHeaders) { newCommand.Headers.Add(header); } } if (!string.IsNullOrEmpty(configuration.VersionInfo.BuildVersion)) { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-App-Build-Version", configuration.VersionInfo.BuildVersion)); } if (!string.IsNullOrEmpty(configuration.VersionInfo.DisplayVersion)) { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-App-Display-Version", configuration.VersionInfo.DisplayVersion)); } if (!string.IsNullOrEmpty(configuration.VersionInfo.OSVersion)) { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-OS-Version", configuration.VersionInfo.OSVersion)); } // TODO (richardross): I hate the idea of having this super tightly coupled static variable in here. // Lets eventually get rid of it. if (!string.IsNullOrEmpty(AVClient.MasterKey)) { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-Key", AVClient.MasterKey + ",master")); } else { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LC-Key", configuration.ApplicationKey)); } // TODO (richardross): Inject this instead of using static here. if (AVUser.IsRevocableSessionEnabled) { newCommand.Headers.Add(new KeyValuePair <string, string>("X-LeanCloud-Revocable-Session", revocableSessionTokenTrueValue)); } return(installationIdTask); }
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); }); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="uploadProgress"></param> /// <param name="downloadProgress"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task<Tuple<HttpStatusCode, IDictionary<string, object>>> RunCommandAsync(AVCommand command, IProgress<AVUploadProgressEventArgs> uploadProgress = null, IProgress<AVDownloadProgressEventArgs> downloadProgress = null, CancellationToken cancellationToken = default(CancellationToken)) { return PrepareCommand(command).ContinueWith(commandTask => { return httpClient.ExecuteAsync(commandTask.Result, uploadProgress, downloadProgress, cancellationToken).OnSuccess(t => { cancellationToken.ThrowIfCancellationRequested(); var response = t.Result; var contentString = response.Item2; int responseCode = (int)response.Item1; 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); }); }).Unwrap(); }
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> 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 SendPushNotificationAsync(IAVState state, CancellationToken cancellationToken) { return currentUserController.GetCurrentSessionTokenAsync(cancellationToken).OnSuccess(sessionTokenTask => { var command = new AVCommand("push", method: "POST", sessionToken: sessionTokenTask.Result, data: AVPushEncoder.Instance.Encode(state)); return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); }).Unwrap(); }
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 UpdatePasswordAsync(string userId, string sessionToken, string oldPassword, string newPassword, CancellationToken cancellationToken) { var command = new AVCommand(String.Format("users/{0}/updatePassword", userId), method: "PUT", sessionToken: sessionToken, data: new Dictionary <string, object> { { "old_password", oldPassword }, { "new_password", newPassword }, }); return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken)); }
public void TestMakeCommand() { AVCommand command = new AVCommand("endpoint", method: "GET", sessionToken: "abcd", headers: null, data: null); Assert.AreEqual("/1/endpoint", command.Uri.AbsolutePath); Assert.AreEqual("GET", command.Method); Assert.IsTrue(command.Headers.Any(pair => pair.Key == "X-LeanCloud-Session-Token" && pair.Value == "abcd")); }
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 <IObjectState> RefreshSessionTokenAsync(string userId, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand(String.Format("users/{0}/refreshSessionToken", userId), method: "PUT", sessionToken: sessionToken, data: null); return(AVPlugins.Instance.CommandRunner.RunCommandAsync(command).OnSuccess(t => { var serverState = AVObjectCoder.Instance.Decode(t.Result.Item2, AVDecoder.Instance); return serverState; })); }
public virtual 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()); }
public Task<AVConfig> FetchConfigAsync(String sessionToken, CancellationToken cancellationToken) { var command = new AVCommand("config", method: "GET", sessionToken: sessionToken, data: null); return commandRunner.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(); }
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); })); }
public Task <AVConfig> FetchConfigAsync(String sessionToken, CancellationToken cancellationToken) { var command = new AVCommand("config", method: "GET", sessionToken: sessionToken, data: null); return(commandRunner.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 relativeUri, IDictionary <string, object> parameters, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand(string.Format("{0}?{1}", relativeUri, AVClient.BuildQueryString(parameters)), method: "GET", sessionToken: sessionToken, data: null); return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => { return t.Result.Item2; })); }
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 <T> RPCFunction <T>(string name, IDictionary <string, object> parameters, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand(string.Format("call/{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 Conversion.To <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); }
public Task<FileState> GetAsync(string objectId, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand("files/" + objectId, method: "GET", sessionToken: sessionToken, data: null); return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(_ => { var result = _.Result; var jsonData = result.Item2; cancellationToken.ThrowIfCancellationRequested(); return new FileState { ObjectId = jsonData["objectId"] as string, Name = jsonData["name"] as string, Url = new Uri(jsonData["url"] as string, UriKind.Absolute), }; }); }
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 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 <FileState> GetAsync(string objectId, string sessionToken, CancellationToken cancellationToken) { var command = new AVCommand("files/" + objectId, method: "GET", sessionToken: sessionToken, data: null); return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(_ => { var result = _.Result; var jsonData = result.Item2; cancellationToken.ThrowIfCancellationRequested(); return new FileState { ObjectId = jsonData["objectId"] as string, Name = jsonData["name"] as string, Url = new Uri(jsonData["url"] as string, UriKind.Absolute), }; })); }
public Task TestRunCommand() { var mockHttpClient = new Mock<IHttpClient>(); var mockInstallationIdController = new Mock<IInstallationIdController>(); var fakeResponse = Task<Tuple<HttpStatusCode, string>>.FromResult(new Tuple<HttpStatusCode, string>(HttpStatusCode.OK, "{}")); mockHttpClient.Setup(obj => obj.ExecuteAsync(It.IsAny<HttpRequest>(), It.IsAny<IProgress<AVUploadProgressEventArgs>>(), It.IsAny<IProgress<AVDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>())).Returns(fakeResponse); mockInstallationIdController.Setup(i => i.GetAsync()).Returns(Task.FromResult<Guid?>(null)); AVCommandRunner commandRunner = new AVCommandRunner(mockHttpClient.Object, mockInstallationIdController.Object); var command = new AVCommand("endpoint", method: "GET", data: null); return commandRunner.RunCommandAsync(command).ContinueWith(t => { Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Assert.IsInstanceOf(typeof(IDictionary<string, object>), t.Result.Item2); Assert.AreEqual(0, t.Result.Item2.Count); }); }
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<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<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; }); }
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; })); }
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; })); }
public Task TestRunCommandWithInvalidString() { var mockHttpClient = new Mock<IHttpClient>(); var mockInstallationIdController = new Mock<IInstallationIdController>(); var fakeResponse = Task<Tuple<HttpStatusCode, string>>.FromResult(new Tuple<HttpStatusCode, string>(HttpStatusCode.OK, "invalid")); mockHttpClient.Setup(obj => obj.ExecuteAsync(It.IsAny<HttpRequest>(), It.IsAny<IProgress<AVUploadProgressEventArgs>>(), It.IsAny<IProgress<AVDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>())).Returns(fakeResponse); mockInstallationIdController.Setup(i => i.GetAsync()).Returns(Task.FromResult<Guid?>(null)); AVCommandRunner commandRunner = new AVCommandRunner(mockHttpClient.Object, mockInstallationIdController.Object); var command = new AVCommand("endpoint", method: "GET", data: null); return commandRunner.RunCommandAsync(command).ContinueWith(t => { Assert.True(t.IsFaulted); Assert.False(t.IsCanceled); Assert.IsInstanceOf<AVException>(t.Exception.InnerException); var parseException = t.Exception.InnerException as AVException; Assert.AreEqual(AVException.ErrorCode.OtherCause, parseException.Code); }); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="uploadProgress"></param> /// <param name="downloadProgress"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <Tuple <HttpStatusCode, IDictionary <string, object> > > RunCommandAsync(AVCommand command, IProgress <AVUploadProgressEventArgs> uploadProgress = null, IProgress <AVDownloadProgressEventArgs> downloadProgress = null, CancellationToken cancellationToken = default(CancellationToken)) { return(PrepareCommand(command).ContinueWith(commandTask => { var requestLog = commandTask.Result.ToLog(); AVClient.PrintLog("http=>" + requestLog); return httpClient.ExecuteAsync(commandTask.Result, uploadProgress, downloadProgress, cancellationToken).OnSuccess(t => { cancellationToken.ThrowIfCancellationRequested(); var response = t.Result; var contentString = response.Item2; int responseCode = (int)response.Item1; var responseLog = responseCode + ";" + contentString; AVClient.PrintLog("http<=" + responseLog); 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) { AVClient.PrintLog("error response code:" + responseCode); int code = (int)(contentJson.ContainsKey("code") ? (int)contentJson["code"] : (int)AVException.ErrorCode.OtherCause); string error = contentJson.ContainsKey("error") ? contentJson["error"] as string : contentString; AVException.ErrorCode ec = (AVException.ErrorCode)code; throw new AVException(ec, error); } return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1, contentJson); } return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1, null); }); }).Unwrap()); }
private Task<AVCommand> PrepareCommand(AVCommand command) { AVCommand newCommand = new AVCommand(command); Task<AVCommand> installationIdTask = installationIdController.GetAsync().ContinueWith(t => { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-Installation-Id", t.Result.ToString())); return newCommand; }); // TODO (richardross): Inject configuration instead of using shared static here. AVClient.Configuration configuration = AVClient.CurrentConfiguration; newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-Id", configuration.ApplicationId)); newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-Client-Version", AVClient.VersionString)); if (configuration.AdditionalHTTPHeaders != null) { foreach (var header in configuration.AdditionalHTTPHeaders) { newCommand.Headers.Add(header); } } if (!string.IsNullOrEmpty(configuration.VersionInfo.BuildVersion)) { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-App-Build-Version", configuration.VersionInfo.BuildVersion)); } if (!string.IsNullOrEmpty(configuration.VersionInfo.DisplayVersion)) { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-App-Display-Version", configuration.VersionInfo.DisplayVersion)); } if (!string.IsNullOrEmpty(configuration.VersionInfo.OSVersion)) { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-OS-Version", configuration.VersionInfo.OSVersion)); } // TODO (richardross): I hate the idea of having this super tightly coupled static variable in here. // Lets eventually get rid of it. if (!string.IsNullOrEmpty(AVClient.MasterKey)) { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-Key", AVClient.MasterKey + ",master")); } else { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LC-Key", configuration.ApplicationKey)); } // TODO (richardross): Inject this instead of using static here. if (AVUser.IsRevocableSessionEnabled) { newCommand.Headers.Add(new KeyValuePair<string, string>("X-LeanCloud-Revocable-Session", revocableSessionTokenTrueValue)); } return installationIdTask; }
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 virtual 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(); }
/// <summary> /// Requests the login SMS code asynchronous. /// </summary> /// <param name="mobilePhoneNumber">The mobile phone number.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public static Task<bool> RequestLoginSmsCodeAsync(string mobilePhoneNumber, CancellationToken cancellationToken) { Dictionary<string, object> strs = new Dictionary<string, object>() { { "mobilePhoneNumber", mobilePhoneNumber } }; var command = new AVCommand("requestLoginSmsCode", method: "POST", sessionToken: CurrentSessionToken, data: strs); return AVPlugins.Instance.CommandRunner.RunCommandAsync(command).ContinueWith(t => { return AVClient.IsSuccessStatusCode(t.Result.Item1); }); }
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 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); }
/// <summary> /// 请求重置密码,需要传入注册时使用的手机号。 /// </summary> /// <param name="mobilePhoneNumber">注册时使用的手机号</param> /// <param name="cancellationToken">cancellationToken</param> /// <returns></returns> public static Task RequestPasswordResetBySmsCode(string mobilePhoneNumber, CancellationToken cancellationToken) { string currentSessionToken = AVUser.CurrentSessionToken; Dictionary<string, object> strs = new Dictionary<string, object>() { { "mobilePhoneNumber", mobilePhoneNumber } }; var command = new AVCommand("requestPasswordResetBySmsCode", method: "POST", sessionToken: currentSessionToken, data: strs); return AVPlugins.Instance.CommandRunner.RunCommandAsync(command).ContinueWith(t => { return AVClient.IsSuccessStatusCode(t.Result.Item1); }); //return AVClient.RequestAsync("POST", "requestPasswordResetBySmsCode", currentSessionToken, strs, cancellationToken); }
/// <summary> /// 通过验证码重置密码。 /// </summary> /// <param name="newPassword">新密码</param> /// <param name="smsCode">6位数验证码</param> /// <param name="cancellationToken">cancellationToken</param> /// <returns></returns> public static Task<bool> ResetPasswordBySmsCodeAsync(string newPassword, string smsCode, CancellationToken cancellationToken) { string currentSessionToken = AVUser.CurrentSessionToken; Dictionary<string, object> strs = new Dictionary<string, object>() { { "password", newPassword } }; var command = new AVCommand("resetPasswordBySmsCode/" + smsCode, method: "PUT", sessionToken: currentSessionToken, data: strs); return AVPlugins.Instance.CommandRunner.RunCommandAsync(command).ContinueWith(t => { return AVClient.IsSuccessStatusCode(t.Result.Item1); }); }
/// <summary> /// 验证手机验证码是否为有效值 /// </summary> /// <param name="code">手机收到的验证码</param> /// <param name="mobilePhoneNumber">手机号</param> /// <param name="cancellationToken"></param> /// <returns></returns> public static Task<bool> VerifyMobilePhoneAsync(string code, string mobilePhoneNumber, CancellationToken cancellationToken) { var command = new AVCommand("verifyMobilePhone" + code.Trim() + "?mobilePhoneNumber=" + mobilePhoneNumber.Trim(), method: "POST", sessionToken: null, data: null); return AVPlugins.Instance.CommandRunner.RunCommandAsync(command).ContinueWith(t => { return AVClient.IsSuccessStatusCode(t.Result.Item1); }); }
private IList <Task <IDictionary <string, object> > > ExecuteBatchRequest(IList <AVCommand> 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 encodedRequests = requests.Select(r => { var results = new Dictionary <string, object> { { "method", r.Method }, { "path", r.Uri.AbsolutePath }, }; if (r.DataObject != null) { results["body"] = r.DataObject; } return(results); }).Cast <object>().ToList(); var command = new AVCommand("batch", method: "POST", sessionToken: sessionToken, data: new Dictionary <string, object> { { "requests", encodedRequests } }); 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 = Conversion.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); }
internal static Task<Tuple<HttpStatusCode, IDictionary<string, object>>> RequestAsync(string method, Uri relativeUri, string sessionToken, IDictionary<string, object> data, CancellationToken cancellationToken) { var command = new AVCommand(relativeUri.ToString(), method: method, sessionToken: sessionToken, data: data); return AVPlugins.Instance.CommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); }