private static IEnumerable <Uri> ExtractDownloadUrls(string source)
        {
#if NETFX_CORE
            string urlMap = new WwwFormUrlDecoder(source).GetFirstValueByName("url_encoded_fmt_stream_map");
#else
            string urlMap = HttpUtility.ParseQueryString(source).Get("url_encoded_fmt_stream_map");
#endif

            string[] splitByUrls = urlMap.Split(',');

            foreach (string s in splitByUrls)
            {
#if NETFX_CORE
                var    decoder = new WwwFormUrlDecoder(s);
                string url     = string.Format("{0}&fallback_host={1}&signature={2}",
                                               decoder.GetFirstValueByName("url"),
                                               decoder.GetFirstValueByName("fallback_host"),
                                               decoder.GetFirstValueByName("sig"));

                url = WebUtility.UrlDecode(url);
                url = WebUtility.UrlDecode(url);
#else
                var    queries = HttpUtility.ParseQueryString(s);
                string url     = string.Format("{0}&fallback_host={1}&signature={2}", queries["url"], queries["fallback_host"], queries["sig"]);

                url = HttpUtility.UrlDecode(url);
                url = HttpUtility.UrlDecode(url);
#endif
                yield return(new Uri(url));
            }
        }
Esempio n. 2
0
        private async void WebViewer_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            // Check if new location is redirect uri
            if (args.Uri.AbsoluteUri.IndexOf(App.RedirectUri) == 0)
            {
                // Get parameters
                var encoder     = new WwwFormUrlDecoder(args.Uri.AbsoluteUri.Replace('#', '&')); // Replacing # with ? to make GetFirstValueByName() work
                var accessToken = encoder.GetFirstValueByName("access_token");
                var expires     = encoder.GetFirstValueByName("expires");
                if (!String.IsNullOrEmpty(accessToken))
                {
                    // Success
                    App.AccessToken = accessToken;
                    App.Expires     = expires;

                    Frame.GoBack();
                    var successDialog = new MessageDialog("Successfully logged in.", "Success!");
                    await successDialog.ShowAsync();

                    return;
                }

                // Show error message, if something went wrong
                var errorDialog = new MessageDialog("Whoops, we could not log you in successfully. Sorry for that!", "Something went wrong...");
                await errorDialog.ShowAsync();

                Frame.GoBack();
            }
        }
        /// <summary>
        /// Method to receive protocal invocation and process the arguments.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(e.Parameter.ToString());

            try
            {
                bool IsJson  = false;
                var  content = decoder.GetFirstValueByName("content");
                var  isjson  = decoder.GetFirstValueByName("isjson");

                if (!string.IsNullOrEmpty(isjson))
                {
                    IsJson = Convert.ToBoolean(isjson);
                }

                if (!string.IsNullOrEmpty(content))
                {
                    if (IsJson)
                    {
                        dynamic data = JObject.Parse(content);
                        txtContent.Text = data.Name;
                    }
                    else
                    {
                        txtContent.Text = content;
                    }
                }
            }
            catch (Exception ex)
            {
                txtContent.Text = ex.Message;
            }
        }
