AzureStorageBlobExtensions.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. using System.Threading.Tasks;
  2. using Azure.Storage;
  3. using Azure.Storage.Blobs;
  4. using Azure.Storage.Blobs.Models;
  5. using System;
  6. using System.IO;
  7. using Azure.Storage.Blobs.Specialized;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using Azure.Core;
  12. using Azure;
  13. using TEAMModelOS.SDK;
  14. using TEAMModelOS.SDK.Extension;
  15. using System.Text.Encodings.Web;
  16. using TEAMModelOS.SDK.Models.Table;
  17. using Microsoft.AspNetCore.Http;
  18. using TEAMModelOS.Models;
  19. using Microsoft.Azure.Cosmos;
  20. using static TEAMModelOS.SDK.CoreAPIHttpService;
  21. using Microsoft.Azure.Cosmos.Table;
  22. using Azure.Storage.Sas;
  23. using Microsoft.Extensions.Configuration;
  24. using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
  25. namespace TEAMModelOS.SDK.DI
  26. {
  27. public static class AzureStorageBlobExtensions
  28. {
  29. /// <summary>
  30. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  31. /// </summary>
  32. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  33. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  34. public static async Task<long?> GetBlobsSize(this BlobContainerClient client, string prefix = null)
  35. {
  36. long? size = 0;
  37. try
  38. {
  39. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  40. {
  41. if (item.Name.StartsWith("res/", StringComparison.OrdinalIgnoreCase) && item.Name.EndsWith(".htex", StringComparison.OrdinalIgnoreCase))
  42. { continue; }
  43. if (!prefix.Equals(item.Name))
  44. {
  45. //避免操作(1111) /1111/1111.json /1111111/11111.json
  46. if (!prefix.EndsWith("/"))
  47. {
  48. if (item.Name.StartsWith(prefix + "/"))
  49. {
  50. size += item.Properties.ContentLength;
  51. }
  52. }
  53. }
  54. else
  55. {
  56. size += item.Properties.ContentLength;
  57. }
  58. };
  59. return size;
  60. }
  61. catch
  62. {
  63. return size;
  64. }
  65. }
  66. public static async Task<List<string>> List(this BlobContainerClient client, string prefix = null) {
  67. try
  68. {
  69. List<string> items = new List<string>();
  70. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix)) {
  71. items.Add(item.Name);
  72. }
  73. return items;
  74. }
  75. catch
  76. {
  77. return null;
  78. }
  79. }
  80. /// <summary>
  81. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  82. /// </summary>
  83. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  84. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  85. public static async Task<(long?, Dictionary<string, double?>)> GetBlobsCatalogSize(this BlobContainerClient client, string prefix = null)
  86. {
  87. long? size = 0;
  88. Dictionary<string, double?> dict = new Dictionary<string, double?>();
  89. try
  90. {
  91. List<KeyValuePair<string, double?>> foderSize = new List<KeyValuePair<string, double?>>();
  92. await foreach (BlobItem item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  93. {
  94. var len = item.Properties.ContentLength;
  95. foderSize.Add(new KeyValuePair<string, double?>(item.Name.Split("/")[0], len));
  96. size += item.Properties.ContentLength;
  97. };
  98. foderSize.Select(x => new { x.Key, x.Value }).GroupBy(y=>y.Key).ToList().ForEach(g=> {
  99. var gpsize = g.Select(m => m.Value).Sum();
  100. dict[g.Key] = gpsize;
  101. });
  102. return (size, dict);
  103. }
  104. catch
  105. {
  106. return (size, dict);
  107. }
  108. }
  109. public class OptUrl
  110. {
  111. public string url { get; set; }
  112. public long size { get; set; }
  113. }
  114. /// <summary>
  115. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  116. /// </summary>
  117. /// <param name="urls">多个文件的连接/param>
  118. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  119. public static async Task<List<OptUrl>> GetBlobsSize(this BlobContainerClient client, List<string> urls)
  120. {
  121. List<OptUrl> optUrls = new List<OptUrl>();
  122. try
  123. {
  124. if (urls != null) {
  125. foreach (var url in urls)
  126. {
  127. OptUrl optUrl = new OptUrl { url = url, size = 0 };
  128. var eurl = System.Web.HttpUtility.UrlDecode(url, Encoding.UTF8);
  129. var blob = client.GetBlobClient(eurl);
  130. if (blob.Exists())
  131. {
  132. var props = await blob.GetPropertiesAsync();
  133. var size = props.Value.ContentLength;
  134. optUrl.size = size;
  135. }
  136. optUrls.Add(optUrl);
  137. }
  138. }
  139. return optUrls;
  140. }
  141. catch
  142. {
  143. return optUrls;
  144. }
  145. }
  146. /// <summary>
  147. ///prefixs多个文件或文件夹路径删除
  148. ///prefixs 或者按前缀文件夹删除
  149. ///
  150. /// </summary>
  151. /// <param name="prefix">篩選開頭名稱,Null代表容器</param>
  152. public static async Task<bool> DeleteBlobs(this BlobServiceClient client,DingDing _dingDing, string blobContainerName, List<string> prefixs )
  153. {
  154. if (!prefixs.IsNotEmpty()) return false;
  155. try
  156. {
  157. BlobContainerClient bcc = client.GetBlobContainerClient(blobContainerName.ToLower());
  158. BlobBatchClient bbc = client.GetBlobBatchClient();
  159. List<Uri> blobs = new List<Uri>();
  160. List<Task<Azure.Response<bool>>> list = new List<Task<Azure.Response<bool>>>();
  161. foreach (var prefix in prefixs) {
  162. string px = prefix;
  163. if (prefix.StartsWith("/")) {
  164. px= prefix.Substring(1);
  165. }
  166. //目录必须有两层以上,避免删除根目录所有的。
  167. var pxlen= px.Split("/");
  168. if (pxlen.Length >=2) {
  169. var items = bcc.GetBlobsAsync(BlobTraits.None, BlobStates.None, px);
  170. await foreach (var item in items)
  171. {
  172. var urib = new UriBuilder(bcc.Uri);
  173. if (!prefix.Equals(item.Name))
  174. {
  175. //避免操作(1111) /1111/1111.json /1111111/11111.json
  176. if (!prefix.EndsWith("/"))
  177. {
  178. if (item.Name.StartsWith(prefix + "/"))
  179. {
  180. string path = $"{urib.Uri.AbsoluteUri}/{item.Name}";
  181. list.Add(bcc.GetBlobClient(item.Name).DeleteIfExistsAsync());
  182. if (item.Name.StartsWith("res/") && item.Name.EndsWith("/index.json"))
  183. {
  184. list.Add(bcc.GetBlobClient($"{prefix}.htex").DeleteIfExistsAsync());
  185. list.Add(bcc.GetBlobClient($"{prefix}.HTEX").DeleteIfExistsAsync());
  186. }
  187. blobs.Add(new Uri(path));
  188. }
  189. }
  190. }
  191. else
  192. {
  193. string path = $"{urib.Uri.AbsoluteUri}/{item.Name}";
  194. list.Add(bcc.GetBlobClient(item.Name).DeleteIfExistsAsync());
  195. blobs.Add(new Uri(path));
  196. }
  197. };
  198. }
  199. }
  200. if (list.Count > 0) {
  201. if (list.Count <= 256)
  202. {
  203. await Task.WhenAll(list);
  204. }
  205. else
  206. {
  207. int pages = (list.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  208. for (int i = 0; i < pages; i++)
  209. {
  210. List<Task<Azure.Response<bool>>> lists = list.Skip((i) * 256).Take(256).ToList();
  211. await Task.WhenAll(lists);
  212. }
  213. }
  214. }
  215. return true;
  216. /*
  217. if (blobs.Count <= 256)
  218. {
  219. if (blobs.Count > 0) {
  220. try {
  221. ResponseMessage[] ass = await bbc.DeleteBlobsAsync(blobs);
  222. }
  223. catch (AggregateException ex)
  224. {
  225. //删除多个时会,如果其中一个文件不存在 或者其中一个删除失败会引发该异常
  226. return true;
  227. }
  228. catch (RequestFailedException ex)
  229. {
  230. await _dingDing.SendBotMsg($"/{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  231. return true;
  232. }
  233. catch (Exception ex)
  234. {
  235. return true;
  236. }
  237. }
  238. return true;
  239. }
  240. else
  241. {
  242. int pages = (blobs.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  243. for (int i = 0; i < pages; i++)
  244. {
  245. List<Uri> lists = blobs.Skip((i) * 256).Take(256).ToList();
  246. try { ResponseMessage[] ass = await bbc.DeleteBlobsAsync(lists); }
  247. catch (AggregateException ex)
  248. {
  249. //删除多个时会,如果其中一个文件不存在 或者其中一个删除失败会引发该异常
  250. return true;
  251. }
  252. catch (RequestFailedException ex)
  253. {
  254. return true;
  255. }
  256. catch (Exception ex)
  257. {
  258. return true;
  259. }
  260. }
  261. return true;
  262. }
  263. */
  264. }
  265. catch(Exception ex )
  266. {
  267. await _dingDing.SendBotMsg($"文件删除异常{ex.Message}\n{ex.StackTrace}{prefixs.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  268. return false;
  269. }
  270. }
  271. /// <summary>
  272. /// 保存操作记录
  273. /// </summary>
  274. /// <param name="azureStorage"></param>
  275. /// <param name="type"></param>
  276. /// <param name="msg"></param>
  277. /// <param name="dingDing"></param>
  278. /// <param name="scope"></param>
  279. /// <param name="bizId"></param>
  280. /// <param name="option"></param>
  281. /// <param name="httpContext"></param>
  282. /// <returns></returns>
  283. 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)
  284. {
  285. var table = azureStorage.GetCloudTableClient().GetTableReference("IESOptLog");
  286. OptLog log = new() { RowKey = Guid.NewGuid().ToString() };
  287. try
  288. {
  289. object id = null, school = null, name = null, website = null ;
  290. httpContext?.Items.TryGetValue("ID", out id);
  291. httpContext?.Items.TryGetValue("School", out school);
  292. httpContext?.Items.TryGetValue("Name", out name);
  293. httpContext?.Items.TryGetValue("Website", out website);
  294. log.tmdId = id != null ? $"{id}" : log.tmdId;
  295. log.name = name != null ? $"{name}" : log.name;
  296. string host = httpContext?.Request?.Host.Value;
  297. log.school = school != null ? $"{school}" : log.school;
  298. log.PartitionKey = type != null ? $"Log-{type}" : "Log-Default";
  299. log.RowKey = bizId != null ? bizId : log.RowKey;
  300. log.platform = website!=null? $"{website}" : "Default";
  301. log.msg = msg;
  302. log.type = type;
  303. log.scope = scope;
  304. host = !string.IsNullOrWhiteSpace($"{host}") ? $"{host}" : option?.Location != null ? $"{host}" : "Default";
  305. log.url =$"{host}{httpContext?.Request.Path}" ;
  306. if (!string.IsNullOrWhiteSpace(msg) && msg.Length > 256)
  307. {
  308. log.saveMod = 1;
  309. log.jsonfile = $"/0-public/optlog/{log.RowKey}-{log.PartitionKey}.json";
  310. await azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(log.ToJsonString(), "optlog", $"{log.RowKey}-{log.PartitionKey}.json");
  311. log.msg = null;
  312. await table.SaveOrUpdate<OptLog>(log);
  313. }
  314. else {
  315. await table.SaveOrUpdate<OptLog>(log);
  316. }
  317. }
  318. catch (Exception ex)
  319. {
  320. _ = dingDing.SendBotMsg($"日志保存失败:{ex.Message}\n{ex.StackTrace},,{log.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  321. }
  322. }
  323. /// <summary>
  324. /// 保存日志文件
  325. /// </summary>
  326. /// <param name="azureStorage"></param>
  327. /// <param name="type"></param>
  328. /// <param name="rootPath"></param>
  329. /// <param name="replaceData"></param>
  330. /// <param name="dingDing"></param>
  331. /// <param name="scope"></param>
  332. /// <param name="bizId"></param>
  333. /// <param name="option"></param>
  334. /// <param name="httpContext"></param>
  335. /// <returns></returns>
  336. public static async Task SaveLogLang(this AzureStorageFactory azureStorage, string type,string rootPath, Dictionary<string, object> replaceData, DingDing dingDing, string scope = null, string bizId = null, Option option = null, HttpContext httpContext = null)
  337. {
  338. string msg = FileWay.FileValue(rootPath, "zh-cn", type, replaceData);
  339. var table = azureStorage.GetCloudTableClient().GetTableReference("IESOptLog");
  340. OptLog log = new() { RowKey = Guid.NewGuid().ToString() };
  341. try
  342. {
  343. object id = null, school = null, name = null, website = null;
  344. httpContext?.Items.TryGetValue("ID", out id);
  345. httpContext?.Items.TryGetValue("School", out school);
  346. httpContext?.Items.TryGetValue("Name", out name);
  347. httpContext?.Items.TryGetValue("Website", out website);
  348. log.tmdId = id != null ? $"{id}" : log.tmdId;
  349. log.name = name != null ? $"{name}" : log.name;
  350. string host = httpContext?.Request?.Host.Value;
  351. log.school = school != null ? $"{school}" : log.school;
  352. log.PartitionKey = type != null ? $"Log-{type}" : "Log-Default";
  353. log.RowKey = bizId != null ? bizId : log.RowKey;
  354. log.platform = website != null ? $"{website}" : "Default";
  355. log.msg = msg;
  356. log.tmsg = FileWay.FileValue(rootPath, "zh-tw", type, replaceData);
  357. log.emsg = FileWay.FileValue(rootPath, "en-us", type, replaceData);
  358. log.type = type;
  359. log.scope = scope;
  360. host = !string.IsNullOrWhiteSpace($"{host}") ? $"{host}" : option?.Location != null ? $"{host}" : "Default";
  361. log.url = $"{host}{httpContext?.Request.Path}";
  362. if (!string.IsNullOrWhiteSpace(msg) && msg.Length > 256)
  363. {
  364. log.saveMod = 1;
  365. log.jsonfile = $"/0-public/optlog/{log.RowKey}-{log.PartitionKey}.json";
  366. await azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(log.ToJsonString(), "optlog", $"{log.RowKey}-{log.PartitionKey}.json");
  367. log.msg = null;
  368. await table.SaveOrUpdate<OptLog>(log);
  369. }
  370. else
  371. {
  372. await table.SaveOrUpdate<OptLog>(log);
  373. }
  374. }
  375. catch (Exception ex)
  376. {
  377. _ = dingDing.SendBotMsg($"日志保存失败:{ex.Message}\n{ex.StackTrace},,{log.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  378. }
  379. }
  380. /// <summary>
  381. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  382. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  383. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  384. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  385. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  386. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  387. /// 答案及学习活动上传的文件,学生基本信息关联
  388. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  389. /// </summary>
  390. /// <param name="name">容器名称</param>
  391. /// <param name="json">文件内容的流</param>
  392. /// <param name="folder">业务文件夹</param>
  393. /// <param name="fileName">文件名</param>
  394. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  395. /// <returns></returns>
  396. public static async Task<string> UploadFileByContainer(this BlobContainerClient blobContainer, string json, string root, string blobpath, bool contentTypeDefault = true)
  397. {
  398. // string groupName =folder;
  399. //BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  400. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  401. string content_type = "application/octet-stream";
  402. if (!contentTypeDefault)
  403. {
  404. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  405. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  406. if (!string.IsNullOrEmpty(contenttype))
  407. {
  408. content_type = contenttype;
  409. }
  410. }
  411. byte[] bytes = System.Text.Encoding.Default.GetBytes(json);
  412. Stream streamBlob = new MemoryStream(bytes);
  413. await blockBlob.UploadAsync(streamBlob, true);
  414. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  415. return blockBlob.Uri.ToString();
  416. }
  417. /// <summary>
  418. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  419. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  420. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  421. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  422. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  423. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  424. /// 答案及学习活动上传的文件,学生基本信息关联
  425. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  426. /// </summary>
  427. /// <param name="name">容器名称</param>
  428. /// <param name="stream">文件内容的流</param>
  429. /// <param name="folder">业务文件夹</param>
  430. /// <param name="fileName">文件名</param>
  431. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  432. /// <returns></returns>
  433. public static async Task<string> UploadFileByContainer(this BlobContainerClient blobContainer, Stream stream, string root, string blobpath, bool contentTypeDefault = true)
  434. {
  435. //BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  436. Uri url = blobContainer.Uri;
  437. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  438. string content_type = "application/octet-stream";
  439. if (!contentTypeDefault)
  440. {
  441. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  442. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  443. if (!string.IsNullOrEmpty(contenttype))
  444. {
  445. content_type = contenttype;
  446. }
  447. }
  448. await blockBlob.UploadAsync(stream, true);
  449. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  450. return blockBlob.Uri.ToString();
  451. }
  452. /// <summary>
  453. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  454. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  455. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  456. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  457. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  458. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  459. /// 答案及学习活动上传的文件,学生基本信息关联
  460. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  461. /// </summary>
  462. /// <param name="name">容器名称</param>
  463. /// <param name="stream">文件内容的流</param>
  464. /// <param name="folder">业务文件夹</param>
  465. /// <param name="fileName">文件名</param>
  466. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  467. /// <returns></returns>
  468. public static async Task<(string blobName, string url)> UploadFileByContainerBName(this BlobContainerClient blobContainer, Stream stream, string root, string blobpath, bool contentTypeDefault = true)
  469. {
  470. //BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  471. Uri url = blobContainer.Uri;
  472. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  473. string content_type = "application/octet-stream";
  474. if (!contentTypeDefault)
  475. {
  476. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  477. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  478. if (!string.IsNullOrEmpty(contenttype))
  479. {
  480. content_type = contenttype;
  481. }
  482. }
  483. await blockBlob.UploadAsync(stream, true);
  484. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  485. return (blockBlob.Name, blockBlob.Uri.ToString());
  486. }
  487. /// <summary>
  488. /// 取得Blob SAS (有效期預設一天)
  489. /// </summary>
  490. /// <param name="containerName">容器名稱</param>
  491. /// <param name="blobName"></param>
  492. /// <param name="blobSasPermissions"></param>
  493. /// <param name="name"></param>
  494. /// <returns></returns>
  495. public static BlobAuth GetBlobSasUriRead(this BlobContainerClient blobContainer, IConfiguration _configuration, string containerName, string blobName, string name = "Default")
  496. {
  497. try
  498. {
  499. var ConnectionString = name.Equals("Default") ? _configuration.GetSection("Azure:Storage:ConnectionString").Value : _configuration.GetSection("Azure:Storage:ConnectionString-Test").Value;
  500. var keys = ParseConnectionString(ConnectionString);
  501. var accountname = keys["AccountName"];
  502. var accountkey = keys["AccountKey"];
  503. var endpoint = keys["EndpointSuffix"];
  504. DateTimeOffset dateTime = DateTimeOffset.UtcNow.Add(new TimeSpan(365 * 99, 0, 15, 0));
  505. long time = dateTime.ToUnixTimeMilliseconds();
  506. var blobSasBuilder = new BlobSasBuilder
  507. {
  508. StartsOn = DateTimeOffset.UtcNow.Subtract(new TimeSpan(0, 15, 0)),
  509. ExpiresOn = dateTime,
  510. BlobContainerName = containerName.ToLower(),
  511. BlobName = blobName
  512. };
  513. blobSasBuilder.SetPermissions(BlobSasPermissions.Read);
  514. var sskc = new StorageSharedKeyCredential(accountname, accountkey);
  515. BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(sskc);
  516. UriBuilder fullUri = new UriBuilder()
  517. {
  518. Scheme = "https",
  519. Host = $"{accountname}.blob.{endpoint}",
  520. Path = $"{containerName.ToLower()}/{blobName}",
  521. Query = sasQueryParameters.ToString()
  522. };
  523. return new BlobAuth { url = fullUri.Uri.ToString(), sas = sasQueryParameters.ToString(), timeout = time };
  524. // return fullUri.Uri.ToString();
  525. }
  526. catch
  527. {
  528. return null;
  529. }
  530. }
  531. public static Dictionary<string, string> ParseConnectionString(string connectionString)
  532. {
  533. var d = new Dictionary<string, string>();
  534. foreach (var item in connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries))
  535. {
  536. var a = item.IndexOf('=');
  537. d.Add(item.Substring(0, a), item.Substring(a + 1));
  538. }
  539. return d;
  540. }
  541. /// <summary>
  542. /// BI保存操作记录
  543. /// </summary>
  544. /// <param name="azureStorage"></param>
  545. /// <param name="type"></param>
  546. /// <param name="msg"></param>
  547. /// <param name="dingDing"></param>
  548. /// <param name="scope"></param>
  549. /// <param name="option"></param>
  550. /// <param name="httpContext"></param>
  551. /// <returns></returns>
  552. 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)
  553. {
  554. var table = tableClient.GetTableReference("BIOptLog");
  555. BIOptLog biLog = new() { RowKey = Guid.NewGuid().ToString() };
  556. try
  557. {
  558. object id = null, name = null, ddid = null, ddname = null, website = null;
  559. httpContext?.Items.TryGetValue("ID", out id);
  560. httpContext?.Items.TryGetValue("Name", out name);
  561. httpContext?.Items.TryGetValue("DDId", out ddid);
  562. httpContext?.Items.TryGetValue("DDName", out ddname);
  563. httpContext?.Items.TryGetValue("Website", out website);
  564. string site = twebsite != null ? twebsite : $"{website}";
  565. biLog.tmdId = id != null ? $"{id}" : tid;
  566. biLog.name = name != null ? $"{name}" : tname;
  567. biLog.PartitionKey = type != null ? $"{site}-Log-{type}" : $"{site}-Log-Default";
  568. biLog.platform = site != null ? site : "Default";
  569. biLog.msg = msg;
  570. biLog.type = type;
  571. biLog.scope = scope;
  572. string host = httpContext?.Request?.Host.Value;
  573. host = !string.IsNullOrWhiteSpace($"{host}") ? $"{host}" : option?.Location != null ? $"{host}" : "Default";
  574. biLog.url = $"{host}{httpContext?.Request.Path}";
  575. if (!string.IsNullOrWhiteSpace(msg) && msg.Length > 255)
  576. {
  577. biLog.saveMod = 1;
  578. biLog.jsonfile = $"/0-public/BIOptLog/{biLog.PartitionKey}-{biLog.RowKey}.json";
  579. await UploadFileByContainer(blobContainer, biLog.ToJsonString(), "BIOptLog", $"{biLog.PartitionKey}-{biLog.RowKey}.json");
  580. biLog.msg = null;
  581. await table.SaveOrUpdate<BIOptLog>(biLog);
  582. }
  583. else await table.SaveOrUpdate<BIOptLog>(biLog);
  584. }
  585. catch (Exception ex)
  586. {
  587. _ = dingDing.SendBotMsg($"BI日志保存失败:{ex.Message}\n{ex.StackTrace},,{biLog.ToJsonString()}", GroupNames.成都开发測試群組);
  588. }
  589. }
  590. }
  591. }