AzureStorageBlobExtensions.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using System.Threading.Tasks;
  2. using Azure.Storage;
  3. using Azure.Storage.Blobs;
  4. using Azure.Storage.Blobs.Models;
  5. using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
  6. using TEAMModelOS.SDK.Module.AzureBlob.Container;
  7. using TEAMModelOS.SDK.Helper.Security.ShaHash;
  8. using System;
  9. using System.IO;
  10. using Azure.Storage.Blobs.Specialized;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using Azure.Core;
  15. using Azure;
  16. using TEAMModelOS.SDK;
  17. using TEAMModelOS.SDK.Extension;
  18. using HTEXLib.COMM.Helpers;
  19. using System.Text.Encodings.Web;
  20. namespace TEAMModelOS.SDK.DI
  21. {
  22. public static class AzureStorageBlobExtensions
  23. {
  24. /// <summary>
  25. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  26. /// </summary>
  27. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  28. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  29. public static async Task<long?> GetBlobsSize(this BlobContainerClient client, string prefix = null)
  30. {
  31. long? size = 0;
  32. try
  33. {
  34. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  35. {
  36. if (item.Name.StartsWith("res/", StringComparison.OrdinalIgnoreCase) && item.Name.EndsWith(".htex", StringComparison.OrdinalIgnoreCase))
  37. { continue; }
  38. if (!prefix.Equals(item.Name))
  39. {
  40. //避免操作(1111) /1111/1111.json /1111111/11111.json
  41. if (!prefix.EndsWith("/"))
  42. {
  43. if (item.Name.StartsWith(prefix + "/"))
  44. {
  45. size += item.Properties.ContentLength;
  46. }
  47. }
  48. }
  49. else
  50. {
  51. size += item.Properties.ContentLength;
  52. }
  53. };
  54. return size;
  55. }
  56. catch
  57. {
  58. return size;
  59. }
  60. }
  61. public static async Task<List<string>> List(this BlobContainerClient client, string prefix = null) {
  62. try
  63. {
  64. List<string> items = new List<string>();
  65. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix)) {
  66. items.Add(item.Name);
  67. }
  68. return items;
  69. }
  70. catch
  71. {
  72. return null;
  73. }
  74. }
  75. /// <summary>
  76. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  77. /// </summary>
  78. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  79. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  80. public static async Task<(long?, Dictionary<string, double?>)> GetBlobsCatalogSize(this BlobContainerClient client, string prefix = null)
  81. {
  82. long? size = 0;
  83. Dictionary<string, double?> dict = new Dictionary<string, double?>();
  84. try
  85. {
  86. List<KeyValuePair<string, double?>> foderSize = new List<KeyValuePair<string, double?>>();
  87. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  88. {
  89. var len = item.Properties.ContentLength;
  90. foderSize.Add(new KeyValuePair<string, double?>(item.Name.Split("/")[0], len));
  91. size += item.Properties.ContentLength;
  92. };
  93. foderSize.Select(x => new { x.Key, x.Value }).GroupBy(y=>y.Key).ToList().ForEach(g=> {
  94. var gpsize = g.Select(m => m.Value).Sum();
  95. dict[g.Key] = gpsize;
  96. });
  97. return (size, dict);
  98. }
  99. catch
  100. {
  101. return (size, dict);
  102. }
  103. }
  104. public class OptUrl
  105. {
  106. public string url { get; set; }
  107. public long size { get; set; }
  108. }
  109. /// <summary>
  110. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  111. /// </summary>
  112. /// <param name="urls">多个文件的连接/param>
  113. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  114. public static async Task<List<OptUrl>> GetBlobsSize(this BlobContainerClient client, List<string> urls)
  115. {
  116. List<OptUrl> optUrls = new List<OptUrl>();
  117. try
  118. {
  119. if (urls != null) {
  120. foreach (var url in urls)
  121. {
  122. OptUrl optUrl = new OptUrl { url = url, size = 0 };
  123. var eurl = System.Web.HttpUtility.UrlDecode(url, Encoding.UTF8);
  124. var blob = client.GetBlobClient(eurl);
  125. if (blob.Exists())
  126. {
  127. var props = await blob.GetPropertiesAsync();
  128. var size = props.Value.ContentLength;
  129. optUrl.size = size;
  130. }
  131. optUrls.Add(optUrl);
  132. }
  133. }
  134. return optUrls;
  135. }
  136. catch
  137. {
  138. return optUrls;
  139. }
  140. }
  141. /// <summary>
  142. ///prefixs多个文件或文件夹路径删除
  143. ///prefixs 或者按前缀文件夹删除
  144. ///
  145. /// </summary>
  146. /// <param name="prefix">篩選開頭名稱,Null代表容器</param>
  147. public static async Task<bool> DeleteBlobs(this BlobServiceClient client,DingDing _dingDing, string blobContainerName, List<string> prefixs )
  148. {
  149. if (!prefixs.IsNotEmpty()) return false;
  150. try
  151. {
  152. BlobContainerClient bcc = client.GetBlobContainerClient(blobContainerName);
  153. BlobBatchClient bbc = client.GetBlobBatchClient();
  154. List<Uri> blobs = new List<Uri>();
  155. List<Task<Azure.Response<bool>>> list = new List<Task<Response<bool>>>();
  156. foreach (var prefix in prefixs) {
  157. string px = prefix;
  158. if (prefix.StartsWith("/")) {
  159. px= prefix.Substring(1);
  160. }
  161. var items = bcc.GetBlobsAsync(BlobTraits.None, BlobStates.None, px);
  162. await foreach (var item in items)
  163. {
  164. var urib = new UriBuilder(bcc.Uri);
  165. if (!prefix.Equals(item.Name))
  166. {
  167. //避免操作(1111) /1111/1111.json /1111111/11111.json
  168. if (!prefix.EndsWith("/"))
  169. {
  170. if (item.Name.StartsWith(prefix+ "/")) {
  171. string path =$"{ urib.Uri.AbsoluteUri }/{ item.Name}";
  172. list.Add(bcc.GetBlobClient(item.Name).DeleteIfExistsAsync());
  173. if (item.Name.StartsWith("res/") && item.Name.EndsWith("/index.json")) {
  174. list.Add(bcc.GetBlobClient($"{prefix}.htex").DeleteIfExistsAsync());
  175. list.Add(bcc.GetBlobClient($"{prefix}.HTEX").DeleteIfExistsAsync());
  176. }
  177. blobs.Add(new Uri(path));
  178. }
  179. }
  180. }
  181. else {
  182. string path = $"{ urib.Uri.AbsoluteUri }/{ item.Name}";
  183. list.Add(bcc.GetBlobClient(item.Name).DeleteIfExistsAsync());
  184. blobs.Add(new Uri(path));
  185. }
  186. };
  187. }
  188. if (list.Count <= 256)
  189. {
  190. await Task.WhenAll(list);
  191. }
  192. else {
  193. int pages = (list.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  194. for (int i = 0; i < pages; i++)
  195. {
  196. List<Task<Azure.Response<bool>>> lists = list.Skip((i) * 256).Take(256).ToList();
  197. await Task.WhenAll(lists);
  198. }
  199. }
  200. return true;
  201. /*
  202. if (blobs.Count <= 256)
  203. {
  204. if (blobs.Count > 0) {
  205. try {
  206. Azure.Response[] ass = await bbc.DeleteBlobsAsync(blobs);
  207. }
  208. catch (AggregateException ex)
  209. {
  210. //删除多个时会,如果其中一个文件不存在 或者其中一个删除失败会引发该异常
  211. return true;
  212. }
  213. catch (RequestFailedException ex)
  214. {
  215. await _dingDing.SendBotMsg($"{ex.StackTrace}/{ex.Message}", GroupNames.醍摩豆服務運維群組);
  216. return true;
  217. }
  218. catch (Exception ex)
  219. {
  220. return true;
  221. }
  222. }
  223. return true;
  224. }
  225. else
  226. {
  227. int pages = (blobs.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  228. for (int i = 0; i < pages; i++)
  229. {
  230. List<Uri> lists = blobs.Skip((i) * 256).Take(256).ToList();
  231. try { Azure.Response[] ass = await bbc.DeleteBlobsAsync(lists); }
  232. catch (AggregateException ex)
  233. {
  234. //删除多个时会,如果其中一个文件不存在 或者其中一个删除失败会引发该异常
  235. return true;
  236. }
  237. catch (RequestFailedException ex)
  238. {
  239. return true;
  240. }
  241. catch (Exception ex)
  242. {
  243. return true;
  244. }
  245. }
  246. return true;
  247. }
  248. */
  249. }
  250. catch(Exception ex )
  251. {
  252. await _dingDing.SendBotMsg($"文件删除异常{ex.Message}{ex.StackTrace}{prefixs.ToJsonString()}", GroupNames.成都开发測試群組);
  253. return false;
  254. }
  255. }
  256. /// <summary>
  257. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  258. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  259. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  260. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  261. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  262. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  263. /// 答案及学习活动上传的文件,学生基本信息关联
  264. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  265. /// </summary>
  266. /// <param name="name">容器名称</param>
  267. /// <param name="json">文件内容的流</param>
  268. /// <param name="folder">业务文件夹</param>
  269. /// <param name="fileName">文件名</param>
  270. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  271. /// <returns></returns>
  272. public static async Task<string> UploadFileByContainer(this AzureStorageFactory azureStorage, string name, string json, string root , string blobpath, bool contentTypeDefault = true)
  273. {
  274. // string groupName =folder;
  275. BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  276. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  277. string content_type = "application/octet-stream";
  278. if (!contentTypeDefault)
  279. {
  280. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  281. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  282. if (!string.IsNullOrEmpty(contenttype))
  283. {
  284. content_type = contenttype;
  285. }
  286. }
  287. byte[] bytes = System.Text.Encoding.Default.GetBytes(json);
  288. Stream streamBlob = new MemoryStream(bytes);
  289. await blockBlob.UploadAsync(streamBlob, true);
  290. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  291. return blockBlob.Uri.ToString();
  292. }
  293. /// <summary>
  294. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  295. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  296. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  297. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  298. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  299. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  300. /// 答案及学习活动上传的文件,学生基本信息关联
  301. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  302. /// </summary>
  303. /// <param name="name">容器名称</param>
  304. /// <param name="stream">文件内容的流</param>
  305. /// <param name="folder">业务文件夹</param>
  306. /// <param name="fileName">文件名</param>
  307. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  308. /// <returns></returns>
  309. public static async Task<string> UploadFileByContainer(this AzureStorageFactory azureStorage, string name, Stream stream, string root, string blobpath, bool contentTypeDefault = true)
  310. {
  311. BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  312. Uri url = blobContainer.Uri;
  313. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  314. string content_type = "application/octet-stream";
  315. if (!contentTypeDefault)
  316. {
  317. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  318. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  319. if (!string.IsNullOrEmpty(contenttype))
  320. {
  321. content_type = contenttype;
  322. }
  323. }
  324. await blockBlob.UploadAsync(stream, true);
  325. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  326. return blockBlob.Uri.ToString();
  327. }
  328. }
  329. }