AzureStorageBlobExtensions.cs 22 KB

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