Esempio n. 4
0
        private async Task ProcessToastNotificationActivation(string arguments, ValueSet userInput)
        {
            // Perform tasks
            if (arguments == ACTIVATION_WITH_ERROR)
            {
                await ShowErrorLog().ConfigureAwait(false);
            }
            else if (arguments == ACTIVATION_WITH_ERROR_COPY_LOG)
            {
                var error = await GetMostRecentErrorText();

                Services.Helpers.ClipboardHelper.CopyToClipboard(error);
            }
            else if (arguments == ACTIVATION_WITH_ERROR_OPEN_LOG)
            {
                await ShowErrorLogFolder();
            }
            else if (arguments.StartsWith("cache_cancel"))
            {
                var cacheManager = Container.Resolve <Models.Cache.VideoCacheManager>();

                var query  = arguments.Split('?')[1];
                var decode = new WwwFormUrlDecoder(query);

                var videoId = decode.GetFirstValueByName("id");
                var quality = (NicoVideoQuality)Enum.Parse(typeof(NicoVideoQuality), decode.GetFirstValueByName("quality"));

                await cacheManager.CancelCacheRequest(videoId, quality);
            }
        }
        private async Task <Token> GetAccessToken()
        {
            var token = new Token();

            var startUrl = Common.FormatAuthUrl(AuthorizationEndpointUrl, ResponseTypes.Token, ConsumerKey,
                                                WebUtility.UrlEncode(CallbackUrl), DisplayTypes.Popup);
            var startUri = new Uri(startUrl);
            var endUri   = new Uri(CallbackUrl);

            var webAuthenticationResult =
                await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync(
                    Windows.Security.Authentication.Web.WebAuthenticationOptions.None,
                    startUri,
                    endUri);

            switch (webAuthenticationResult.ResponseStatus)
            {
            case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
                var responseData = webAuthenticationResult.ResponseData;
                var responseUri  = new Uri(responseData);
                var decoder      = new WwwFormUrlDecoder(responseUri.Fragment.Replace("#", "?"));

                token.AccessToken  = decoder.GetFirstValueByName("access_token");
                token.RefreshToken = decoder.GetFirstValueByName("refresh_token");
                token.InstanceUrl  = WebUtility.UrlDecode(decoder.GetFirstValueByName("instance_url"));

                return(token);

            case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
                throw new Exception(webAuthenticationResult.ResponseErrorDetail.ToString());

            default:
                throw new Exception(webAuthenticationResult.ResponseData);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Retrieves an OAuth 2.0 token for a given Authentication ticket.
        /// </summary>
        /// <param name="httpClient">The <see cref="HttpClient"/> instance to use for this request.</param>
        /// <param name="authTicket">The Authentication Ticket to use for this request. Obtained by calling <see cref="GetAuthenticationTicket(HttpClient, PtcLoginParameters)"/>.</param>
        /// <returns></returns>
        private async Task <AccessToken> GetOAuthToken(string authTicket)
        {
            var requestData = new Dictionary <string, string>
            {
                { "client_id", "mobile-app_pokemon-go" },
                { "redirect_uri", "https://www.nianticlabs.com/pokemongo/error" },
                { "client_secret", "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR" },
                { "grant_type", "refresh_token" },
                { "code", authTicket }
            };

            var responseMessage = await HttpClient.PostAsync(Constants.LoginOauthUrl, new FormUrlEncodedContent(requestData)).ConfigureAwait(false);

            var responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(responseContent))
            {
                throw new Exception("Your login was OK, but we could not get an API Token.");
            }

            var decoder = new WwwFormUrlDecoder(responseContent);

            if (decoder.Count == 0)
            {
                throw new Exception("Your login was OK, but we could not get an API Token.");
            }

            return(new AccessToken
            {
                Username = this.Username,
                Token = decoder.GetFirstValueByName("access_token"),
                ExpiresUtc = DateTime.UtcNow.AddSeconds(int.Parse(decoder.GetFirstValueByName("expires"))),
                AuthType = AuthType.Ptc
            });
        }
Esempio n. 7
0
        private async Task ProcessCommand(WwwFormUrlDecoder querybag, IOutputStream outstream)
        {
            try
            {
                string botCmd = querybag.GetFirstValueByName("cmd").ToLowerInvariant(); // Throws System.ArgumentException if not found
                switch (botCmd)
                {
                case "arm":
                {
                    fc.Arm();
                    await WriteResponseAsync("200 OK", successMsg, outstream);

                    break;
                }

                case "disarm":
                {
                    fc.Disarm();
                    await WriteResponseAsync("200 OK", successMsg, outstream);

                    break;
                }

                case "takeoff":
                {
                    await fc.takeoff();
                    await WriteResponseAsync("200 OK", successMsg, outstream);

                    break;
                }

                case "flyheight":
                {
                    UInt32 height = UInt32.Parse(querybag.GetFirstValueByName("height"));         // in cm!
                    fc.flyToHeight(height);
                    await WriteResponseAsync("200 OK", successMsg, outstream);

                    break;
                }

                default:
                {
                    await WriteResponseAsync("400 Bad Request", string.Format("UNSUPPORTED COMMAND: {0}", botCmd), outstream);

                    break;
                }
                }

                lastCommand = botCmd;
            }
            catch (ArgumentException)
            {
                await WriteResponseAsync("400 Bad Request", "INVALID QUERY STRING", outstream);
            }
            catch (Exception e)
            {
                await WriteResponseAsync("500 Internal Server Error", e.Message + e.StackTrace, outstream);
            }
        }
Esempio n. 8
0
        private async void Authenticate()
        {
            var SpotifyUrl = $"https://accounts.google.com/o/oauth2/auth?client_id={this.clientId}&redirect_uri={Uri.EscapeDataString(this.redirectURI)}&response_type=code&scope={Uri.EscapeDataString(this.scope)}";
            var StartUri   = new Uri(SpotifyUrl);
            var EndUri     = new Uri(redirectURI);

            WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);

            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var decoder = new WwwFormUrlDecoder(new Uri(WebAuthenticationResult.ResponseData).Query);
                if (decoder[0].Name != "code")
                {
                    System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {decoder.GetFirstValueByName("error")}.");
                    return;
                }

                var autorizationCode = decoder.GetFirstValueByName("code");

                var pairs = new Dictionary <string, string>();
                pairs.Add("code", autorizationCode);
                pairs.Add("client_id", this.clientId);
                pairs.Add("client_secret", this.clientSecret);
                pairs.Add("redirect_uri", this.redirectURI);
                pairs.Add("grant_type", "authorization_code");

                var formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);

                var client = new Windows.Web.Http.HttpClient();
                var httpResponseMessage = await client.PostAsync(new Uri("https://www.googleapis.com/oauth2/v4/token"), formContent);

                if (!httpResponseMessage.IsSuccessStatusCode)
                {
                    System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {httpResponseMessage.StatusCode}.");
                    return;
                }

                string jsonString = await httpResponseMessage.Content.ReadAsStringAsync();

                var jsonObject  = Windows.Data.Json.JsonObject.Parse(jsonString);
                var accessToken = jsonObject["access_token"].GetString();
                this.accessToken = accessToken;

                this.gotAccessToken = true;

                this.GMailServices = new GmailServices(this.accessToken);
                this.GMailServices.LatestEmailsEvent += (sender, status) => { this.LatestEmailsEvent?.Invoke(this, status); };

                this.CalendarServices = new CalendarServices(this.accessToken);
                this.CalendarServices.LatestCalendarEvent += (sender, status) => { this.LatestCalendarEvent?.Invoke(this, status); };
            }
        }
