public async Task AuthenticateUser() { var state = Guid.NewGuid().ToString(); var nonce = Guid.NewGuid().ToString(); await accessTokenSem.WaitAsync(); try { var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri($"{authorizationUrl}/connect/authorize?client_id={clientId}&scope={scopes} openid offline_access&response_type=code id_token&" + $"redirect_uri={redirectUri}&state={state}&nonce={nonce}"), new Uri(redirectUri)); if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var data = webAuthenticationResult.ResponseData; var parms = new WwwFormUrlDecoder(new Uri(data.Replace("#", "?")).Query); if (state != parms.Where(p => p.Name == "state").Single().Value) { throw new UnauthorizedException("State differs"); } var code = parms.Where(p => p.Name == "code").Single().Value; var client = new System.Net.Http.HttpClient(); var dict = new Dictionary <string, string>(); dict.Add("client_id", clientId); dict.Add("client_secret", clientSecret); dict.Add("grant_type", "authorization_code"); dict.Add("code", code); dict.Add("redirect_uri", redirectUri); var res = await client.PostAsync($"{authorizationUrl}/connect/token", new FormUrlEncodedContent(dict)); if (res.IsSuccessStatusCode) { var str = await res.Content.ReadAsStringAsync(); var token = JsonConvert.DeserializeObject <TokenResponse>(str); var tokens = new StoredTokens() { AccessToken = token.access_token, RefreshToken = token.refresh_token, AccessTokenExpires = DateTime.Now.AddSeconds(token.expires_in) }; await tokenStorage.Store(tokens); } else { throw new UnauthorizedException("Could not redeem refresh token."); } } else { throw new UnauthorizedException("Browser authentication was not successful"); } } finally { accessTokenSem.Release(); } }
public SendReplyToastActivation(Uri uri) { WwwFormUrlDecoder query = UriUtils.parseUriQuery(uri); CHAT_ID = query.Where(x => string.Equals(x.Name, CHAT_QUERY)).Select(x => x.Value).FirstOrDefault(); CHAT_MESSAGE_ID = query.Where(x => string.Equals(x.Name, CHAT_MESSAGE_QUERY)).Select(x => x.Value).FirstOrDefault(); IS_VALID = !string.IsNullOrEmpty(CHAT_ID) && !string.IsNullOrEmpty(CHAT_MESSAGE_ID); }
private async Task <WebResponse> ApiPage(WebRequest request) { // Prepare the response object var response = new WebResponse { // Create a new dictionary for headers - this could be done using a more advanced class for // WebResponse object - I just used a simple structure Header = new Dictionary <string, string> { // Add content type header { "Content-Type", "application/json'" } } }; Stream responseText = new MemoryStream(); if (request.Uri.IndexOf('?') > -1) { var queryString = request.Uri.Substring(request.Uri.IndexOf('?')); var decoder = new WwwFormUrlDecoder(queryString); foreach (var color in decoder.Where(param => param.Name == "color").Select(param => Color.FromArgb(255, Convert.ToByte(param.Value.Substring(0, 2), 16), Convert.ToByte(param.Value.Substring(2, 2), 16), Convert.ToByte(param.Value.Substring(4, 2), 16)))) { try { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var colorBrush = new SolidColorBrush(color); LightColor = colorBrush; var contentWriter = new StreamWriter(responseText); contentWriter.WriteLine( "{\"status\":200,\"message\":\"Color was set to " + LightColor.Color + "\"}" ); contentWriter.Flush(); } ); } catch (Exception e) { Debug.WriteLine(e); } } } // Assign the response response.Content = responseText; // Return the response return(response); }
public ChatToastActivation(Uri uri) { WwwFormUrlDecoder query = UriUtils.parseUriQuery(uri); if (query is null) { IS_VALID = false; return; } string chatIdStr = query.Where(x => string.Equals(x.Name, CHAT_QUERY)).Select(x => x.Value).FirstOrDefault(); IS_VALID = int.TryParse(chatIdStr, out CHAT_ID) && CHAT_ID != 0; string msgIdStr = query.Where(x => string.Equals(x.Name, CHAT_MESSAGE_QUERY)).Select(x => x.Value).FirstOrDefault(); IS_VALID &= int.TryParse(msgIdStr, out CHAT_MESSAGE_ID) && CHAT_MESSAGE_ID != 0; }
public MarkChatAsReadToastActivation(Uri uri) { WwwFormUrlDecoder query = UriUtils.parseUriQuery(uri); if (query is null) { IS_VALID = false; return; } CHAT_ID = query.Where(x => string.Equals(x.Name, CHAT_QUERY)).Select(x => x.Value).FirstOrDefault(); IS_VALID = !string.IsNullOrEmpty(CHAT_ID); }
public static bool TryGetParameters <T>(this NavigationEventArgs args, string name, out IEnumerable <T> values) { try { var www = new WwwFormUrlDecoder(args.Parameter.ToString()); values = www .Where(x => x.Name == name) .Select(x => (T)Convert.ChangeType(x.Value, typeof(T))); return(true); } catch { values = default(IEnumerable <T>); return(false); } }
//--------------------------------------------------------Attributes:-----------------------------------------------------------------\\ #region --Attributes-- #endregion //--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public static AbstractToastActivation parseArguments(string activationString) { if (string.IsNullOrEmpty(activationString) || !activationString.Contains('=')) { return(null); } if (!Uri.TryCreate(activationString, UriKind.RelativeOrAbsolute, out Uri result)) { Logger.Warn("Failed to parse activationString to Uri: " + activationString); return(null); } WwwFormUrlDecoder query = UriUtils.parseUriQuery(result); if (query is null) { return(null); } string type = query.Where(x => string.Equals(x.Name, AbstractToastActivation.TYPE_QUERY)).Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(type)) { Logger.Warn("Failed to parse activationString - no type query: " + activationString); return(null); } switch (type) { case ChatToastActivation.TYPE: return(new ChatToastActivation(result)); case MarkChatAsReadToastActivation.TYPE: return(new MarkChatAsReadToastActivation(result)); case MarkMessageAsReadToastActivation.TYPE: return(new MarkMessageAsReadToastActivation(result)); case SendReplyToastActivation.TYPE: return(new SendReplyToastActivation(result)); default: return(null); } }
private async Task HandleProtocolActivation(IActivatedEventArgs args) { var protocolArgs = (ProtocolActivatedEventArgs)args; var uri = protocolArgs.Uri; if (string.IsNullOrEmpty(uri.Query)) { return; } WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query); switch (uri.Host) { case "goto": if (decoder[0]?.Name == "page") { if (decoder[0]?.Value == VLCPage.SettingsPageUI.ToString()) { Locator.NavigationService.Go(VLCPage.SettingsPageUI); } } break; case "openstream": // do stuff if (decoder[0]?.Name == "from") { switch (decoder[0]?.Value) { case "clipboard": await Task.Delay(1000); var dataPackage = Clipboard.GetContent(); Uri url = null; if (dataPackage.Contains(StandardDataFormats.ApplicationLink)) { url = await dataPackage.GetApplicationLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.WebLink)) { url = await dataPackage.GetWebLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.Text)) { url = new Uri(await dataPackage.GetTextAsync()); } if (url != null) { await Locator.MediaPlaybackViewModel.PlayStream(url.AbsoluteUri); } break; case "useraction": Locator.MainVM.GoToStreamPanel.Execute(null); break; case "url": if (decoder[1]?.Name == "url") { StorageFile subsFd = null; try { var subsFrom = decoder.Where((item, index) => item.Name == "subs_from").FirstOrDefault(); var subsValue = decoder.Where((item, index) => item.Name == "subs").FirstOrDefault(); if (!(subsFrom == default(IWwwFormUrlDecoderEntry) && subsValue == default(IWwwFormUrlDecoderEntry))) { switch (subsFrom.Value) { case "path": //this StorageFile is like a File Descriptor from Unix subsFd = await StorageFile.GetFileFromPathAsync(subsValue.Value); if (subsFd == null) { ToastHelper.Basic("Failed to Load Subtitles: Couln´t find the file."); } else if (!StorageApplicationPermissions.FutureAccessList.CheckAccess(subsFd)) { StorageApplicationPermissions.FutureAccessList.Add(subsFd); } break; case "url": using (var httpClient = new System.Net.Http.HttpClient()) { var subsContent = await httpClient.GetStringAsync(subsValue.Value); subsFd = await ApplicationData.Current.LocalFolder.CreateFileAsync(subsContent.GetHashCode().ToString(), CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(subsFd, subsContent); } break; case "picker": var openPicker = new FileOpenPicker(); openPicker.FileTypeFilter.Add(".srt"); openPicker.FileTypeFilter.Add(".txt"); openPicker.SuggestedStartLocation = PickerLocationId.Downloads; subsFd = await openPicker.PickSingleFileAsync(); break; } } } //StorageFile.GetFileFromPath or CreateFileAsync failed catch (UnauthorizedAccessException) { ToastHelper.Basic("Failed to Load Subtitles: Access Denied to the file."); } //HttpClient usually fails with an AggregateException instead of WebException or HttpRequest...Exception catch (AggregateException) { ToastHelper.Basic("Failed to Load Subtitles: Problems downloading the subtitles"); } //HttpClient fails with a WebException when there´s no connectivity catch (System.Net.WebException) { ToastHelper.Basic("Failed to Load Subtitles: No Connectivity"); } catch (Exception ex) { ToastHelper.Basic("Failed to Load Subtitles: " + ex.GetType().ToString()); } await Locator.MediaPlaybackViewModel.PlayStream(decoder[1].Value); if (subsFd != null) { ToastHelper.Basic("Subtitles Loaded Successfully"); Locator.MediaPlaybackViewModel.OpenSubtitleCommand.Execute(subsFd); } } break; } } break; } }