private static Task <string> GetAutenficationCode(string clientId, CancellationToken cancellation) { return(PromptCodeFromBrowser.Show($"https://accounts.google.com/o/oauth2/v2/auth?scope={Uri.EscapeDataString(Scopes.JoinToString(' '))}&" + $"redirect_uri={RedirectUrl}&response_type=code&" + $"client_id={clientId}", new Regex(@"Success code=(\S+)", RegexOptions.Compiled), ToolsStrings.Uploader_EnterGoogleDriveAuthenticationCode, ToolsStrings.Uploader_GoogleDrive, cancellation: cancellation)); }
public static Task <OAuthCode> GetCode( string name, string requestUrl, [CanBeNull] string noRedirectUrl, string successCodeRegex = @"Success code=(\S+)", string redirectUrlKey = "redirect_uri", string responseError = "error", string responseCode = "code", string description = null, string title = null, CancellationToken cancellation = default(CancellationToken)) { var tcs = new TaskCompletionSource <OAuthCode>(); // Try to use web server and localhost to redirect WebServer server = null; var redirectUri = "http://localhost/" + SubUrl; async void DisposeLater() { await Task.Delay(2000); Logging.Debug("Stopping server…"); // ReSharper disable once AccessToModifiedClosure server?.Dispose(); server = null; } server = new WebServer("http://+:80/" + SubUrl, new Log(e => { tcs.TrySetException(e); DisposeLater(); }), Unosquare.Labs.EmbedIO.RoutingStrategy.Wildcard); if (server != null) { server.RegisterModule(new WebApiModule()); server.Module <WebApiModule>().RegisterController(() => new IndexPageController(responseError, responseCode, (e, s) => { if (e != null || s == null) { tcs.TrySetException(new Exception(e == null ? "Code is missing" : "Authentication went wrong: " + e)); } else { tcs.TrySetResult(new OAuthCode(false, s, redirectUri)); } DisposeLater(); })); cancellation.Register(() => { tcs.TrySetCanceled(); DisposeLater(); }); try { Logging.Debug($"Launching web-server on {SubUrl}…"); server.RunAsync(); var url = requestUrl + $"&{redirectUrlKey}={Uri.EscapeDataString(redirectUri)}"; #if DEBUG Logging.Debug(url); #endif WindowsHelper.ViewInBrowser(url); return(tcs.Task); } catch (Exception e) { Logging.Warning(e); } } DisposeLater(); description = description ?? ToolsStrings.Uploader_EnterGoogleDriveAuthenticationCode.Replace("Google Drive", name); title = title ?? ToolsStrings.Uploader_GoogleDrive.Replace("Google Drive", name); return(PromptCodeFromBrowser.Show(noRedirectUrl != null ? requestUrl + $"&{redirectUrlKey}={Uri.EscapeDataString(noRedirectUrl)}" : requestUrl, new Regex(successCodeRegex, RegexOptions.Compiled), description, title, cancellation: cancellation).ContinueWith(x => new OAuthCode(true, x.Result, noRedirectUrl))); }