private async void checkForUpdateAsync() { try { var releases = new JsonWebRequest <GitHubRelease>("https://api.github.com/repos/ppy/osu/releases/latest"); await releases.PerformAsync(); var latest = releases.ResponseObject; if (latest.TagName != version) { notificationOverlay.Post(new SimpleNotification { Text = $"A newer release of osu! has been found ({version} → {latest.TagName}).\n\n" + "Click here to download the new version, which can be installed over the top of your existing installation", Icon = FontAwesome.Solid.Upload, Activated = () => { host.OpenUrlExternally(getBestUrl(latest)); return(true); } }); } } catch { // we shouldn't crash on a web failure. or any failure for the matter. } }
public bool TryAuthenticate(string code, string state, string verify, out GithubAccessToken token) { token = null; if (!String.Equals(state, verify, StringComparison.Ordinal)) { return false; } var post = String.Concat("client_id=", Configuration.ClientId, "&client_secret=", Configuration.ClientSecret, "&code=", code); try { var tokenRequest = new JsonWebRequest("https://github.com/login/oauth/access_token") { PostData = post }; var response = tokenRequest.Request<TokenResponse>(); token = new GithubAccessToken() { ReturnUrl = state.Length > 32 ? state.Substring(32) : null, Scope = response.scope, Type = response.token_type, Value = response.access_token }; } catch (Exception e) { var t = e; } return token != null; }
public void SaveProfilePhoto(long ownerId, Rect thumbnailRect, byte[] photoData, Action <BackendResult <ProfilePhoto, ResultCode> > callback) { ProfilesService.GetPhotoUploadServer(ownerId, (Action <BackendResult <VKClient.Audio.Base.UploadServerAddress, ResultCode> >)(res => { if (res.ResultCode != ResultCode.Succeeded) { callback(new BackendResult <ProfilePhoto, ResultCode>(res.ResultCode)); } else { string uploadUrl = res.ResultData.upload_url; // ISSUE: explicit reference operation if (((Rect)@thumbnailRect).Width != 0.0) { // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation string str = string.Format("&_square_crop={0},{1},{2}&_full={0},{1},{2},{2}", (int)((Rect)@thumbnailRect).X, (int)((Rect)@thumbnailRect).Y, (int)((Rect)@thumbnailRect).Width); uploadUrl += str; } MemoryStream memoryStream = new MemoryStream(photoData); JsonWebRequest.Upload(uploadUrl, (Stream)memoryStream, "photo", "image", (Action <JsonResponseData>)(jsonResult => { if (!jsonResult.IsSucceeded) { callback(new BackendResult <ProfilePhoto, ResultCode>(ResultCode.UnknownError)); } else { ProfilesService.SaveProfilePhoto(JsonConvert.DeserializeObject <UploadPhotoResponseData>(jsonResult.JsonString), ownerId, callback); } }), "MyImage.jpg", null, null); } })); }
public void TestUnbindOnDispose(bool async) { WebRequest request; using (request = new JsonWebRequest <HttpBinGetResponse>("https://httpbin.org/get") { Method = HttpMethod.GET }) { request.Started += () => { }; request.Failed += e => { }; request.DownloadProgress += (l1, l2) => { }; request.UploadProgress += (l1, l2) => { }; Assert.DoesNotThrow(request.Perform); } var events = request.GetType().GetEvents(BindingFlags.Instance | BindingFlags.Public); foreach (var e in events) { var field = request.GetType().GetField(e.Name, BindingFlags.Instance | BindingFlags.Public); Assert.IsFalse(((Delegate)field?.GetValue(request))?.GetInvocationList().Length > 0); } }
public void TestValidGet([ValueSource(nameof(protocols))] string protocol, [Values(true, false)] bool async) { var url = $"{protocol}://{host}/get"; var request = new JsonWebRequest <HttpBinGetResponse>(url) { Method = HttpMethod.Get, AllowInsecureRequests = true }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject != null); Assert.IsTrue(responseObject.Headers.UserAgent == "osu!"); Assert.IsTrue(responseObject.Url == url); Assert.IsFalse(hasThrown); }
private dynamic getJsonFromApi(string request) { var req = new JsonWebRequest <dynamic>($"{base_url}/api/{request}"); req.Perform(); return(req.ResponseObject); }
private static List <GitHubPullRequest> GetPullRequests() { // Gets the last release var previousVersion = GetLastGithubRelease(); var reqMinified = new JsonWebRequest <List <GitHubMinifiedPullRequest> >($"{GitHubApiEndpoint}pulls?state=closed"); reqMinified.AuthenticatedBlockingPerform(); List <GitHubMinifiedPullRequest> minifiedPullRequests = reqMinified.ResponseObject; List <GitHubPullRequest> requests = new List <GitHubPullRequest>(); foreach (var pr in minifiedPullRequests) { // We want to ignore all previous pr's from the last release if (pr.MergedAt < previousVersion.PublishedAt) { continue; } var req = new JsonWebRequest <GitHubPullRequest>($"{GitHubApiEndpoint}pulls/{pr.Number}"); req.AuthenticatedBlockingPerform(); requests.Add(req.ResponseObject); } pullRequests = requests; return(requests); }
public bool TryAuthenticate(string code, string state, string verify, out GithubAccessToken token) { token = null; if (!String.Equals(state, verify, StringComparison.Ordinal)) { return(false); } var post = String.Concat("client_id=", Configuration.ClientId, "&client_secret=", Configuration.ClientSecret, "&code=", code); try { var tokenRequest = new JsonWebRequest("https://github.com/login/oauth/access_token") { PostData = post }; var response = tokenRequest.Request <TokenResponse>(); token = new GithubAccessToken() { ReturnUrl = state.Length > 32 ? state.Substring(32) : null, Scope = response.scope, Type = response.token_type, Value = response.access_token }; } catch (Exception e) { var t = e; } return(token != null); }
private static GitHubRelease getLastGithubRelease(bool includeDrafts = false) { var req = new JsonWebRequest <List <GitHubRelease> >($"{GitHubApiEndpoint}"); req.AuthenticatedBlockingPerform(); return(req.ResponseObject.FirstOrDefault(r => includeDrafts || !r.Draft)); }
public void TestPostWithJsonRequest([Values(true, false)] bool async) { var request = new JsonWebRequest <HttpBinPostResponse>($"{default_protocol}://{host}/post") { Method = HttpMethod.Post, AllowInsecureRequests = true, }; var testObject = new TestObject(); request.AddRaw(JsonConvert.SerializeObject(testObject)); if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } var responseObject = request.ResponseObject; Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); Assert.IsTrue(responseObject.Headers.ContentLength > 0); Assert.IsTrue(responseObject.Json != null); Assert.AreEqual(testObject.TestString, responseObject.Json.TestString); Assert.IsTrue(responseObject.Headers.ContentType == null); }
public void UpdateChatPhoto(long chatId, byte[] photoData, Rect thumbnailRect, Action <BackendResult <ChatInfoWithMessageId, ResultCode> > callback) { this.GetChatUploadServer(chatId, (Action <BackendResult <UploadServerAddress, ResultCode> >)(getUplResp => { if (getUplResp.ResultCode != ResultCode.Succeeded) { callback(new BackendResult <ChatInfoWithMessageId, ResultCode>(getUplResp.ResultCode)); } else { string uploadUrl = getUplResp.ResultData.upload_url; // ISSUE: explicit reference operation if (((Rect)@thumbnailRect).Width != 0.0) { // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation string str = string.Format("&_square_crop={0},{1},{2}&_full={0},{1},{2},{2}", (int)((Rect)@thumbnailRect).X, (int)((Rect)@thumbnailRect).Y, (int)((Rect)@thumbnailRect).Width); uploadUrl += str; } MemoryStream memoryStream = new MemoryStream(photoData); JsonWebRequest.Upload(uploadUrl, (Stream)memoryStream, "photo", "image", (Action <JsonResponseData>)(jsonResult => { if (!jsonResult.IsSucceeded) { callback(new BackendResult <ChatInfoWithMessageId, ResultCode>(ResultCode.UnknownError)); } else { this.SetChatPhoto(JsonConvert.DeserializeObject <UploadResponseData>(jsonResult.JsonString), callback); } }), "MyImage.jpg", null, null); } })); }
public void TestPostWithJsonRequest(bool async) { var request = new JsonWebRequest <HttpBinPostResponse>("https://httpbin.org/post") { Method = HttpMethod.POST }; var testObject = new TestObject(); request.AddRaw(JsonConvert.SerializeObject(testObject)); if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } var responseObject = request.ResponseObject; Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); Assert.IsTrue(responseObject.Headers.ContentLength > 0); Assert.IsTrue(responseObject.Json != null); Assert.AreEqual(testObject.TestString, responseObject.Json.TestString); Assert.IsTrue(responseObject.Headers.ContentType == null); }
public void TestValidGet([ValueSource(nameof(protocols))] string protocol, [Values(true, false)] bool async) { var url = $"{protocol}://{host}/get"; var request = new JsonWebRequest <HttpBinGetResponse>(url) { Method = HttpMethod.Get, AllowInsecureRequests = true }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject != null); Assert.IsTrue(responseObject.Headers.UserAgent == "osu!"); // disabled due to hosted version returning incorrect response (https://github.com/postmanlabs/httpbin/issues/545) // Assert.AreEqual(url, responseObject.Url); Assert.IsFalse(hasThrown); }
public void TestValidGet(string protocol, bool async) { var url = $"{protocol}://httpbin.org/get"; var request = new JsonWebRequest <HttpBinGetResponse>(url) { Method = HttpMethod.GET }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject != null); Assert.IsTrue(responseObject.Headers.UserAgent == "osu!"); Assert.IsTrue(responseObject.Url == url); Assert.IsFalse(hasThrown); }
public void Play() { if (this._currentState == VoiceMessageAttachmentViewModel.State.NotStarted || this._currentState == VoiceMessageAttachmentViewModel.State.Failed) { this.CurrentState = VoiceMessageAttachmentViewModel.State.Downloading; Stream stream = CacheManager.GetStreamForWrite(this._localFile); this._currentCancellationToken = new Cancellation(); JsonWebRequest.Download(this.VideoUri, stream, delegate(bool res) { Execute.ExecuteOnUIThread(delegate { try { if (this._currentCancellationToken.IsSet) { this.CurrentState = VoiceMessageAttachmentViewModel.State.Failed; stream.Close(); CacheManager.TryDelete(this._localFile, CacheManager.DataType.CachedData); } else { int fileSize = (int)stream.Length; stream.Close(); if (res) { MediaLRUCache.Instance.AddLocalFile(this.VideoUri, this._localFile, fileSize); this.CurrentState = VoiceMessageAttachmentViewModel.State.Downloaded; this.CurrentState = VoiceMessageAttachmentViewModel.State.Playing; } else { this.CurrentState = VoiceMessageAttachmentViewModel.State.Failed; CacheManager.TryDelete(this._localFile, CacheManager.DataType.CachedData); } } } catch { try { stream.Close(); } catch { } this.CurrentState = VoiceMessageAttachmentViewModel.State.Failed; CacheManager.TryDelete(this._localFile, CacheManager.DataType.CachedData); } }); }, delegate(double progress) { this.DownloadProgress = progress; }, this._currentCancellationToken); return; } if (this._currentState == VoiceMessageAttachmentViewModel.State.Downloaded) { this.CurrentState = VoiceMessageAttachmentViewModel.State.Playing; } }
public void TestAbortReceive(bool async) { var request = new JsonWebRequest <HttpBinGetResponse>("https://httpbin.org/get") { Method = HttpMethod.GET }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; request.Started += () => request.Abort(); if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); Assert.IsTrue(request.ResponseObject == null); Assert.IsFalse(hasThrown); }
public void TestRestartAfterAbort(bool async) { var request = new JsonWebRequest <HttpBinGetResponse>("https://httpbin.org/get") { Method = HttpMethod.GET }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; #pragma warning disable 4014 request.PerformAsync(); #pragma warning restore 4014 Assert.DoesNotThrow(request.Abort); if (async) { Assert.ThrowsAsync <InvalidOperationException>(request.PerformAsync); } else { Assert.Throws <InvalidOperationException>(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject == null); Assert.IsFalse(hasThrown); }
public void UploadVoiceMessageDocument(Stream stream, List <int> waveform, Action <BackendResult <Doc, ResultCode> > callback, Action <double> progressCallback = null, Cancellation cancellation = null) { DocumentsService.GetDocumentUploadServer(0, "audio_message", (Action <BackendResult <VKClient.Audio.Base.UploadServerAddress, ResultCode> >)(uploadUrlResponse => { if (uploadUrlResponse.ResultCode == ResultCode.Succeeded) { JsonWebRequest.UploadVoiceMessage(uploadUrlResponse.ResultData.upload_url, stream, "file", "file", waveform, (Action <JsonResponseData>)(jsonResult => { if (jsonResult.IsSucceeded) { UploadDocResponseData uploadData = JsonConvert.DeserializeObject <UploadDocResponseData>(jsonResult.JsonString); if (string.IsNullOrEmpty(uploadData.error)) { DocumentsService.SaveDocument(uploadData, callback); } else { callback(new BackendResult <Doc, ResultCode>(ResultCode.UnknownError)); } } else { callback(new BackendResult <Doc, ResultCode>(ResultCode.UnknownError)); } }), "Voice Message", progressCallback, cancellation); } else { callback(new BackendResult <Doc, ResultCode>(uploadUrlResponse.ResultCode)); } })); }
private static void PlayYouTube(string uri, int resolution, Action callback) { YouTubeExtractorAdapter.GetYouTubeVideoUri(uri, resolution, (Action <bool, Uri>)((success, resultUri) => Execute.ExecuteOnUIThread((Action)(() => { if (!success) { Navigator.Current.NavigateToWebUri(uri, false, false); callback(); } else { JsonWebRequest.GetHttpStatusCode(resultUri.ToString(), (Action <HttpStatusCode>)(statusCode => { if (statusCode == HttpStatusCode.OK) { VideoPlayerHelper.LaunchMediaPlayer(resultUri); } else { Navigator.Current.NavigateToWebUri(uri, false, false); } callback(); })); } })))); }
public void TestGetWithQueryStringParameters() { const string test_key_1 = "testkey1"; const string test_val_1 = "testval1 that ends with a #"; const string test_key_2 = "testkey2"; const string test_val_2 = "testval2 that ends with a space "; var request = new JsonWebRequest <HttpBinGetResponse>($@"{default_protocol}://{host}/get") { Method = HttpMethod.Get, AllowInsecureRequests = true }; request.AddParameter(test_key_1, test_val_1); request.AddParameter(test_key_2, test_val_2); Assert.DoesNotThrow(request.Perform); var responseObject = request.ResponseObject; Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); Assert.NotNull(responseObject.Arguments); Assert.True(responseObject.Arguments.ContainsKey(test_key_1)); Assert.AreEqual(test_val_1, responseObject.Arguments[test_key_1]); Assert.True(responseObject.Arguments.ContainsKey(test_key_2)); Assert.AreEqual(test_val_2, responseObject.Arguments[test_key_2]); }
private static GitHubRelease getLastGithubRelease() { var req = new JsonWebRequest <List <GitHubRelease> >($"{GitHubApiEndpoint}"); req.AuthenticatedBlockingPerform(); return(req.ResponseObject.FirstOrDefault()); }
private static void AnnounceToDiscord(string version) { if (!AnnounceDiscord) { return; } var req = new JsonWebRequest <DiscordWebhook>(DiscordWebhookURL) { Method = HttpMethod.Post, ContentType = "application/json" }; // Get all of the previous PR's name var body = $"Version {version} for {GitHubRepoName} has been released! this now fixes and adds:\r\n"; // Adds every pull requests after the last release pullRequests.ForEach(pr => { body += $"- {pr.Title} | {pr.User.Name}\r\n"; }); body += $"\r\nDownload:\r\n<https://github.com/{GitHubUsername}/{GitHubRepoName}/releases>\r\n<https://www.nuget.org/packages/{GitHubRepoName}/{version}>"; req.AddRaw(JsonConvert.SerializeObject(new DiscordWebhook { Content = body })); req.Perform(); }
public void TestUnbindOnDispose([Values(true, false)] bool async) { WebRequest request; using (request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get") { Method = HttpMethod.Get, AllowInsecureRequests = true, }) { request.Started += () => { }; request.Failed += e => { }; request.DownloadProgress += (l1, l2) => { }; request.UploadProgress += (l1, l2) => { }; Assert.DoesNotThrow(request.Perform); } var events = request.GetType().GetEvents(BindingFlags.Instance | BindingFlags.Public); foreach (var e in events) { var field = request.GetType().GetField(e.Name, BindingFlags.Instance | BindingFlags.Public); Assert.IsFalse(((Delegate)field?.GetValue(request))?.GetInvocationList().Length > 0); } }
public void TestRestartAfterAbort([Values(true, false)] bool async) { var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get") { Method = HttpMethod.Get, AllowInsecureRequests = true, }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; #pragma warning disable 4014 request.PerformAsync(); #pragma warning restore 4014 Assert.DoesNotThrow(request.Abort); if (async) { Assert.ThrowsAsync <InvalidOperationException>(request.PerformAsync); } else { Assert.Throws <InvalidOperationException>(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject == null); Assert.IsFalse(hasThrown); }
public void TestRestartAfterAbort() { var cancellationSource = new CancellationTokenSource(); var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get") { Method = HttpMethod.Get, AllowInsecureRequests = true, }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; cancellationSource.Cancel(); request.PerformAsync(cancellationSource.Token); Assert.ThrowsAsync <InvalidOperationException>(request.PerformAsync); Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject == null); Assert.IsFalse(hasThrown); }
public void TestAbortRequest() { var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get") { Method = HttpMethod.Get, AllowInsecureRequests = true, }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; #pragma warning disable 4014 request.PerformAsync(); #pragma warning restore 4014 Assert.DoesNotThrow(request.Abort); Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); Assert.IsTrue(request.ResponseObject == null); Assert.IsFalse(hasThrown); }
public void TestAbortReceive([Values(true, false)] bool async) { var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get") { Method = HttpMethod.Get, AllowInsecureRequests = true, }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; request.Started += () => request.Abort(); if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); Assert.IsTrue(request.ResponseObject == null); Assert.IsFalse(hasThrown); }
private static void testValidGetInternal(bool async, JsonWebRequest <HttpBinGetResponse> request, string expectedUserAgent) { bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; if (async) { Assert.DoesNotThrowAsync(request.PerformAsync); } else { Assert.DoesNotThrow(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsFalse(request.Aborted); var responseObject = request.ResponseObject; Assert.IsTrue(responseObject != null); Assert.IsTrue(responseObject.Headers.UserAgent == expectedUserAgent); // disabled due to hosted version returning incorrect response (https://github.com/postmanlabs/httpbin/issues/545) // Assert.AreEqual(url, responseObject.Url); Assert.IsFalse(hasThrown); }
public void TestJsonWebRequestThrowsCorrectlyOnMultipleErrors([Values(true, false)] bool async) { var request = new JsonWebRequest <Drawable>("badrequest://www.google.com") { AllowInsecureRequests = true, }; bool hasThrown = false; request.Failed += exception => hasThrown = exception != null; if (async) { Assert.ThrowsAsync <ArgumentException>(request.PerformAsync); } else { Assert.Throws <ArgumentException>(request.Perform); } Assert.IsTrue(request.Completed); Assert.IsTrue(request.Aborted); Assert.IsNull(request.GetResponseString()); Assert.IsNull(request.ResponseObject); Assert.IsTrue(hasThrown); }
/// <summary> /// Download assets from a previous release into the releases folder. /// </summary> /// <param name="release"></param> private static void getAssetsFromRelease(GitHubRelease release) { if (!canGitHub) { return; } //there's a previous release for this project. var assetReq = new JsonWebRequest <List <GitHubObject> >($"{GitHubApiEndpoint}/{release.Id}/assets"); assetReq.AuthenticatedBlockingPerform(); var assets = assetReq.ResponseObject; //make sure our RELEASES file is the same as the last build on the server. var releaseAsset = assets.FirstOrDefault(a => a.Name == "RELEASES"); //if we don't have a RELEASES asset then the previous release likely wasn't a Squirrel one. if (releaseAsset == null) { return; } bool requireDownload = false; if (!File.Exists(Path.Combine(releases_folder, $"{PackageName}-{release.Name}-full.nupkg"))) { write("Last version's package not found locally.", ConsoleColor.Red); requireDownload = true; } else { var lastReleases = new RawFileWebRequest($"{GitHubApiEndpoint}/assets/{releaseAsset.Id}"); lastReleases.AuthenticatedBlockingPerform(); if (File.ReadAllText(Path.Combine(releases_folder, "RELEASES")) != lastReleases.ResponseString) { write("Server's RELEASES differed from ours.", ConsoleColor.Red); requireDownload = true; } } if (!requireDownload) { return; } write("Refreshing local releases directory..."); refreshDirectory(releases_folder); foreach (var a in assets) { if (a.Name.EndsWith(".exe") || a.Name.EndsWith(".app.zip")) { continue; } write($"- Downloading {a.Name}...", ConsoleColor.Yellow); new FileWebRequest(Path.Combine(releases_folder, a.Name), $"{GitHubApiEndpoint}/assets/{a.Id}").AuthenticatedBlockingPerform(); } }
private void Play(GifPlayStartType startType, bool suppressStats) { if (this._state == InplaceGifViewerViewModel.State.NotStarted || this._state == InplaceGifViewerViewModel.State.Failed) { this.CurrentState = InplaceGifViewerViewModel.State.Downloading; Stream stream = CacheManager.GetStreamForWrite(this._localFile); this._currentCancellationToken = new Cancellation(); JsonWebRequest.Download(this.VideoUri, stream, (Action <bool>)(res => Execute.ExecuteOnUIThread((Action)(() => { try { if (this._currentCancellationToken.IsSet) { this.CurrentState = InplaceGifViewerViewModel.State.Failed; stream.Close(); CacheManager.TryDelete(this._localFile, CacheManager.DataType.CachedData); } else { int fileSize = (int)stream.Length; stream.Close(); if (res) { MediaLRUCache.Instance.AddLocalFile(this.VideoUri, this._localFile, fileSize); this.CurrentState = InplaceGifViewerViewModel.State.Downloaded; this.CurrentState = InplaceGifViewerViewModel.State.Playing; this.SendGifPlayStats(startType, suppressStats); } else { this.CurrentState = InplaceGifViewerViewModel.State.Failed; CacheManager.TryDelete(this._localFile, CacheManager.DataType.CachedData); } } } catch { try { stream.Close(); } catch { } this.CurrentState = InplaceGifViewerViewModel.State.Failed; CacheManager.TryDelete(this._localFile, CacheManager.DataType.CachedData); } }))), (Action <double>)(progress => this.DownloadProgress = progress), this._currentCancellationToken); } else { if (this._state != InplaceGifViewerViewModel.State.Downloaded) { return; } this.CurrentState = InplaceGifViewerViewModel.State.Playing; this.SendGifPlayStats(startType, suppressStats); } }
public GithubUser GetUser(string accessToken) { var authorization = "Bearer " + accessToken; var userRequest = new JsonWebRequest("https://api.github.com/user") { Authorization = authorization }; var user = userRequest.Request<User>(); var emailRequest = new JsonWebRequest("https://api.github.com/user/emails") { Accept = "application/vnd.github.v3", Authorization = authorization }; var emails = emailRequest.Request<UserEmail[]>(); var primaryEmail = emails.Where(e => e.Primary).Select(e => e.Email).FirstOrDefault(); return new GithubUser() { Company = user.Company, Login = user.Login, Name = user.Name, PrimaryEmail = primaryEmail }; }