Esempio n. 9
0
        // launch by protocol
        protected override void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);
            if (args.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs protocolArgs = (ProtocolActivatedEventArgs)args;
                WwwFormUrlDecoder          decoder      = new WwwFormUrlDecoder(protocolArgs.Uri.Query);
                string s_port = decoder.GetFirstValueByName("port");
                int.TryParse(s_port, out int port);
                Controller.Connect(port);

                Frame rootFrame = Window.Current.Content as Frame;
                if (rootFrame == null)
                {
                    rootFrame = new Frame();
                    rootFrame.NavigationFailed += OnNavigationFailed;
                    Window.Current.Content      = rootFrame;
                }
                if (rootFrame.Content == null)
                {
                    rootFrame.Navigate(typeof(MainPage));
                }
            }
            Window.Current.Activate();
        }
Esempio n. 10
0
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            if (args is ProtocolActivatedEventArgs pArgs)
            {
                if (!string.IsNullOrWhiteSpace(pArgs.Uri.Query))
                {
                    try
                    {
                        var parsedQuery = new WwwFormUrlDecoder(pArgs.Uri.Query);
                        if (parsedQuery.Count > 0)
                        {
                            var chatUrl = parsedQuery.GetFirstValueByName("chatflow");
                            Utils.APISettings.Values["API"] = chatUrl;
                            MainPageViewModel.CurrentInstance?.StartChatting();
                        }
                    }
                    catch { }
                }
            }
            if (args is FileActivatedEventArgs fArgs && fArgs.Files.Count > 0)
            {
                var file = fArgs.Files[0] as StorageFile;
                Utils.APISettings.Values["JSON"] = await FileIO.ReadTextAsync(file);

                MainPageViewModel.CurrentInstance?.StartChatting();
            }
            // long-running startup tasks go here
            await Utils.LoadConfig();

            NavigationService.Navigate(typeof(Views.MainPage));
            await Task.CompletedTask;
        }
