GoogleDriveUserItem.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using Google.Apis.Auth.OAuth2;
  2. using Google.Apis.Download;
  3. using Google.Apis.Drive.v3;
  4. using Google.Apis.Services;
  5. using Google.Apis.Util.Store;
  6. using PDF_Office.Model.CloudDrive;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace PDF_Office.ViewModels.HomePanel.CloudDrive
  15. {
  16. /// <summary>
  17. /// 对单账号处理的核心功能类
  18. /// </summary>
  19. public class GoogleDriveUserItem
  20. {
  21. public GoogleDriveUser User { get; set; }
  22. public DriveService Service { get; set; }
  23. private List<GoogleDriveFiles> GoogleDriveFilesList = new List<GoogleDriveFiles>();
  24. public GoogleDriveUserItem()
  25. {
  26. User = new GoogleDriveUser();
  27. }
  28. #region 对用户账号处理
  29. public async Task<bool> RemoveUser()
  30. {
  31. bool result = false;
  32. if (User.CurrentCredential != null)
  33. {
  34. result = await User.CurrentCredential.RevokeTokenAsync(CancellationToken.None);
  35. }
  36. if (result == true)
  37. User.CurrentCredential = null;
  38. return result;
  39. }
  40. /// <summary>
  41. /// 获取帐号
  42. /// </summary>
  43. /// <returns>返回用户帐号地址</returns>
  44. private async Task<string> GetUserAcount()
  45. {
  46. string userAcount = "";
  47. if (Service != null)
  48. {
  49. var about = Service.About.Get();
  50. about.Fields = "user";
  51. var uss = about.Execute().User;
  52. userAcount = uss.EmailAddress;
  53. }
  54. return userAcount;
  55. }
  56. /// <summary>
  57. /// 获取帐号
  58. /// </summary>
  59. /// <returns>返回用户帐号地址</returns>
  60. public async Task<string> GetUserAcountAsync()
  61. {
  62. return await GetUserAcount();
  63. }
  64. #endregion
  65. #region 文件夹
  66. #endregion
  67. #region 文件
  68. /// <summary>
  69. /// 对单个用户,获取文件列表
  70. /// </summary>
  71. public async Task<List<GoogleDriveFiles>> GetDriveFiles(DriveService service = null)
  72. {
  73. if (service == null)
  74. return null;
  75. // define parameters of request.
  76. FilesResource.ListRequest FileListRequest = service.Files.List();
  77. //listRequest.PageSize = 10;
  78. //listRequest.PageToken = 10;
  79. FileListRequest.Fields = "nextPageToken, files(id, name, size, version, createdTime)";
  80. //get file list.
  81. IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
  82. List<GoogleDriveFiles> FileList = new List<GoogleDriveFiles>();
  83. if (files != null && files.Count > 0)
  84. {
  85. foreach (var file in files)
  86. {
  87. GoogleDriveFiles File = new GoogleDriveFiles
  88. {
  89. Id = file.Id,
  90. Name = file.Name,
  91. Size = file.Size,
  92. Version = file.Version,
  93. CreatedTime = file.CreatedTime
  94. };
  95. FileList.Add(File);
  96. }
  97. }
  98. return FileList;
  99. }
  100. /// <summary>
  101. /// 上传文件
  102. /// </summary>
  103. /// <param name="filepath">本地文件路径</param>
  104. public async Task<bool> FileUpload(string filepath)
  105. {
  106. if (Service == null)
  107. return false;
  108. var FileMetaData = new Google.Apis.Drive.v3.Data.File();
  109. var str = filepath.LastIndexOf("\\");
  110. var str2 = filepath.Substring(str + 1, filepath.Length - str - 1);
  111. FileMetaData.Name = str2;
  112. FileMetaData.MimeType = "";
  113. FilesResource.CreateMediaUpload request;
  114. try
  115. {
  116. using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open))
  117. {
  118. request = Service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
  119. request.Fields = "id";
  120. request.Upload();
  121. }
  122. return true;
  123. }
  124. catch
  125. {
  126. return false;
  127. }
  128. }
  129. /// <summary>
  130. /// Download file from Google Drive by fileId.
  131. /// </summary>
  132. /// <param name="googleDriveFiles"></param>
  133. /// <param name="savePath"></param>
  134. /// <returns></returns>
  135. //
  136. public async Task<string> DownloadGoogleFile(GoogleDriveFiles googleDriveFiles, string savePath)
  137. {
  138. if (Service == null)
  139. return "";
  140. string fileId = googleDriveFiles.Id;
  141. if (string.IsNullOrEmpty(fileId))
  142. return "";
  143. //fileId = DriveFiles[0].Id;
  144. FilesResource.GetRequest request = Service.Files.Get(fileId);
  145. string FileName = request.Execute().Name;
  146. string FilePath = System.IO.Path.Combine(savePath, FileName);
  147. MemoryStream stream = new MemoryStream();
  148. // Add a handler which will be notified on progress changes.
  149. // It will notify on each chunk download and when the
  150. // download is completed or failed.
  151. request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
  152. {
  153. switch (progress.Status)
  154. {
  155. case DownloadStatus.Downloading:
  156. {
  157. Console.WriteLine(progress.BytesDownloaded);
  158. break;
  159. }
  160. case DownloadStatus.Completed:
  161. {
  162. Console.WriteLine("Download complete.");
  163. SaveStream(stream, FilePath);
  164. break;
  165. }
  166. case DownloadStatus.Failed:
  167. {
  168. Console.WriteLine("Download failed.");
  169. break;
  170. }
  171. }
  172. };
  173. request.Download(stream);
  174. if (string.IsNullOrEmpty(savePath) == false)
  175. {
  176. }
  177. return FilePath;
  178. }
  179. private static void SaveStream(MemoryStream stream, string FilePath)
  180. {
  181. using (System.IO.FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
  182. {
  183. stream.WriteTo(file);
  184. }
  185. }
  186. #endregion
  187. }
  188. public static class GoogleDriveStatic
  189. {
  190. public static string[] Scopes = { DriveService.Scope.Drive };
  191. //Google Drive应用名称
  192. private static readonly string GoogleDriveAppName = "PDF Office";
  193. //请求应用进行身份验证的信息
  194. public static string CredentialsPath { get; private set; }
  195. //存放已通过身份验证的用户信息,以便下次不用登录便可使用云文档
  196. public static string FilesPathTemp { get; private set; }
  197. /// <summary>
  198. /// 异步获取Google服务的包信息,避免UI线程卡死
  199. /// </summary>
  200. /// <param name="userInfoFile"></param>
  201. [Obsolete]
  202. public static async Task<Tuple<DriveService, UserCredential>> GetServiceAsync(string userInfoFile = "")
  203. {
  204. Tuple<DriveService, UserCredential> tuple = null;
  205. await Task.Run(() =>
  206. {
  207. tuple = GetService(userInfoFile);
  208. });
  209. return tuple;
  210. }
  211. /// <summary>
  212. /// 获取Google服务的包信息(包含访问令牌,App Key密钥等)
  213. /// </summary>
  214. /// <param name="FilePath">登录过的用户文件;若为空,则为新用户登录</param>
  215. /// <returns></returns>
  216. [Obsolete]
  217. public static Tuple<DriveService, UserCredential> GetService(string FilePath = "")
  218. {
  219. Tuple<DriveService, UserCredential> tuple = null;
  220. UserCredential credential;
  221. if (FilePath == "")
  222. {
  223. var time = DateTime.Now.ToString("yyyyMMddHHmmss");
  224. FilePath = System.IO.Path.Combine(FilesPathTemp, time + ".json");
  225. }
  226. using (var stream = new FileStream(CredentialsPath, FileMode.Open, FileAccess.Read))
  227. {
  228. credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
  229. GoogleClientSecrets.Load(stream).Secrets,
  230. Scopes,
  231. "user",
  232. CancellationToken.None,
  233. new FileDataStore(FilePath, true)).Result;
  234. }
  235. //create Drive API service.
  236. DriveService service = new DriveService(new BaseClientService.Initializer()
  237. {
  238. HttpClientInitializer = credential,
  239. ApplicationName = GoogleDriveAppName
  240. });
  241. return tuple = new Tuple<DriveService, UserCredential>(service, credential);
  242. }
  243. /// <summary>
  244. /// 获取登录过的账号
  245. /// </summary>
  246. /// <returns>历史账号</returns>
  247. public static async Task<List<Tuple<DriveService, UserCredential>>> GetHistoryService()
  248. {
  249. DirectoryInfo TheFolder = new DirectoryInfo(FilesPathTemp);
  250. List<Tuple<DriveService, UserCredential>> DriveServices = new List<Tuple<DriveService, UserCredential>>();
  251. foreach (var directorieItem in TheFolder.GetDirectories())
  252. {
  253. var driveServiceItem = await GetServiceAsync(directorieItem.Name);
  254. if (driveServiceItem != null)
  255. {
  256. DriveServices.Add(driveServiceItem);
  257. }
  258. }
  259. return DriveServices;
  260. }
  261. #region 云文档的用户帐户缓存路径和身份验证文件
  262. /// <summary>
  263. /// 获取或创建缓存登录帐户信息
  264. /// </summary>
  265. public static string GetFilesPathTemp()
  266. {
  267. string str_1 = System.AppDomain.CurrentDomain.BaseDirectory;
  268. String FolderPath = str_1 + "GoogleDriveUsers";
  269. if (Directory.Exists(FolderPath) == false)
  270. Directory.CreateDirectory(FolderPath);
  271. FilesPathTemp = FolderPath;
  272. return FolderPath;
  273. }
  274. /// <summary>
  275. /// 获取本地身份验证文件
  276. /// </summary>
  277. public static string GetCredentialsPath()
  278. {
  279. string str_1 = System.AppDomain.CurrentDomain.BaseDirectory;
  280. String filePath = str_1 + @"\credentials.json";
  281. CredentialsPath = filePath;
  282. return filePath;
  283. }
  284. #endregion
  285. }
  286. }