BlobService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using Azure;
  2. using Azure.Cosmos;
  3. using Azure.Messaging.ServiceBus;
  4. using Azure.Storage.Blobs;
  5. using DocumentFormat.OpenXml.Wordprocessing;
  6. using HTEXLib.COMM.Helpers;
  7. using Microsoft.Extensions.Configuration;
  8. using StackExchange.Redis;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Text.Json;
  14. using System.Threading.Tasks;
  15. using TEAMModelOS.Models;
  16. using TEAMModelOS.SDK.DI;
  17. using TEAMModelOS.SDK.Extension;
  18. using TEAMModelOS.SDK.Models;
  19. namespace TEAMModelOS.SDK.Services
  20. {
  21. public static class BlobService
  22. {
  23. public static async Task RefreshBlobRoot(BlobRefreshMessage message, AzureServiceBusFactory _serviceBus,IConfiguration _configuration,AzureRedisFactory _azureRedis) {
  24. if (!string.IsNullOrWhiteSpace(message.root) && !string.IsNullOrWhiteSpace(message.name)) {
  25. string lockKey = $"Blob:Lock:{message.name}:{message.root}";
  26. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  27. //不存在Blob:Lock:hbcn:video 文件夹在队列中 则加入队列
  28. if (!exist)
  29. {
  30. //保持一天的时间
  31. TimeSpan timeSpan = new TimeSpan(1,0,0);
  32. //加入队列的时间
  33. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  34. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  35. var messageBlob = new ServiceBusMessage(message.ToJsonString());
  36. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  37. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  38. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  39. }
  40. //如果已经存在,则忽略,不加入队列。
  41. }
  42. }
  43. /// <summary>
  44. /// 获取学校或者个人的剩余空间
  45. /// </summary>
  46. /// <param name="name">学校id 或者醍摩豆id</param>
  47. /// <param name="scope"></param>
  48. /// <param name="_azureCosmos"></param>
  49. /// <param name="_azureRedis"></param>
  50. public static async Task<(long usedSize, long teach, long total, long surplus, Dictionary<string, double?> catalog)> GetSurplusSpace(string name, string scope,Option _option, AzureCosmosFactory _azureCosmos, AzureRedisFactory _azureRedis, AzureStorageFactory _azureStorage,DingDing _dingDing )
  51. {
  52. //已经存储的空间
  53. long usedSize = 0;
  54. //分配给教师的
  55. long teach = 0;
  56. //总空间
  57. long total = 0;
  58. // 剩余的
  59. long surplus = 0;
  60. Dictionary<string, double?> catalog = new Dictionary<string, double?>();
  61. try
  62. {
  63. if (!string.IsNullOrWhiteSpace(name))
  64. {
  65. if ("school".Equals(scope, StringComparison.OrdinalIgnoreCase))
  66. {
  67. School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(name, new PartitionKey("Base"));
  68. total = school.size;
  69. teach = school.tsize;
  70. //用tsize代替
  71. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ",
  72. // requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{name}") }))
  73. //{
  74. // var json = await JsonDocument.ParseAsync(item.ContentStream);
  75. // foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  76. // {
  77. // if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  78. // {
  79. // teach = _size.GetInt32();
  80. // break;
  81. // }
  82. // }
  83. //}
  84. }
  85. else
  86. {
  87. Teacher teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(name, new PartitionKey("Base"));
  88. total = teacher.size;
  89. foreach (var school in teacher.schools)
  90. {
  91. try
  92. {
  93. SchoolTeacher schoolTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<SchoolTeacher>(name, new PartitionKey($"Teacher-{school.schoolId}"));
  94. total += schoolTeacher.size;
  95. }
  96. catch (Exception ex) { }
  97. }
  98. }
  99. long blobsize = 0;
  100. RedisValue value = default;
  101. value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", name);
  102. if (value != default && !value.IsNullOrEmpty)
  103. {
  104. JsonElement record = value.ToString().ToObject<JsonElement>();
  105. if (record.TryGetInt64(out blobsize))
  106. {
  107. }
  108. }
  109. else
  110. {
  111. var client = _azureStorage.GetBlobContainerClient(name);
  112. var size = await client.GetBlobsCatalogSize();
  113. if (size.Item1 > 0)
  114. {
  115. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
  116. }
  117. foreach (var key in size.Item2.Keys)
  118. {
  119. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  120. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  121. }
  122. usedSize = size.Item1.Value;
  123. //1024 * 1024 * 1024=1073741824 =1G
  124. surplus = (total - teach) * 1073741824 - usedSize;
  125. catalog=size.Item2;
  126. //return (usedSize, teach, total, surplus, catalog = size.Item2);
  127. }
  128. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{name}");
  129. if (Scores != null)
  130. {
  131. foreach (var score in Scores)
  132. {
  133. double val = score.Score;
  134. string key = score.Element.ToString();
  135. catalog.Add(key, val);
  136. }
  137. usedSize = blobsize;
  138. //1024 * 1024 * 1024=1073741824 =1G
  139. surplus = (total - teach) * 1073741824 - usedSize;
  140. //return (usedSize, teach, total, surplus, catalog);
  141. }
  142. else
  143. {
  144. //没有缓存
  145. var client = _azureStorage.GetBlobContainerClient(name);
  146. var size = await client.GetBlobsCatalogSize();
  147. if (size.Item1 > 0)
  148. {
  149. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
  150. }
  151. foreach (var key in size.Item2.Keys)
  152. {
  153. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  154. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  155. }
  156. usedSize = size.Item1.Value;
  157. //1024 * 1024 * 1024=1073741824 =1G
  158. //surplus 可能为负数
  159. surplus = (total - teach) * 1073741824 - usedSize;
  160. catalog = size.Item2;
  161. //return (usedSize, teach, total, surplus, catalog = size.Item2);
  162. }
  163. }
  164. }
  165. catch (Exception ex)
  166. {
  167. await _dingDing.SendBotMsg($"IES5,{_option.Location},blob/used-space()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  168. return (usedSize, teach, total, surplus, catalog);
  169. }
  170. if (usedSize > 0 && total > 0) {
  171. double percent= surplus / total * 1073741824 *100;
  172. int tag =11;
  173. if (percent <= 10 && percent > 5)
  174. {
  175. tag = 10;
  176. }
  177. else if (percent <= 5 && percent > 0)
  178. {
  179. tag = 5;
  180. }
  181. else if (percent <= 0)
  182. {
  183. tag = 0;
  184. }//如果已经扩容请忽略此通知!
  185. //if()
  186. }
  187. return (usedSize, teach, total, surplus, catalog);
  188. }
  189. public class BlobSpace{ }
  190. /// <param name="scope">school or private</param>
  191. /// <param name="containerName">school code or tmid</param>
  192. /// <param name="type">doc, res, item... Empty if no need.</param>
  193. /// <param name="periodId">Only for school</param>
  194. public static async Task<List<BlobCount>> BloblogCount(CosmosClient clientc, string scope, string containerName, string type, string periodId)
  195. {
  196. List<BlobCount> bloblogcnt = new List<BlobCount>();
  197. try
  198. {
  199. //必須項檢查
  200. if(scope.Equals("school") && string.IsNullOrWhiteSpace(periodId))
  201. {
  202. return bloblogcnt;
  203. }
  204. //資料取得
  205. var queryslt = new StringBuilder();
  206. queryslt.Append($"SELECT COUNT(1) AS count, c.type FROM c ");
  207. if (scope.Equals("school"))
  208. {
  209. queryslt.Append($"JOIN A1 IN c.periodId WHERE A1 IN ('{periodId}') ");
  210. if(!string.IsNullOrWhiteSpace(type)) queryslt.Append($"AND c.type='{type}'");
  211. queryslt.Append("GROUP BY c.type");
  212. await foreach (var item in clientc.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<BlobCount>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{containerName}") }))
  213. {
  214. bloblogcnt.Add(item);
  215. }
  216. }
  217. else if (scope.Equals("private"))
  218. {
  219. if (!string.IsNullOrWhiteSpace(type)) queryslt.Append($"AND c.type='{type}'");
  220. queryslt.Append("GROUP BY c.type");
  221. await foreach (var item in clientc.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<BlobCount>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{containerName}") }))
  222. {
  223. bloblogcnt.Add(item);
  224. }
  225. }
  226. return bloblogcnt;
  227. }
  228. catch (Exception ex)
  229. {
  230. return bloblogcnt;
  231. }
  232. }
  233. public class UsedBlob
  234. {
  235. public long teach { get; set; }
  236. public long? size { get; set; }
  237. public Dictionary<string, double?> catalog { get; set; }
  238. }
  239. public class BlobCount
  240. {
  241. public string type { get; set; }
  242. public int count { get; set; }
  243. }
  244. }
  245. public class BlobRefreshMessage{
  246. public string id { get; set; }= Guid.NewGuid().ToString();
  247. public string name { get; set; }
  248. public string progress { get; set; }
  249. public string root { get; set; }
  250. }
  251. }