Esempio n. 11
0
        /// <summary>
        /// Performs the first step in the OAuth2 workflow and retreives the auth code
        /// </summary>
        /// <param name="authCodeUri">The box api uri to retrieve the auth code. BoxConfig.AuthCodeUri should be used for this field</param>
        /// <param name="redirectUri">The redirect uri that the page will navigate to after granting the auth code</param>
        /// <returns></returns>
        public static async Task <string> GetAuthCode(Uri authCodeUri, Uri redirectUri = null)
        {
            Uri callbackUri = redirectUri == null?
                              WebAuthenticationBroker.GetCurrentApplicationCallbackUri() :
                                  redirectUri;

            WebAuthenticationResult war = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                authCodeUri,
                callbackUri);

            switch (war.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                // grab auth code
                var response = war.ResponseData;
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(new Uri(response).Query);
                return(decoder.GetFirstValueByName("code"));

            case WebAuthenticationStatus.UserCancel:
                throw new Exception("User Canceled Login");

            case WebAuthenticationStatus.ErrorHttp:
            default:
                throw new Exception("Error returned by GetAuthCode() : " + war.ResponseStatus.ToString());
            }
        }
Esempio n. 12
0
        public async Task AuthenticateAsync()
        {
            var clientId             = "MTcpOsELm-U8sw";
            var authenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri("https://www.reddit.com/api/v1/authorize?client_id=" + clientId + "&response_type=code&state=RANDOM_STRING2&redirect_uri=http://localhost&duration=permanent&scope=identity,edit,flair,history,modconfig,modflair,modlog,modposts,modwiki,mysubreddits,privatemessages,read,report,save,submit,subscribe,vote,wikiedit,wikiread"), new Uri("http://localhost"));

            if (authenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                WwwFormUrlDecoder urlDecoder = new WwwFormUrlDecoder(new Uri(authenticationResult.ResponseData).Query);

                var codeString = urlDecoder.GetFirstValueByName("code");

                var postClient = new HttpClient();
                postClient.DefaultRequestHeaders.Authorization = CreateBasicHeader(clientId, "");

                HttpContent httpContent = new StringContent("grant_type=authorization_code&code=" + codeString + "&redirect_uri=http://localhost");
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                var responseMessage = await postClient.PostAsync(new Uri("https://ssl.reddit.com/api/v1/access_token"), httpContent);

                var responseContent = await responseMessage.Content.ReadAsStringAsync();

                var jsonResponse = JObject.Parse(responseContent);

                accessToken = jsonResponse["access_token"].ToString();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            }
        }
Esempio n. 13
0
        private async void BingTranslationReady(IAsyncResult ar)
        {
            // STEP 4: Process the translation
            // Get the request details
            HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
            // Get the response details
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);

            // Read the contents of the response into a string
            System.IO.Stream       streamResponse = response.GetResponseStream();
            System.IO.StreamReader streamRead     = new System.IO.StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();

            // Translator returns XML, so load it into an XDocument
            System.Xml.Linq.XDocument xTranslation =
                System.Xml.Linq.XDocument.Parse(responseString);
            string strTest = xTranslation.Root.FirstNode.ToString();
            // We're not on the UI thread, so use the dispatcher to update the UI
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                translationResult.Text    = strTest;
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(request.RequestUri.Query);
                Word w        = new Word();
                w.Text        = decoder.GetFirstValueByName("text");
                w.Learning    = true;
                Description d = new Description()
                {
                    Text = strTest
                };
                w.addDescription(d);
                App.ViewModel.addWord(w);
            });
        }
Esempio n. 14
0
        private async void FinalizeAuthorization(string url)
        {
            try
            {
                var urlDecoder = new WwwFormUrlDecoder(url.Substring(url.IndexOf('?') + 1));
                await Authorization.RetrieveAndSaveTokensFromAuthCode(urlDecoder.GetFirstValueByName("code"));

                WebViewHelper.Navigate(new Uri(urlDecoder.GetFirstValueByName("state")));
            }
            catch (Exception ex)
            {
                logger.Info("Authorization failed. " + ex.ToString());

                Authorize("https://open.spotify.com/", clearExisting: false);
            }
        }
