DropbBoxUserItem.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using Dropbox.Api;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. namespace PDF_Office.ViewModels.HomePanel.CloudDrive
  10. {
  11. public class DropbBoxUserItem
  12. {
  13. DropboxClient client;
  14. // This loopback host is for demo purpose. If this port is not
  15. // available on your machine you need to update this URL with an unused port.
  16. public static readonly string LoopbackHost = "http://127.0.0.1:8080/";
  17. // Add an ApiKey (from https://www.dropbox.com/developers/apps) here
  18. public static readonly string ApiKey = "k1hv3601odbsmln";
  19. // URL to receive OAuth 2 redirect from Dropbox server.
  20. // You also need to register this redirect URL on https://www.dropbox.com/developers/apps.
  21. public readonly Uri RedirectUri = new Uri(LoopbackHost + "authorize");
  22. // URL to receive access token from JS.
  23. public readonly Uri JSRedirectUri = new Uri(LoopbackHost + "token");
  24. private string currentFolder = "";
  25. HttpListener http = new HttpListener();
  26. private async void btnConnect_Click()
  27. {
  28. DropboxCertHelper.InitializeCertPinning();
  29. var state = Guid.NewGuid().ToString("N");
  30. var OAuthflow = new PKCEOAuthFlow();
  31. var authorizeUri = OAuthflow.GetAuthorizeUri(OAuthResponseType.Code, ApiKey, RedirectUri.ToString(), state: state, tokenAccessType: TokenAccessType.Offline, scopeList: null, includeGrantedScopes: IncludeGrantedScopes.None);
  32. //var http = new HttpListener();
  33. http.Prefixes.Clear();
  34. http.Prefixes.Add(LoopbackHost);
  35. http.Start();
  36. // IAsyncResult result = http.BeginGetContext(new AsyncCallback(ListenerCallback), http);
  37. System.Diagnostics.Process.Start(authorizeUri.ToString());
  38. await HandleOAuth2Redirect(http);
  39. // Handle redirect from JS and process OAuth response.
  40. var redirectUri = await HandleJSRedirect(http);
  41. var tokenResult = await OAuthflow.ProcessCodeFlowAsync(redirectUri, ApiKey, RedirectUri.ToString(), state);
  42. // Window.GetWindow(this).Activate();
  43. DropboxClientConfig dropboxClientConfig = new DropboxClientConfig("ControlTest");
  44. client = new DropboxClient(tokenResult.AccessToken, dropboxClientConfig);
  45. RefreshList();
  46. }
  47. public static void ListenerCallback(IAsyncResult result)
  48. {
  49. HttpListener listener = (HttpListener)result.AsyncState;
  50. // Call EndGetContext to complete the asynchronous operation.
  51. HttpListenerContext context = listener.EndGetContext(result);
  52. HttpListenerRequest request = context.Request;
  53. // Obtain a response object.
  54. HttpListenerResponse response = context.Response;
  55. // Construct a response.
  56. string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
  57. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
  58. // Get a response stream and write the response to it.
  59. response.ContentLength64 = buffer.Length;
  60. System.IO.Stream output = response.OutputStream;
  61. output.Write(buffer, 0, buffer.Length);
  62. // You must close the output stream.
  63. output.Close();
  64. }
  65. public async void RefreshList(string path = "")
  66. {
  67. var files = await client.Files.ListFolderAsync(path);
  68. // ItemList.ItemsSource = files.Entries;
  69. }
  70. /// <summary>
  71. /// Handles the redirect from Dropbox server. Because we are using token flow, the local
  72. /// http server cannot directly receive the URL fragment. We need to return a HTML page with
  73. /// inline JS which can send URL fragment to local server as URL parameter.
  74. /// </summary>
  75. /// <param name="http">The http listener.</param>
  76. /// <returns>The <see cref="Task"/></returns>
  77. private async Task HandleOAuth2Redirect(HttpListener http)
  78. {
  79. var context = await http.GetContextAsync();
  80. // We only care about request to RedirectUri endpoint.
  81. while (context.Request.Url.AbsolutePath != RedirectUri.AbsolutePath)
  82. {
  83. context = await http.GetContextAsync();
  84. }
  85. context.Response.ContentType = "text/html";
  86. // Respond with a page which runs JS and sends URL fragment as query string
  87. // to TokenRedirectUri.
  88. using (var file = System.IO.File.OpenRead("index.html"))
  89. {
  90. file.CopyTo(context.Response.OutputStream);
  91. }
  92. context.Response.OutputStream.Close();
  93. }
  94. /// <summary>
  95. /// Handle the redirect from JS and process raw redirect URI with fragment to
  96. /// complete the authorization flow.
  97. /// </summary>
  98. /// <param name="http">The http listener.</param>
  99. /// <returns>The <see cref="OAuth2Response"/></returns>
  100. private async Task<Uri> HandleJSRedirect(HttpListener http)
  101. {
  102. var context = await http.GetContextAsync();
  103. // We only care about request to TokenRedirectUri endpoint.
  104. while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
  105. {
  106. context = await http.GetContextAsync();
  107. }
  108. var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]);
  109. return redirectUri;
  110. }
  111. }
  112. }