AzureStorageBlobExtensions.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. using TEAMModelOS.SDK.Models.Table;
  21. using Microsoft.AspNetCore.Http;
  22. using TEAMModelOS.Models;
  23. namespace TEAMModelOS.SDK.DI
  24. {
  25. public static class AzureStorageBlobExtensions
  26. {
  27. /// <summary>
  28. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  29. /// </summary>
  30. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  31. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  32. public static async Task<long?> GetBlobsSize(this BlobContainerClient client, string prefix = null)
  33. {
  34. long? size = 0;
  35. try
  36. {
  37. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  38. {
  39. if (item.Name.StartsWith("res/", StringComparison.OrdinalIgnoreCase) && item.Name.EndsWith(".htex", StringComparison.OrdinalIgnoreCase))
  40. { continue; }
  41. if (!prefix.Equals(item.Name))
  42. {
  43. //避免操作(1111) /1111/1111.json /1111111/11111.json
  44. if (!prefix.EndsWith("/"))
  45. {
  46. if (item.Name.StartsWith(prefix + "/"))
  47. {
  48. size += item.Properties.ContentLength;
  49. }
  50. }
  51. }
  52. else
  53. {
  54. size += item.Properties.ContentLength;
  55. }
  56. };
  57. return size;
  58. }
  59. catch
  60. {
  61. return size;
  62. }
  63. }
  64. public static async Task<List<string>> List(this BlobContainerClient client, string prefix = null) {
  65. try
  66. {
  67. List<string> items = new List<string>();
  68. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix)) {
  69. items.Add(item.Name);
  70. }
  71. return items;
  72. }
  73. catch
  74. {
  75. return null;
  76. }
  77. }
  78. /// <summary>
  79. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  80. /// </summary>
  81. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  82. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  83. public static async Task<(long?, Dictionary<string, double?>)> GetBlobsCatalogSize(this BlobContainerClient client, string prefix = null)
  84. {
  85. long? size = 0;
  86. Dictionary<string, double?> dict = new Dictionary<string, double?>();
  87. try
  88. {
  89. List<KeyValuePair<string, double?>> foderSize = new List<KeyValuePair<string, double?>>();
  90. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  91. {
  92. var len = item.Properties.ContentLength;
  93. foderSize.Add(new KeyValuePair<string, double?>(item.Name.Split("/")[0], len));
  94. size += item.Properties.ContentLength;
  95. };
  96. foderSize.Select(x => new { x.Key, x.Value }).GroupBy(y=>y.Key).ToList().ForEach(g=> {
  97. var gpsize = g.Select(m => m.Value).Sum();
  98. dict[g.Key] = gpsize;
  99. });
  100. return (size, dict);
  101. }
  102. catch
  103. {
  104. return (size, dict);
  105. }
  106. }
  107. public class OptUrl
  108. {
  109. public string url { get; set; }
  110. public long size { get; set; }
  111. }
  112. /// <summary>
  113. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  114. /// </summary>
  115. /// <param name="urls">多个文件的连接/param>
  116. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  117. public static async Task<List<OptUrl>> GetBlobsSize(this BlobContainerClient client, List<string> urls)
  118. {
  119. List<OptUrl> optUrls = new List<OptUrl>();
  120. try
  121. {
  122. if (urls != null) {
  123. foreach (var url in urls)
  124. {
  125. OptUrl optUrl = new OptUrl { url = url, size = 0 };
  126. var eurl = System.Web.HttpUtility.UrlDecode(url, Encoding.UTF8);
  127. var blob = client.GetBlobClient(eurl);
  128. if (blob.Exists())
  129. {
  130. var props = await blob.GetPropertiesAsync();
  131. var size = props.Value.ContentLength;
  132. optUrl.size = size;
  133. }
  134. optUrls.Add(optUrl);
  135. }
  136. }
  137. return optUrls;
  138. }
  139. catch
  140. {
  141. return optUrls;
  142. }
  143. }
  144. /// <summary>
  145. ///prefixs多个文件或文件夹路径删除
  146. ///prefixs 或者按前缀文件夹删除
  147. ///
  148. /// </summary>
  149. /// <param name="prefix">篩選開頭名稱,Null代表容器</param>
  150. public static async Task<bool> DeleteBlobs(this BlobServiceClient client,DingDing _dingDing, string blobContainerName, List<string> prefixs )
  151. {
  152. if (!prefixs.IsNotEmpty()) return false;
  153. try
  154. {
  155. BlobContainerClient bcc = client.GetBlobContainerClient(blobContainerName);
  156. BlobBatchClient bbc = client.GetBlobBatchClient();
  157. List<Uri> blobs = new List<Uri>();
  158. List<Task<Azure.Response<bool>>> list = new List<Task<Response<bool>>>();
  159. foreach (var prefix in prefixs) {
  160. string px = prefix;
  161. if (prefix.StartsWith("/")) {
  162. px= prefix.Substring(1);
  163. }
  164. var items = bcc.GetBlobsAsync(BlobTraits.None, BlobStates.None, px);
  165. await foreach (var item in items)
  166. {
  167. var urib = new UriBuilder(bcc.Uri);
  168. if (!prefix.Equals(item.Name))
  169. {
  170. //避免操作(1111) /1111/1111.json /1111111/11111.json
  171. if (!prefix.EndsWith("/"))
  172. {
  173. if (item.Name.StartsWith(prefix+ "/")) {
  174. string path =$"{ urib.Uri.AbsoluteUri }/{ item.Name}";
  175. list.Add(bcc.GetBlobClient(item.Name).DeleteIfExistsAsync());
  176. if (item.Name.StartsWith("res/") && item.Name.EndsWith("/index.json")) {
  177. list.Add(bcc.GetBlobClient($"{prefix}.htex").DeleteIfExistsAsync());
  178. list.Add(bcc.GetBlobClient($"{prefix}.HTEX").DeleteIfExistsAsync());
  179. }
  180. blobs.Add(new Uri(path));
  181. }
  182. }
  183. }
  184. else {
  185. string path = $"{ urib.Uri.AbsoluteUri }/{ item.Name}";
  186. list.Add(bcc.GetBlobClient(item.Name).DeleteIfExistsAsync());
  187. blobs.Add(new Uri(path));
  188. }
  189. };
  190. }
  191. if (list.Count <= 256)
  192. {
  193. await Task.WhenAll(list);
  194. }
  195. else {
  196. int pages = (list.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  197. for (int i = 0; i < pages; i++)
  198. {
  199. List<Task<Azure.Response<bool>>> lists = list.Skip((i) * 256).Take(256).ToList();
  200. await Task.WhenAll(lists);
  201. }
  202. }
  203. return true;
  204. /*
  205. if (blobs.Count <= 256)
  206. {
  207. if (blobs.Count > 0) {
  208. try {
  209. Azure.Response[] ass = await bbc.DeleteBlobsAsync(blobs);
  210. }
  211. catch (AggregateException ex)
  212. {
  213. //删除多个时会,如果其中一个文件不存在 或者其中一个删除失败会引发该异常
  214. return true;
  215. }
  216. catch (RequestFailedException ex)
  217. {
  218. await _dingDing.SendBotMsg($"/{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  219. return true;
  220. }
  221. catch (Exception ex)
  222. {
  223. return true;
  224. }
  225. }
  226. return true;
  227. }
  228. else
  229. {
  230. int pages = (blobs.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  231. for (int i = 0; i < pages; i++)
  232. {
  233. List<Uri> lists = blobs.Skip((i) * 256).Take(256).ToList();
  234. try { Azure.Response[] ass = await bbc.DeleteBlobsAsync(lists); }
  235. catch (AggregateException ex)
  236. {
  237. //删除多个时会,如果其中一个文件不存在 或者其中一个删除失败会引发该异常
  238. return true;
  239. }
  240. catch (RequestFailedException ex)
  241. {
  242. return true;
  243. }
  244. catch (Exception ex)
  245. {
  246. return true;
  247. }
  248. }
  249. return true;
  250. }
  251. */
  252. }
  253. catch(Exception ex )
  254. {
  255. await _dingDing.SendBotMsg($"文件删除异常{ex.Message}\n{ex.StackTrace}{prefixs.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  256. return false;
  257. }
  258. }
  259. /// <summary>
  260. /// 保存操作记录
  261. /// </summary>
  262. /// <param name="azureStorage"></param>
  263. /// <param name="type"></param>
  264. /// <param name="msg"></param>
  265. /// <param name="dingDing"></param>
  266. /// <param name="scope"></param>
  267. /// <param name="bizId"></param>
  268. /// <param name="option"></param>
  269. /// <param name="httpContext"></param>
  270. /// <returns></returns>
  271. public static async Task SaveLog(this AzureStorageFactory azureStorage, string type, string msg,DingDing dingDing, string scope = null, string bizId = null, Option option = null, HttpContext httpContext = null)
  272. {
  273. var table = azureStorage.GetCloudTableClient().GetTableReference("OptLog");
  274. OptLog log = new() { RowKey = Guid.NewGuid().ToString() };
  275. try
  276. {
  277. object id = null, school = null, name = null, website = null ;
  278. httpContext?.Items.TryGetValue("ID", out id);
  279. httpContext?.Items.TryGetValue("School", out school);
  280. httpContext?.Items.TryGetValue("Name", out name);
  281. httpContext?.Items.TryGetValue("Website", out website);
  282. log.tmdId = id != null ? $"{id}" : log.tmdId;
  283. log.name = name != null ? $"{name}" : log.name;
  284. string host = httpContext?.Request?.Host.Value;
  285. log.school = school != null ? $"{school}" : log.school;
  286. log.PartitionKey = type != null ? $"Log-{type}" : "Log-Default";
  287. log.RowKey = bizId != null ? bizId : log.RowKey;
  288. log.platform = website!=null? $"{website}" : "Default";
  289. log.msg = msg;
  290. log.type = type;
  291. log.scope = scope;
  292. host = !string.IsNullOrWhiteSpace($"{host}") ? $"{host}" : option?.Location != null ? $"{host}" : "Default";
  293. log.url =$"{host}{httpContext?.Request.Path}" ;
  294. if (!string.IsNullOrWhiteSpace(msg) && msg.Length > 150)
  295. {
  296. log.saveMod = 1;
  297. log.jsonfile = $"/0-public/optlog/{log.RowKey}-{log.PartitionKey}.json";
  298. await azureStorage.UploadFileByContainer("0-public", log.ToJsonString(), "optlog", $"{log.RowKey}-{log.PartitionKey}.json");
  299. log.msg = null;
  300. await table.SaveOrUpdate<OptLog>(log);
  301. }
  302. else {
  303. await table.SaveOrUpdate<OptLog>(log);
  304. }
  305. }
  306. catch (Exception ex)
  307. {
  308. _ = dingDing.SendBotMsg($"日志保存失败:{ex.Message}\n{ex.StackTrace},,{log.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  309. }
  310. }
  311. /// <summary>
  312. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  313. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  314. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  315. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  316. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  317. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  318. /// 答案及学习活动上传的文件,学生基本信息关联
  319. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  320. /// </summary>
  321. /// <param name="name">容器名称</param>
  322. /// <param name="json">文件内容的流</param>
  323. /// <param name="folder">业务文件夹</param>
  324. /// <param name="fileName">文件名</param>
  325. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  326. /// <returns></returns>
  327. public static async Task<string> UploadFileByContainer(this AzureStorageFactory azureStorage, string name, string json, string root , string blobpath, bool contentTypeDefault = true)
  328. {
  329. // string groupName =folder;
  330. BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  331. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  332. string content_type = "application/octet-stream";
  333. if (!contentTypeDefault)
  334. {
  335. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  336. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  337. if (!string.IsNullOrEmpty(contenttype))
  338. {
  339. content_type = contenttype;
  340. }
  341. }
  342. byte[] bytes = System.Text.Encoding.Default.GetBytes(json);
  343. Stream streamBlob = new MemoryStream(bytes);
  344. await blockBlob.UploadAsync(streamBlob, true);
  345. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  346. return blockBlob.Uri.ToString();
  347. }
  348. /// <summary>
  349. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  350. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  351. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  352. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  353. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  354. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  355. /// 答案及学习活动上传的文件,学生基本信息关联
  356. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  357. /// </summary>
  358. /// <param name="name">容器名称</param>
  359. /// <param name="stream">文件内容的流</param>
  360. /// <param name="folder">业务文件夹</param>
  361. /// <param name="fileName">文件名</param>
  362. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  363. /// <returns></returns>
  364. public static async Task<string> UploadFileByContainer(this AzureStorageFactory azureStorage, string name, Stream stream, string root, string blobpath, bool contentTypeDefault = true)
  365. {
  366. BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  367. Uri url = blobContainer.Uri;
  368. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  369. string content_type = "application/octet-stream";
  370. if (!contentTypeDefault)
  371. {
  372. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  373. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  374. if (!string.IsNullOrEmpty(contenttype))
  375. {
  376. content_type = contenttype;
  377. }
  378. }
  379. await blockBlob.UploadAsync(stream, true);
  380. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  381. return blockBlob.Uri.ToString();
  382. }
  383. /// <summary>
  384. /// BI保存操作记录
  385. /// </summary>
  386. /// <param name="azureStorage"></param>
  387. /// <param name="type"></param>
  388. /// <param name="msg"></param>
  389. /// <param name="dingDing"></param>
  390. /// <param name="scope"></param>
  391. /// <param name="option"></param>
  392. /// <param name="httpContext"></param>
  393. /// <returns></returns>
  394. public static async Task SaveBILog(this AzureStorageFactory azureStorage, string type, string msg, DingDing dingDing, string tid = null, string tname = null, string twebsite = null, string scope = null, Option option = null, HttpContext httpContext = null)
  395. {
  396. var table = azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  397. BIOptLog biLog = new() { RowKey = Guid.NewGuid().ToString() };
  398. try
  399. {
  400. object id = null, name = null, ddid = null, ddname = null, website = null;
  401. httpContext?.Items.TryGetValue("ID", out id);
  402. httpContext?.Items.TryGetValue("Name", out name);
  403. httpContext?.Items.TryGetValue("DDId", out ddid);
  404. httpContext?.Items.TryGetValue("DDName", out ddname);
  405. httpContext?.Items.TryGetValue("Website", out website);
  406. string site = twebsite != null ? twebsite : $"{website}";
  407. biLog.tmdId = id != null ? $"{id}" : tid;
  408. biLog.name = name != null ? $"{name}" : tname;
  409. biLog.PartitionKey = type != null ? $"{site}-Log-{type}" : $"{site}-Log-Default";
  410. biLog.platform = site != null ? site : "Default";
  411. biLog.msg = msg;
  412. biLog.type = type;
  413. biLog.scope = scope;
  414. string host = httpContext?.Request?.Host.Value;
  415. host = !string.IsNullOrWhiteSpace($"{host}") ? $"{host}" : option?.Location != null ? $"{host}" : "Default";
  416. biLog.url = $"{host}{httpContext?.Request.Path}";
  417. if (!string.IsNullOrWhiteSpace(msg) && msg.Length > 255)
  418. {
  419. biLog.saveMod = 1;
  420. biLog.jsonfile = $"/0-public/BIOptLog/{biLog.PartitionKey}-{biLog.RowKey}.json";
  421. await azureStorage.UploadFileByContainer("0-public", biLog.ToJsonString(), "BIOptLog", $"{biLog.PartitionKey}-{biLog.RowKey}.json");
  422. biLog.msg = null;
  423. await table.SaveOrUpdate<BIOptLog>(biLog);
  424. }
  425. else await table.SaveOrUpdate<BIOptLog>(biLog);
  426. }
  427. catch (Exception ex)
  428. {
  429. _ = dingDing.SendBotMsg($"BI日志保存失败:{ex.Message}\n{ex.StackTrace},,{biLog.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  430. }
  431. }
  432. }
  433. }