Esempio n. 15
0
        private void OnNavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            this.ResetErrorView();
            this.LoadingState = true;

            var isSignOutWorkflow = GoogleDomainsHelper.IsSignOutWorkflow(args.Uri);

            if (_customHttpHeaderSet && !isSignOutWorkflow)
            {
                _customHttpHeaderSet = false;
                return;
            }

            args.Cancel = true;
            if (isSignOutWorkflow)
            {
                var queryParams = new WwwFormUrlDecoder(args.Uri.Query);
                var uri         = new Uri(queryParams.GetFirstValueByName("continue"));
                UriHelper.ClearCookiesFor(uri);
                this.ManageUri(uri);
            }
            else
            {
                this.ManageUri(args.Uri);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// This function extracts access_token from the response returned from web authentication broker
        /// and uses that token to get user information using facebook graph api.
        /// </summary>
        /// <param name="responseData">responseData returned from AuthenticateAsync result.</param>
        private async Task GetFacebookUserNameAsync(string responseData)
        {
            var decoder = new WwwFormUrlDecoder(responseData);
            var error   = decoder.TryGetValue("error");

            if (error != null)
            {
                FacebookUserName.Text = $"Error: {error}";
                return;
            }

            // You can store access token locally for further use.
            string access_token = decoder.GetFirstValueByName("access_token");
            string expires_in   = decoder.TryGetValue("expires_in"); // expires_in is optional

            HttpClient httpClient = new HttpClient();
            Uri        uri        = new Uri($"https://graph.facebook.com/me?access_token={Uri.EscapeDataString(access_token)}");

            try
            {
                string response = await httpClient.GetStringAsync(uri);

                JsonObject userInfo = JsonObject.Parse(response).GetObject();
                FacebookUserName.Text = userInfo.GetNamedString("name");
            }
            catch (Exception)
            {
                FacebookUserName.Text = "Error contacting Facebook";
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Обработчик перехода на страницу авторизации
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void WvAuthorization_LoginNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            wvAuthorization.Visibility = Visibility.Visible;
            if (string.IsNullOrEmpty(args.Uri.Fragment))
            {
                return;
            }

            var decoder = new WwwFormUrlDecoder(args.Uri.Fragment.Substring(1));

            App.VkSettings.AccessToken = decoder.GetFirstValueByName("access_token");
            App.VkSettings.UserId      = decoder.GetFirstValueByName("user_id");
            App.NavigationService.Navigate(typeof(MainView));

            wvAuthorization.NavigationCompleted -= WvAuthorization_LoginNavigationCompleted;
        }
Esempio n. 18
0
        public async Task ProcessRedirect(Uri url)
        {
            if (url.Host == "golf1052.com" && !url.Query.Contains("error=access_denied"))
            {
                var    decoded = new WwwFormUrlDecoder(url.Query);
                string code    = decoded.GetFirstValueByName("code");
                FormUrlEncodedContent tokenRequestContent = new FormUrlEncodedContent(new Dictionary <string, string>()
                {
                    { "grant_type", "authorization_code" },
                    { "code", code },
                    { "redirect_uri", Secrets.SpotifyRedirectUrl }
                });
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", GetEncodedAuth());
                HttpResponseMessage tokenResponseMessage = await httpClient.PostAsync("https://accounts.spotify.com/api/token", tokenRequestContent);

                try
                {
                    await SetupSpotifyToken(tokenResponseMessage);
                }
                catch
                {
                    Available = false;
                    throw;
                }
            }
            else
            {
                Available = false;
            }
        }
Esempio n. 19
0
        public async void NavigateWithConfig(string parameter)
        {
            try
            {
                var urlDecoder = new WwwFormUrlDecoder(parameter);
                var pageUrl    = urlDecoder.GetFirstValueByName("pageUrl");

                await WebViewHelper.NavigateToSpotifyUrl(pageUrl);

                var            autoplayEntry = urlDecoder.FirstOrDefault(x => x.Name == "autoplay");
                AutoPlayAction action        = AutoPlayAction.None;
                if (autoplayEntry != null)
                {
                    action = autoplayEntry.Value == "track" ? AutoPlayAction.Track : AutoPlayAction.Playlist;
                }

                if (action != AutoPlayAction.None)
                {
                    await WebViewHelper.AutoPlay(action);
                }

                return;
            }
            catch (Exception ex)
            {
                logger.Info($"Parsing input parameter {parameter} failed. {ex}");
            }
        }
Esempio n. 20
0
        private async void OauthBrowser_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            if (OauthViewer.Visibility == Visibility.Collapsed)
            {
                return;
            }


            OauthProgress.Visibility = Visibility.Collapsed;
            if (!args.IsSuccess)
            {
                MessageDialog dlg = new MessageDialog(args.WebErrorStatus.ToString() + ": " + args.Uri.AbsoluteUri);
                await dlg.ShowAsync();

                ShowOauthPanel(false);
                return;
            }

            if (string.IsNullOrWhiteSpace(args.Uri.Query))
            {
                return;
            }

            string code = string.Empty;

            try
            {
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args.Uri.Query);
                if (ListProviders.SelectedIndex == OauthProvider.GoogleProvider)
                {
                    code = decoder.GetFirstValueByName("approvalCode");
                }
                else
                {
                    code = decoder.GetFirstValueByName("code");
                }
            }
            catch { }

            if (string.IsNullOrWhiteSpace(code))
            {
                return;
            }

            _oauthWrapper.AuthorizationCode = code;
            ShowOauthPanel(false);
        }
