MonitorServicesBus.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.Json;
  4. using System.Threading.Tasks;
  5. using Azure.Cosmos;
  6. using Azure.Messaging.ServiceBus;
  7. using Microsoft.Azure.WebJobs;
  8. using Microsoft.Azure.WebJobs.Host;
  9. using Microsoft.Extensions.Logging;
  10. using StackExchange.Redis;
  11. using TEAMModelOS.SDK.DI;
  12. using TEAMModelOS.SDK.Extension;
  13. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  14. using TEAMModelOS.SDK.Models;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. namespace TEAMModelFunction
  17. {
  18. public class MonitorServicesBus
  19. {
  20. private readonly AzureCosmosFactory _azureCosmos;
  21. private readonly DingDing _dingDing;
  22. private readonly AzureStorageFactory _azureStorage;
  23. private readonly AzureRedisFactory _azureRedis;
  24. private readonly AzureServiceBusFactory _serviceBus;
  25. public MonitorServicesBus(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage , AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus)
  26. {
  27. _azureCosmos = azureCosmos;
  28. _dingDing = dingDing;
  29. _azureStorage = azureStorage;
  30. _azureRedis = azureRedis;
  31. _serviceBus = serviceBus;
  32. }
  33. [FunctionName("Exam")]
  34. public async Task Exam([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  35. {
  36. try
  37. {
  38. var json = JsonDocument.Parse(msg);
  39. json.RootElement.TryGetProperty("id", out JsonElement id);
  40. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  41. json.RootElement.TryGetProperty("code", out JsonElement code);
  42. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  43. var client = _azureCosmos.GetCosmosClient();
  44. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  45. exam.progress = progress.ToString();
  46. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  47. }
  48. catch (Exception ex)
  49. {
  50. await _dingDing.SendBotMsg($"ServiceBus,ExamBus()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  51. }
  52. }
  53. [FunctionName("Vote")]
  54. public async Task Vote([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  55. {
  56. try
  57. {
  58. var jsonMsg = JsonDocument.Parse(msg);
  59. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  60. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  61. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  62. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  63. var client = _azureCosmos.GetCosmosClient();
  64. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  65. vote.progress = progress.ToString();
  66. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  67. }
  68. catch (Exception ex)
  69. {
  70. await _dingDing.SendBotMsg($"ServiceBus,VoteBus()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  71. }
  72. }
  73. [FunctionName("Survey")]
  74. public async Task Survey([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  75. {
  76. try
  77. {
  78. var jsonMsg = JsonDocument.Parse(msg);
  79. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  80. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  81. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  82. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  83. var client = _azureCosmos.GetCosmosClient();
  84. Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  85. survey.progress = progress.ToString();
  86. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  87. }
  88. catch (Exception ex)
  89. {
  90. await _dingDing.SendBotMsg($"ServiceBus,SurveyBus()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  91. }
  92. }
  93. [FunctionName("Blob")]
  94. public async Task Blob([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blob", Connection = "Azure:ServiceBus:ConnectionString")] string msg) {
  95. try
  96. {
  97. // await _dingDing.SendBotMsg($"ServiceBus,Blob(){msg}", GroupNames.醍摩豆服務運維群組);
  98. var jsonMsg = JsonDocument.Parse(msg);
  99. if(jsonMsg.RootElement.TryGetProperty("name", out JsonElement name)&& name.ValueKind==JsonValueKind.String)
  100. {
  101. var client = _azureStorage.GetBlobContainerClient($"{name}");
  102. var size = await client.GetBlobsCatalogSize();
  103. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{long.Parse($"{size.Item1}")}"));
  104. foreach (var key in size.Item2.Keys)
  105. {
  106. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  107. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  108. }
  109. #if DEBUG
  110. await _dingDing.SendBotMsg($"ServiceBus,Blob() 容器:{name}使用:{size.Item1},文件分类:{size.Item2.ToJsonString()}",
  111. GroupNames.成都开发測試群組);
  112. #endif
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. await _dingDing.SendBotMsg($"ServiceBus,Blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  118. }
  119. }
  120. /// <summary>
  121. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  122. /// </summary>
  123. /// <data msg>
  124. /// CourseChange
  125. ///// </data>
  126. /// <param name="msg"></param>
  127. /// <returns></returns>
  128. [FunctionName("StuList")]
  129. public async Task StuList([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "stulist", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  130. {
  131. var client = _azureCosmos.GetCosmosClient();
  132. try
  133. {
  134. await _dingDing.SendBotMsg($"ServiceBus,StuList:{msg}", GroupNames.醍摩豆服務運維群組);
  135. var jsonMsg = JsonDocument.Parse(msg);
  136. StuListChange stuListChange = msg.ToObject<StuListChange>();
  137. //名单变动修改学生课程关联信息
  138. await StuListService.FixStuCourse(client, stuListChange);
  139. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  140. //名单变动修改学生问卷关联信息
  141. await StuListService.FixActivity(client, stuListChange, "Survey");
  142. //名单变动修改学生投票关联信息
  143. await StuListService.FixActivity(client, stuListChange, "Vote");
  144. //名单变动修改学生评测关联信息
  145. await StuListService.FixActivity(client, stuListChange, "Exam");
  146. //TODO学习活动
  147. //await FixActivity(client, stuListChange, "Learn");
  148. //TODO作业活动
  149. // await FixActivity(client, stuListChange, "Homework");
  150. }
  151. catch (Exception ex)
  152. {
  153. await _dingDing.SendBotMsg($"StuListServiceBus-StuList\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  154. }
  155. }
  156. [FunctionName("Notice")]
  157. public async Task Notice([ServiceBusTrigger("%Azure:ServiceBus:NoticeTask%", "notice", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  158. {
  159. var client = _azureRedis.GetRedisClient(8);
  160. try
  161. {
  162. Console.WriteLine(msg);
  163. // List<Task<string>> tasks = new List<Task<string>>();
  164. //List<Task> sessionTasks = new List<Task>();
  165. var jsonMsg = JsonDocument.Parse(msg);
  166. Notice notice = msg.ToObject<Notice>();
  167. var blobcntr = "";
  168. if (notice.scope.Equals("school"))
  169. {
  170. blobcntr = notice.school;
  171. }
  172. else
  173. {
  174. blobcntr = notice.creatorId;
  175. }
  176. if (string.IsNullOrEmpty(blobcntr))
  177. {
  178. return;
  179. }
  180. #if DEBUG
  181. await _dingDing.SendBotMsg($"NoticeServiceBus-Notice:\n发起通知{msg}", GroupNames.成都开发測試群組);
  182. #endif
  183. var urlNotice = $"{notice.msgId}.json";
  184. var blobNotice = new
  185. {
  186. notice.type,
  187. notice.priority,
  188. notice.body,
  189. notice.creation,
  190. notice.expire,
  191. notice.creatorId
  192. };
  193. await _azureStorage.UploadFileByContainer(blobcntr, blobNotice.ToJsonString(), "notice", urlNotice);
  194. var urlReceiver = $"{notice.msgId}_receiver.json";
  195. var blobReceiver = new
  196. {
  197. notice.stuids,
  198. notice.tmdids
  199. };
  200. await _azureStorage.UploadFileByContainer(blobcntr, blobReceiver.ToJsonString(), "notice", urlReceiver);
  201. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  202. // "ttl":2592000,不能超过30天(2592000),一天(3600),一周(25200)
  203. if (notice.stuids.IsNotEmpty())
  204. {
  205. // List<Receiver> receivers = new List<Receiver>();
  206. foreach (var stu in notice.stuids)
  207. {
  208. Receiver receiver = new Receiver
  209. {
  210. id = notice.msgId,
  211. pk = "Receiver",
  212. status = 0,
  213. scope = "school",
  214. ctime = now,
  215. urlNotice = $"/notice/{urlNotice}",
  216. rid = $"{stu.schoolId}-{stu.id}"
  217. };
  218. var url = $"{stu.id}/receive/{notice.msgId}.json";
  219. await client.HashSetAsync($"Notice:Receiver:{stu.schoolId}-{stu.id}", notice.msgId, $"/student/{url}");
  220. // await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync<Receiver>(receiver,new Azure.Cosmos.PartitionKey(receiver.code));
  221. // /student/{stuid}/receive/{notice.sid}.json
  222. //存放通知到学生容器空间
  223. await _azureStorage.UploadFileByContainer(blobcntr, receiver.ToJsonString(), "student", url);
  224. var messageBlob = new ServiceBusMessage(receiver.ToJsonString()) { SessionId = $"{stu.schoolId}-{stu.id}" };
  225. // messageBlob.ApplicationProperties.Add("name", "Receiver");
  226. await _serviceBus.GetServiceBusClient().SendMessageAsync("notice-task", messageBlob);
  227. }
  228. }
  229. if (notice.tmdids.IsNotEmpty())
  230. {
  231. foreach (var tmdid in notice.tmdids)
  232. {
  233. Receiver receiver = new Receiver
  234. {
  235. id = notice.msgId,
  236. pk = "Receiver",
  237. status = 0,
  238. //school = stu.schoolId,
  239. scope = "school",
  240. ctime = now,
  241. urlNotice = $"/notice/{urlNotice}",
  242. rid = $"{tmdid}"
  243. };
  244. var url = $"{notice.msgId}.json";
  245. await client.HashSetAsync($"Notice:Receiver:{tmdid}", notice.msgId, new { now, url = $"/receive/{url}" }.ToJsonString());
  246. //await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync<Receiver>(receiver, new Azure.Cosmos.PartitionKey(receiver.code));
  247. // /student/{stuid}/receive/{notice.sid}.json
  248. //存放通知到学生容器空间
  249. await _azureStorage.UploadFileByContainer(blobcntr, receiver.ToJsonString(), "receive", url);
  250. var messageBlob = new ServiceBusMessage(receiver.ToJsonString()) { SessionId = $"{tmdid}" };
  251. //messageBlob.ApplicationProperties.Add("name", "Receiver");
  252. await _serviceBus.GetServiceBusClient().SendMessageAsync("notice-task", messageBlob);
  253. }
  254. }
  255. }
  256. catch (Exception ex)
  257. {
  258. await _dingDing.SendBotMsg($"NoticeServiceBus-Notice\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  259. }
  260. }
  261. }
  262. }