DropbBoxUserItem.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using Dropbox.Api;
  2. using Dropbox.Api.Files;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. namespace PDF_Office.ViewModels.HomePanel.CloudDrive
  12. {
  13. public class DropbBoxUserItem
  14. {
  15. DropboxClient client;
  16. // This loopback host is for demo purpose. If this port is not
  17. // available on your machine you need to update this URL with an unused port.
  18. public static readonly string LoopbackHost = "http://127.0.0.1:8080/";
  19. // Add an ApiKey (from https://www.dropbox.com/developers/apps) here
  20. public static readonly string ApiKey = "k1hv3601odbsmln";
  21. // URL to receive OAuth 2 redirect from Dropbox server.
  22. // You also need to register this redirect URL on https://www.dropbox.com/developers/apps.
  23. public readonly Uri RedirectUri = new Uri(LoopbackHost + "authorize");
  24. // URL to receive access token from JS.
  25. public readonly Uri JSRedirectUri = new Uri(LoopbackHost + "token");
  26. private string currentFolder = "";
  27. HttpListener http = new HttpListener();
  28. private async void Connect()
  29. {
  30. DropboxCertHelper.InitializeCertPinning();
  31. var state = Guid.NewGuid().ToString("N");
  32. var OAuthflow = new PKCEOAuthFlow();
  33. var authorizeUri = OAuthflow.GetAuthorizeUri(OAuthResponseType.Code, ApiKey, RedirectUri.ToString(), state: state, tokenAccessType: TokenAccessType.Offline, scopeList: null, includeGrantedScopes: IncludeGrantedScopes.None);
  34. //var http = new HttpListener();
  35. http.Prefixes.Clear();
  36. http.Prefixes.Add(LoopbackHost);
  37. http.Start();
  38. System.Diagnostics.Process.Start(authorizeUri.ToString());
  39. await HandleOAuth2Redirect(http);
  40. // Handle redirect from JS and process OAuth response.
  41. var redirectUri = await HandleJSRedirect(http);
  42. var tokenResult = await OAuthflow.ProcessCodeFlowAsync(redirectUri, ApiKey, RedirectUri.ToString(), state);
  43. // Window.GetWindow(this).Activate();
  44. DropboxClientConfig dropboxClientConfig = new DropboxClientConfig("ControlTest");
  45. client = new DropboxClient(tokenResult.AccessToken, dropboxClientConfig);
  46. RefreshList();
  47. }
  48. public static void ListenerCallback(IAsyncResult result)
  49. {
  50. HttpListener listener = (HttpListener)result.AsyncState;
  51. // Call EndGetContext to complete the asynchronous operation.
  52. HttpListenerContext context = listener.EndGetContext(result);
  53. HttpListenerRequest request = context.Request;
  54. // Obtain a response object.
  55. HttpListenerResponse response = context.Response;
  56. // Construct a response.
  57. string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
  58. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
  59. // Get a response stream and write the response to it.
  60. response.ContentLength64 = buffer.Length;
  61. System.IO.Stream output = response.OutputStream;
  62. output.Write(buffer, 0, buffer.Length);
  63. // You must close the output stream.
  64. output.Close();
  65. }
  66. public async void RefreshList(string path = "")
  67. {
  68. var files = await client.Files.ListFolderAsync(path);
  69. // ItemList.ItemsSource = files.Entries;
  70. }
  71. /// <summary>
  72. /// Handles the redirect from Dropbox server. Because we are using token flow, the local
  73. /// http server cannot directly receive the URL fragment. We need to return a HTML page with
  74. /// inline JS which can send URL fragment to local server as URL parameter.
  75. /// </summary>
  76. /// <param name="http">The http listener.</param>
  77. /// <returns>The <see cref="Task"/></returns>
  78. private async Task HandleOAuth2Redirect(HttpListener http)
  79. {
  80. var context = await http.GetContextAsync();
  81. // We only care about request to RedirectUri endpoint.
  82. while (context.Request.Url.AbsolutePath != RedirectUri.AbsolutePath)
  83. {
  84. context = await http.GetContextAsync();
  85. }
  86. context.Response.ContentType = "text/html";
  87. // Respond with a page which runs JS and sends URL fragment as query string
  88. // to TokenRedirectUri.
  89. using (var file = System.IO.File.OpenRead("index.html"))
  90. {
  91. file.CopyTo(context.Response.OutputStream);
  92. }
  93. context.Response.OutputStream.Close();
  94. }
  95. /// <summary>
  96. /// Handle the redirect from JS and process raw redirect URI with fragment to
  97. /// complete the authorization flow.
  98. /// </summary>
  99. /// <param name="http">The http listener.</param>
  100. /// <returns>The <see cref="OAuth2Response"/></returns>
  101. private async Task<Uri> HandleJSRedirect(HttpListener http)
  102. {
  103. var context = await http.GetContextAsync();
  104. // We only care about request to TokenRedirectUri endpoint.
  105. while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
  106. {
  107. context = await http.GetContextAsync();
  108. }
  109. var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]);
  110. return redirectUri;
  111. }
  112. private void Download()
  113. {
  114. //if (ItemList.SelectedItem != null)
  115. //{
  116. // var item = ItemList.SelectedItem as Metadata;
  117. // if (item.IsFolder)
  118. // return;
  119. // SaveFileDialog saveFileDialog = new SaveFileDialog();
  120. // saveFileDialog.FileName = item.Name;
  121. // if ((bool)saveFileDialog.ShowDialog())
  122. // {
  123. // string folder = item.PathDisplay.Replace("/" + item.Name, "");
  124. // using (var response = await client.Files.DownloadAsync(item.PathDisplay))
  125. // {
  126. // var result = await response.GetContentAsStreamAsync();
  127. // var stream = StreamToMemoryStream(result);
  128. // using (var fileStream = System.IO.File.Create(saveFileDialog.FileName))
  129. // {
  130. // stream.Seek(0, System.IO.SeekOrigin.Begin);
  131. // stream.CopyTo(fileStream);
  132. // }
  133. // }
  134. // MessageBox.Show("下载完成");
  135. // System.Diagnostics.Process.Start(@"explorer.exe", "/select,\"" + saveFileDialog.FileName + "\"");
  136. // RefreshList(folder);
  137. // }
  138. //}
  139. }
  140. public MemoryStream StreamToMemoryStream(Stream stream)
  141. {
  142. MemoryStream memoryStream = new MemoryStream();
  143. //将基础流写入内存流
  144. const int bufferLength = 1024;
  145. byte[] buffer = new byte[bufferLength];
  146. int actual = stream.Read(buffer, 0, bufferLength);
  147. while (actual > 0)
  148. {
  149. // 读、写过程中,流的位置会自动走。
  150. memoryStream.Write(buffer, 0, actual);
  151. actual = stream.Read(buffer, 0, bufferLength);
  152. }
  153. memoryStream.Position = 0;
  154. return memoryStream;
  155. }
  156. private void Upload()
  157. {
  158. //if (ItemList.SelectedItem != null)
  159. //{
  160. // var item = ItemList.SelectedItem as Metadata;
  161. // if (item.IsFolder)
  162. // return;
  163. //OpenFileDialog openFileDialog = new OpenFileDialog();
  164. //if ((bool)openFileDialog.ShowDialog())
  165. //{
  166. // string folder = currentFolder; /*= item.PathDisplay.Replace("/" + item.Name, "");*/
  167. // using (var stream = System.IO.File.OpenRead(openFileDialog.FileName))
  168. // {
  169. // await client.Files.UploadAsync(folder + "/" + openFileDialog.SafeFileName, WriteMode.Overwrite.Instance, body: stream);
  170. // }
  171. // MessageBox.Show("上传完成");
  172. // RefreshList(folder);
  173. //}
  174. //}
  175. }
  176. private void Loaded()
  177. {
  178. //var text = sender as TextBlock;
  179. //if (text == null)
  180. // return;
  181. //if (text.DataContext is Metadata)
  182. //{
  183. // var data = (text.DataContext as Metadata);
  184. // if (data.IsFile)
  185. // {
  186. // text.Text = "File";
  187. // }
  188. // if (data.IsFolder)
  189. // {
  190. // text.Text = "Folder";
  191. // }
  192. //}
  193. }
  194. }
  195. }