Esempio n. 21
0
        public Login()
        {
            this.InitializeComponent();
            Window.Current.SetTitleBar(TitleBarElement);
            Window.Current.Activated        += OnWindowFocusChange;
            Window.Current.SizeChanged      += OnWindowSizeChanged;
            LoginWebview.Height              = Window.Current.Bounds.Height * 0.8;
            WebviewPopup.VerticalOffset      = -(LoginWebview.Height / 2);
            LoginWebview.NavigationStarting += async(view, args) =>
            {
                // Clearing challenge
                if (args.Uri.PathAndQuery == "/" || string.IsNullOrEmpty(args.Uri.PathAndQuery))
                {
                    WebviewPopup.IsOpen = false;
                }

                // Facebook OAuth Login
                if (args.Uri.PathAndQuery.Contains("accounts/signup", StringComparison.OrdinalIgnoreCase))
                {
                    // Uri looks like this: https://www.instagram.com/accounts/signup/?#access_token=...
                    WebviewPopup.IsOpen     = false;
                    FbLoginButton.IsEnabled = false;
                    try
                    {
                        var query     = args.Uri.Fragment.Substring(1); // turn fragment into query (remove the '#')
                        var urlParams = new WwwFormUrlDecoder(query);
                        var fbToken   = urlParams.GetFirstValueByName("access_token");
                        if (string.IsNullOrEmpty(fbToken))
                        {
                            await ShowLoginErrorDialog("Failed to acquire access token");

                            FbLoginButton.IsEnabled = true;
                            return;
                        }

                        var result = await _viewModel.LoginWithFacebook(fbToken).ConfigureAwait(true);

                        if (!result.IsSucceeded)
                        {
                            await ShowLoginErrorDialog(result.Message);

                            FbLoginButton.IsEnabled = true;
                            return;
                        }

                        Frame.Navigate(typeof(MainPage));
                    }
                    catch (Exception e)
                    {
                        await ShowLoginErrorDialog(
                            "Unexpected error occured while logging in with Facebook. Please try again later or log in with Instagram account instead.");

#if !DEBUG
                        Crashes.TrackError(e);
#endif
                    }
                }
            };
        }
Esempio n. 22
0
        public void Test_BuildUri_1()
        {
            Dictionary <string, string> queryPairs = new Dictionary <string, string>
            {
                { "type", "CHAT" },
                { "msgId", "[email protected]_SOME_MESSAGE_ID" },
            };
            Uri result = UriUtils.buildUri("*****@*****.**", queryPairs);

            Assert.IsTrue(result.Scheme.Equals(UriUtils.URI_SCHEME));
            Assert.IsTrue(UriUtils.getBareJidFromUri(result).Equals("*****@*****.**"));

            WwwFormUrlDecoder decoder = UriUtils.parseUriQuery(result);

            Assert.AreEqual(decoder.GetFirstValueByName("type"), "CHAT");
            Assert.AreEqual(decoder.GetFirstValueByName("msgId"), "[email protected]_SOME_MESSAGE_ID");
        }
