AzureStorageBlobExtensions.cs 14 KB

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