Esempio n. 23
0
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            if (e.Kind == ActivationKind.Protocol)
            {
//#pragma warning disable UWP003 // UWP-only
//                await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
//#pragma warning restore UWP003 // UWP-only
                ProtocolActivatedEventArgs protocolArgs = (ProtocolActivatedEventArgs)e;
                Uri uri = protocolArgs.Uri;
                if (uri.Scheme == "live.wallpaper.store")
                {
                    if (!string.IsNullOrEmpty(uri.Query))
                    {
                        WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query);
                        if (decoder.Count > 0)
                        {
                            string host = null, wallpaperDir = null;
                            try
                            {
                                host         = decoder.GetFirstValueByName("host");
                                wallpaperDir = decoder.GetFirstValueByName("wallpaper");
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine(ex);
                            }
                            //var setting = new SettingObject
                            //{
                            //    //Server = new ServerSetting
                            //    //{
                            //    //    ServerUrl = host
                            //    //},
                            //    //General = new GeneralSetting()
                            //    //{
                            //    //    WallpaperSaveDir = wallpaperDir
                            //    //}
                            //};
                            //await ApplicationData.Current.LocalSettings.SaveAsync("config", setting);
                        }
                    }

                    await ActivationService.ActivateAsync(e);
                }
            }
        }
Esempio n. 24
0
        private async Task LoadReportAsync()
        {
            if (Uri.TryCreate(EmbedUrl, UriKind.Absolute, out Uri embedUri))
            {
                string token = await GetUserTokenAsync();

                if (!string.IsNullOrEmpty(token) &&
                    embedUri.Query.IndexOf("reportid", StringComparison.OrdinalIgnoreCase) != -1 &&
                    embedUri.Query.IndexOf("groupid", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    var tokenCredentials = new TokenCredentials(token, "Bearer");

                    using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                    {
                        var    decoder  = new WwwFormUrlDecoder(embedUri.Query.ToLower());
                        string groupId  = decoder.GetFirstValueByName("groupid");
                        string reportId = decoder.GetFirstValueByName("reportid");

                        Report report = await client.Reports.GetReportAsync(groupId, reportId);

                        if (report != null)
                        {
                            InvokeScriptAsync($"loadGroups(" +
                                              $"'{token}', " +
                                              $"{JsonConvert.SerializeObject(new Report[] { report })}, " +
                                              $"{JsonConvert.SerializeObject(report)}, " +
                                              (IsWindowsPhone ? $"'{DisplayInformation.CurrentOrientation.ToString()}'," : "'', ") +
                                              $"{ShowFilter.ToString().ToLower()}" +
                                              ")");

                            return;
                        }
                    }
                }

                ClearReport();
            }
            else
            {
                throw new ArgumentException(nameof(EmbedUrl));
            }
        }
Esempio n. 25
0
 public static int GetInt32(this WwwFormUrlDecoder query, string key)
 {
     try
     {
         return(query.GetFirstValueByName(key).QueryValueAsInt32());
     }
     catch (ArgumentException)
     {
         return(0);
     }
 }
Esempio n. 26
0
        private async void ShowPopup(string parameter)
        {
            WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(parameter);

            Debug.WriteLine(decoder.GetFirstValueByName("num"));
            Debug.WriteLine(decoder.GetFirstValueByName("offset"));
            var menu = new PopupMenu();

            menu.Commands.Add(new UICommand("Citer", (command) =>
            {
                Debug.WriteLine("VM Open param=" + parameter);
            }));

            var chosenCommand = await menu.ShowAsync(new Point(100, Convert.ToDouble(decoder.GetFirstValueByName("offset")) + 44.0));

            if (chosenCommand == null)
            {
                Debug.WriteLine("VM Dismiss param=" + parameter);
            }
        }
Esempio n. 27
0
 public static string GetString(this WwwFormUrlDecoder query, string key)
 {
     try
     {
         return(query.GetFirstValueByName(key));
     }
     catch (ArgumentException)
     {
         return(null);
     }
 }
Esempio n. 28
0
 static string GetDecoderField(WwwFormUrlDecoder decoder, string key)
 {
     try
     {
         return(decoder.GetFirstValueByName(key));
     }
     catch (Exception)
     {
         return(String.Empty);
     }
 }
 private string GetValue(WwwFormUrlDecoder decoder, string key, string defaultValue = null)
 {
     try
     {
         return(decoder.GetFirstValueByName(key));
     }
     catch (ArgumentException)
     {
         return(defaultValue);
     }
 }
Esempio n. 30
0
 public static bool GetBoolean(this WwwFormUrlDecoder query, string key)
 {
     try
     {
         return(query.GetFirstValueByName(key).QueryValueAsBoolean());
     }
     catch (ArgumentException)
     {
         return(false);
     }
 }