ActiveTaskTopic.cs 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. using Azure.Cosmos;
  7. using Azure.Messaging.ServiceBus;
  8. using Microsoft.Extensions.Logging;
  9. using StackExchange.Redis;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using System.Linq;
  17. using TEAMModelOS.SDK.Models.Service;
  18. using TEAMModelOS.SDK.Models.Cosmos.BI;
  19. using TEAMModelOS.Models;
  20. using Microsoft.Extensions.Options;
  21. using Microsoft.Extensions.Configuration;
  22. using HTEXLib.COMM.Helpers;
  23. using Microsoft.Azure.Functions.Worker;
  24. using TEAMModelOS.SDK.Services;
  25. using Azure.Storage.Blobs.Models;
  26. using System.IO;
  27. using Azure;
  28. namespace TEAMModelOS.FunctionV4.ServiceBus
  29. {
  30. public class ActiveTaskTopic
  31. {
  32. private readonly AzureCosmosFactory _azureCosmos;
  33. private readonly DingDing _dingDing;
  34. private readonly AzureStorageFactory _azureStorage;
  35. private readonly AzureRedisFactory _azureRedis;
  36. private readonly AzureServiceBusFactory _serviceBus;
  37. private readonly Option _option;
  38. private readonly NotificationService _notificationService;
  39. private readonly CoreAPIHttpService _coreAPIHttpService;
  40. private readonly IConfiguration _configuration;
  41. public ActiveTaskTopic(CoreAPIHttpService coreAPIHttpService,AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
  42. {
  43. _azureCosmos = azureCosmos;
  44. _dingDing = dingDing;
  45. _azureStorage = azureStorage;
  46. _azureRedis = azureRedis;
  47. _serviceBus = serviceBus;
  48. _option = option?.Value;
  49. _notificationService = notificationService;
  50. _configuration = configuration;
  51. _coreAPIHttpService = coreAPIHttpService;
  52. }
  53. [Function("Exam")]
  54. public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  55. {
  56. try
  57. {
  58. var json = JsonDocument.Parse(msg);
  59. json.RootElement.TryGetProperty("id", out JsonElement id);
  60. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  61. json.RootElement.TryGetProperty("code", out JsonElement code);
  62. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  63. var client = _azureCosmos.GetCosmosClient();
  64. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  65. exam.progress = progress.ToString();
  66. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  67. }
  68. catch (CosmosException e)
  69. {
  70. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  71. }
  72. catch (Exception ex)
  73. {
  74. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  75. }
  76. }
  77. [Function("Vote")]
  78. public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  79. {
  80. try
  81. {
  82. var jsonMsg = JsonDocument.Parse(msg);
  83. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  84. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  85. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  86. var client = _azureCosmos.GetCosmosClient();
  87. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  88. vote.progress = progress.ToString();
  89. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  90. }
  91. catch (CosmosException e)
  92. {
  93. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  94. }
  95. catch (Exception ex)
  96. {
  97. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  98. }
  99. }
  100. [Function("Correct")]
  101. public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  102. {
  103. try
  104. {
  105. var jsonMsg = JsonDocument.Parse(msg);
  106. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  107. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  108. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  109. var client = _azureCosmos.GetCosmosClient();
  110. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  111. correct.progress = progress.ToString();
  112. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  113. }
  114. catch (CosmosException e)
  115. {
  116. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  117. }
  118. catch (Exception ex)
  119. {
  120. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  121. }
  122. }
  123. [Function("Survey")]
  124. public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  125. {
  126. try
  127. {
  128. var jsonMsg = JsonDocument.Parse(msg);
  129. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  130. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  131. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  132. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  133. var client = _azureCosmos.GetCosmosClient();
  134. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  135. survey.progress = progress.ToString();
  136. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  137. }
  138. catch (CosmosException e)
  139. {
  140. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  141. }
  142. catch (Exception ex)
  143. {
  144. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  145. }
  146. }
  147. [Function("Homework")]
  148. public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  149. {
  150. try
  151. {
  152. var jsonMsg = JsonDocument.Parse(msg);
  153. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  154. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  155. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  156. var client = _azureCosmos.GetCosmosClient();
  157. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  158. homework.progress = progress.ToString();
  159. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  160. }
  161. catch (CosmosException e)
  162. {
  163. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.StackTrace}{e.Message}{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  164. }
  165. catch (Exception ex)
  166. {
  167. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  168. }
  169. }
  170. [Function("Study")]
  171. public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  172. {
  173. string activityId = string.Empty;
  174. try
  175. {
  176. var jsonMsg = JsonDocument.Parse(msg);
  177. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  178. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  179. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  180. var client = _azureCosmos.GetCosmosClient();
  181. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  182. study.progress = progress.ToString();
  183. activityId = id.ToString();
  184. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  185. }
  186. catch (CosmosException e)
  187. {
  188. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  189. }
  190. catch (Exception ex)
  191. {
  192. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  193. }
  194. }
  195. [Function("ExamLite")]
  196. public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  197. {
  198. try
  199. {
  200. var jsonMsg = JsonDocument.Parse(msg);
  201. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  202. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  203. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  204. var client = _azureCosmos.GetCosmosClient();
  205. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  206. lite.progress = progress.ToString();
  207. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  208. }
  209. catch (CosmosException e)
  210. {
  211. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  212. }
  213. catch (Exception ex)
  214. {
  215. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  216. }
  217. }
  218. /// <summary>
  219. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  220. /// </summary>
  221. /// <param name="msg"></param>
  222. /// <returns></returns>
  223. [Function("BlobRoot")]
  224. public async Task BlobRootFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  225. {
  226. try
  227. {
  228. var jsonMsg = JsonDocument.Parse(msg);
  229. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  230. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  231. {
  232. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  233. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  234. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  235. string name = $"{_name}";
  236. string lockKey = $"Blob:Lock:{name}:{u}";
  237. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  238. if (!exist)
  239. { ///key不存在则正常进行计算
  240. bool condition = false;
  241. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  242. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  243. //准备处理Blob刷新时间
  244. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  245. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  246. await RefreshBlob(name, u);
  247. //将action 与Redis最新的时间进行比较,如果
  248. var rds = await CheckLockKey(lockKey, action);
  249. condition = rds.condition;
  250. exist = rds.exist;
  251. if (condition || !exist)
  252. {
  253. await RefreshBlob(name, u);
  254. }
  255. //使用 CancellationToken
  256. //while (condition || !exist)
  257. //{
  258. //}
  259. }
  260. else
  261. {
  262. ///key存在则,则刷新key对应的值
  263. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  264. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  265. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  266. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  267. }
  268. }
  269. }
  270. catch (Exception ex)
  271. {
  272. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  273. }
  274. }
  275. private async Task<(bool condition, bool exist)> CheckLockKey(string lockKey, long nowTime)
  276. {
  277. //Redis的最新时间
  278. long newestTime = 0;
  279. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  280. if (value != default && !value.IsNullOrEmpty)
  281. {
  282. JsonElement record = value.ToString().ToObject<JsonElement>();
  283. if (record.TryGetInt64(out newestTime))
  284. {
  285. }
  286. }
  287. //说明key已经不存在
  288. if (newestTime == 0)
  289. {
  290. return (false, true);
  291. }
  292. //说明key存在
  293. else
  294. {
  295. //说明Redis记录了最新的时间戳
  296. if (nowTime != newestTime)
  297. {
  298. return (true, false);
  299. }
  300. //时间相同,没有被再次记录最新的时间戳
  301. else
  302. {
  303. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  304. return (false, true);
  305. }
  306. }
  307. }
  308. private async Task RefreshBlob(string name, string u)
  309. {
  310. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  311. var client = _azureStorage.GetBlobContainerClient(name);
  312. var size = await client.GetBlobsSize(u);
  313. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  314. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  315. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  316. double blobsize = 0;
  317. if (scores != default && scores != null)
  318. {
  319. foreach (var score in scores)
  320. {
  321. blobsize = blobsize + score.Score;
  322. }
  323. }
  324. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  325. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  326. long dis = (end - statr) / 1000;
  327. long timeout = 60*5;
  328. if (dis > timeout)
  329. {
  330. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  331. }
  332. }
  333. /// <summary>
  334. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  335. /// </summary>
  336. /// <data msg>
  337. /// CourseChange
  338. ///// </data>
  339. /// <param name="msg"></param>
  340. /// <returns></returns>
  341. [Function("TeacherTrainChange")]
  342. public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  343. {
  344. try
  345. {
  346. // await _dingDing.SendBotMsg($"teacher-train-change\n{msg}",GroupNames.成都开发測試群組);
  347. TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
  348. if (change.update == null || change.update.Count <= 0 || change.tmdids.IsEmpty())
  349. {
  350. return;
  351. }
  352. var client = _azureCosmos.GetCosmosClient();
  353. string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
  354. string selsql = $"select value(c) from c {insql} ";
  355. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  356. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
  357. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
  358. {
  359. teacherTrains.Add(item);
  360. }
  361. if (change.statistics != 1)
  362. {
  363. List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
  364. teacherTrains.ForEach(x =>
  365. {
  366. x.update.UnionWith(change.update);
  367. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
  368. });
  369. await task.TaskPage(5);
  370. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  371. if (unchange != null)
  372. {
  373. task.Clear();
  374. unchange.ToList().ForEach(x =>
  375. {
  376. TeacherTrain teacherTrain = new TeacherTrain
  377. {
  378. pk = "TeacherTrain",
  379. id = x,
  380. code = $"TeacherTrain-{change.school}",
  381. tmdid = x,
  382. school = change.school,
  383. update = new HashSet<string> { StatisticsService.TeacherAbility,
  384. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  385. };
  386. teacherTrain.update.UnionWith(change.update);
  387. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
  388. });
  389. await task.TaskPage(1);
  390. }
  391. }
  392. else
  393. {
  394. Area area = null;
  395. string sql = $"select value(c) from c where c.standard='{change.standard}'";
  396. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
  397. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  398. {
  399. area = item;
  400. }
  401. AreaSetting setting = null;
  402. if (area != null)
  403. {
  404. try
  405. {
  406. //优先找校级
  407. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  408. }
  409. catch (CosmosException)
  410. {
  411. try
  412. {
  413. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  414. }
  415. catch (CosmosException)
  416. {
  417. setting = null;
  418. }
  419. }
  420. }
  421. if (setting == null)
  422. {
  423. setting = new AreaSetting
  424. {
  425. allTime = 50,
  426. classTime = 5,
  427. submitTime = 15,
  428. onlineTime = 20,
  429. offlineTime = 10,
  430. lessonMinutes = 45,
  431. };
  432. }
  433. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  434. teacherTrains.ForEach(x =>
  435. {
  436. x.update.UnionWith(change.update);
  437. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  438. });
  439. await task.TaskPage(1);
  440. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  441. if (unchange != null)
  442. {
  443. task.Clear();
  444. unchange.ToList().ForEach(x =>
  445. {
  446. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  447. {
  448. pk = "TeacherTrain",
  449. id = x,
  450. code = $"TeacherTrain-{change.school}",
  451. tmdid = x,
  452. school = change.school,
  453. update = new HashSet<string> { StatisticsService.TeacherAbility,
  454. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  455. }, setting, area, client, null));
  456. });
  457. await task.TaskPage(1);
  458. }
  459. }
  460. }
  461. catch (CosmosException ex)
  462. {
  463. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}CosmosException{ex.Status}", GroupNames.醍摩豆服務運維群組);
  464. }
  465. catch (Exception ex)
  466. {
  467. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  468. }
  469. }
  470. /// <summary>
  471. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  472. /// </summary>
  473. /// <data msg>
  474. /// CourseChange
  475. ///// </data>
  476. /// <param name="msg"></param>
  477. /// <returns></returns>
  478. [Function("GroupChange")]
  479. public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  480. {
  481. var client = _azureCosmos.GetCosmosClient();
  482. try
  483. {
  484. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.醍摩豆服務運維群組);
  485. var jsonMsg = JsonDocument.Parse(msg);
  486. GroupChange groupChange = msg.ToObject<GroupChange>();
  487. //名单变动修改学生课程关联信息
  488. //await StuListService.FixStuCourse(client, stuListChange);
  489. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  490. //名单变动修改学生问卷关联信息
  491. await ActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
  492. //名单变动修改学生投票关联信息
  493. await ActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
  494. //名单变动修改学生评测关联信息
  495. await ActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
  496. //名单变动修改学生研修关联信息
  497. await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  498. //名单变动修改学生简易评测关联信息
  499. await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  500. //名单变动修改学生作业活动信息
  501. await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  502. //TODO学习活动
  503. //await FixActivity(client, stuListChange, "Learn");
  504. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  505. {
  506. //课程名单变动修改学生课程关联信息
  507. await ActivityService.FixStuCourse(client, _dingDing, groupChange);
  508. //名单变动修改课例关联信息
  509. //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
  510. }
  511. }
  512. catch (Exception ex)
  513. {
  514. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange-GroupChange\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  515. }
  516. }
  517. [Function("ItemCond")]
  518. public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  519. {
  520. try
  521. {
  522. var client = _azureCosmos.GetCosmosClient();
  523. var jsonMsg = JsonDocument.Parse(msg);
  524. List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
  525. foreach (var itemCondDto in itemCondDtos)
  526. {
  527. if (itemCondDto.scope.Equals("school"))
  528. {
  529. ItemCond itemCond = null;
  530. List<ItemInfo> items = new List<ItemInfo>();
  531. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.periodId='{itemCondDto.filed}' and c.pid= null ";
  532. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
  533. {
  534. items.Add(item);
  535. }
  536. itemCond = new ItemCond()
  537. {
  538. id = $"{itemCondDto.filed}",
  539. code = $"ItemCond-{itemCondDto.key}",
  540. pk = "ItemCond",
  541. ttl = -1,
  542. count = items.Count,
  543. grades = new List<GradeCount>(),
  544. subjects = new List<SubjectItemCount>()
  545. };
  546. items.ForEach(z =>
  547. {
  548. if (!string.IsNullOrEmpty(z.type))
  549. {
  550. ItemService.CountItemCond(z, null, itemCond);
  551. }
  552. });
  553. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
  554. }
  555. else
  556. {
  557. ItemCond itemCond = null;
  558. List<ItemInfo> items = new List<ItemInfo>();
  559. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
  560. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
  561. {
  562. items.Add(item);
  563. }
  564. itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
  565. items.ForEach(z =>
  566. {
  567. if (!string.IsNullOrEmpty(z.type))
  568. {
  569. ItemService.CountItemCond(z, null, itemCond);
  570. }
  571. });
  572. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
  573. }
  574. }
  575. }
  576. catch (CosmosException ex)
  577. {
  578. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  579. }
  580. catch (Exception ex)
  581. {
  582. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  583. }
  584. }
  585. //更新產品一覽表
  586. [Function("Product")]
  587. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  588. {
  589. try
  590. {
  591. var jsonMsg = JsonDocument.Parse(msg);
  592. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  593. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  594. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  595. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  596. var client = _azureCosmos.GetCosmosClient();
  597. string strQuery = string.Empty;
  598. //取得所有學校產品
  599. ////序號
  600. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  601. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  602. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  603. {
  604. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  605. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  606. {
  607. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  608. {
  609. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  610. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  611. if (serialProd == null)
  612. {
  613. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  614. serialProdAdd.prodCode = serialInfo.prodCode;
  615. serialProdAdd.ids.Add(serialInfo.id);
  616. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  617. serialsProductSumOrg.Add(serialProdAdd);
  618. }
  619. else
  620. {
  621. if (!serialProd.ids.Contains(serialInfo.id))
  622. {
  623. serialProd.ids.Add(serialInfo.id);
  624. }
  625. serialProd.avaliable = serialProd.ids.Count;
  626. }
  627. }
  628. }
  629. }
  630. ////服務
  631. List<SchoolProductSumData> servicesProductSumOrg = new List<SchoolProductSumData>();
  632. long timestampToday = DateTimeOffset.UtcNow.AddSeconds(1).ToUnixTimeSeconds(); //比現實時間延遲1秒
  633. strQuery = $"SELECT * FROM c WHERE c.dataType = 'service' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0"; //在授權期間、ttl < 0 才取
  634. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  635. {
  636. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  637. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  638. {
  639. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  640. {
  641. SchoolProductService serviceInfo = obj.ToObject<SchoolProductService>();
  642. SchoolProductSumData serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == serviceInfo.prodCode).FirstOrDefault();
  643. if (serviceProd == null)
  644. {
  645. SchoolProductSumData serviceProdAdd = new SchoolProductSumData();
  646. serviceProdAdd.prodCode = serviceInfo.prodCode;
  647. serviceProdAdd.avaliable = 0;
  648. serviceProdAdd.ids.Add(serviceInfo.id);
  649. serviceProdAdd.avaliable += serviceInfo.number;
  650. servicesProductSumOrg.Add(serviceProdAdd);
  651. }
  652. else
  653. {
  654. if (!serviceProd.ids.Contains(serviceInfo.id))
  655. {
  656. serviceProd.ids.Add(serviceInfo.id);
  657. serviceProd.avaliable += serviceInfo.number;
  658. }
  659. }
  660. }
  661. }
  662. }
  663. ////服務產品特別對應項
  664. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  665. bool updSchool = false; //是否變更學校基本資料
  666. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  667. int schoolDefaultSize = 1; //學校空間初始值:1
  668. if (!string.IsNullOrWhiteSpace(school.id))
  669. {
  670. if (servicesProductSumOrg.Count > 0)
  671. {
  672. foreach (SchoolProductSumData servicesProductSumOrgRow in servicesProductSumOrg)
  673. {
  674. //更新學校空間
  675. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  676. {
  677. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  678. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  679. updSchool = true;
  680. chgSchSizeCnt++;
  681. }
  682. }
  683. }
  684. if(chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  685. {
  686. school.size = schoolDefaultSize;
  687. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  688. updSchool = false;
  689. }
  690. }
  691. //變更學校基本資料
  692. if(updSchool)
  693. {
  694. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  695. }
  696. ////硬體
  697. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  698. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  699. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  700. {
  701. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  702. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  703. {
  704. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  705. {
  706. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  707. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  708. if (hardProd == null)
  709. {
  710. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  711. hardProdAdd.prodCode = hardInfo.prodCode;
  712. hardProdAdd.model = hardInfo.model;
  713. hardProdAdd.ids.Add(hardInfo.id);
  714. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  715. hardsProductSumOrg.Add(hardProdAdd);
  716. }
  717. else
  718. {
  719. if (!hardProd.ids.Contains(hardInfo.id))
  720. {
  721. hardProd.ids.Add(hardInfo.id);
  722. }
  723. hardProd.avaliable = hardProd.ids.Count;
  724. }
  725. }
  726. }
  727. }
  728. //更新學校產品一覽表
  729. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  730. prodSum.serial = serialsProductSumOrg;
  731. prodSum.service = servicesProductSumOrg;
  732. prodSum.hard = hardsProductSumOrg;
  733. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  734. }
  735. catch (CosmosException ex)
  736. {
  737. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  738. }
  739. catch (Exception ex)
  740. {
  741. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  742. }
  743. }
  744. /// <summary>
  745. /// 批量复制文件
  746. /// </summary>
  747. /// <param name="msg"></param>
  748. /// <returns></returns>
  749. [Function("CopyStandardFile")]
  750. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  751. {
  752. try
  753. {
  754. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
  755. var jsonMsg = JsonDocument.Parse(msg);
  756. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  757. //批量复制文件
  758. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  759. if (result == 200)
  760. {
  761. //发送消息实体
  762. Notification notification = new Notification
  763. {
  764. hubName = "hita",
  765. type = "msg",
  766. from = $"BI:{_option.Location}:private",
  767. to = bIBatchCopyFile.tmdIds,
  768. label = $"{bIBatchCopyFile.codeKey}_finish",
  769. body = new { location = $"{Environment.GetEnvironmentVariable("Option:Location")}", biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  770. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  771. };
  772. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  773. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  774. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  775. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  776. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  777. }
  778. }
  779. catch (Exception ex)
  780. {
  781. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  782. }
  783. }
  784. /// <summary>
  785. /// 更新开课数据事件
  786. /// </summary>
  787. /// <param name="msg"></param>
  788. /// <returns></returns>
  789. [Function("LessonRecordEvent")]
  790. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  791. {
  792. JsonElement data = msg.ToObject<JsonElement>();
  793. string scope = "";
  794. string tmdid = "";
  795. string lessonId;
  796. string school;
  797. string tbname;
  798. string code;
  799. string blobname;
  800. List<LessonUpdate> updates = new List<LessonUpdate>();
  801. //更新课堂记录
  802. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  803. {
  804. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  805. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  806. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  807. data.TryGetProperty("school", out JsonElement _school);
  808. school = $"{_school}";
  809. scope = $"{_scope}";
  810. tmdid = $"{_tmdid}";
  811. lessonId = $"{_lessonId}";
  812. updates = _grant_types.ToObject<List<LessonUpdate>>();
  813. }//创建课堂记录
  814. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  815. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  816. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  817. {
  818. data.TryGetProperty("school", out JsonElement _school);
  819. school = $"{_school}";
  820. scope = $"{_scope}";
  821. tmdid = $"{_tmdid}";
  822. lessonId = $"{_id}";
  823. updates.Add(new LessonUpdate { grant_type = "create" });
  824. }//删除课堂记录
  825. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  826. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  827. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  828. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  829. {
  830. data.TryGetProperty("school", out JsonElement _dschool);
  831. school = $"{_dschool}";
  832. if ($"{_opt}".Equals("delete"))
  833. {
  834. scope = $"{_dscope}";
  835. tmdid = $"{_dtmdid}";
  836. lessonId = $"{_delete_id}";
  837. updates.Add(new LessonUpdate { grant_type = "delete" });
  838. }
  839. else { return; }
  840. }
  841. else
  842. {
  843. return;
  844. }
  845. var client = _azureCosmos.GetCosmosClient();
  846. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  847. {
  848. blobname = $"{school}";
  849. code = $"LessonRecord-{school}";
  850. tbname = "School";
  851. }
  852. else if ($"{scope}".Equals("private"))
  853. {
  854. blobname = $"{tmdid}";
  855. code = $"LessonRecord";
  856. tbname = "Teacher";
  857. }
  858. else
  859. {
  860. return;
  861. }
  862. LessonDis lessonDis = new LessonDis();
  863. List<LessonUpdate> msgs = new List<LessonUpdate>();
  864. try
  865. {
  866. LessonRecord oldlessonRecord = null;
  867. LessonRecord lessonRecord = null;
  868. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  869. if (response.Status == 200)
  870. {
  871. var doc = JsonDocument.Parse(response.ContentStream);
  872. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  873. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  874. }
  875. else
  876. {
  877. lessonRecord = null;
  878. }
  879. bool isReplace = true;
  880. if (updates.IsNotEmpty())
  881. {
  882. foreach (LessonUpdate update in updates)
  883. {
  884. switch (update.grant_type)
  885. {
  886. //更新课堂时长
  887. case "up-duration":
  888. var duration = double.Parse($"{update.data}");
  889. lessonRecord.duration = duration;
  890. msgs.Add(update);
  891. try {
  892. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  893. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  894. if (RecordingJson.TryGetProperty("duration",out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number)) {
  895. var durationFile = double.Parse($"{_duration}");
  896. if (duration < durationFile) {
  897. lessonRecord.duration = durationFile;
  898. }
  899. }
  900. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) &&!string.IsNullOrWhiteSpace($"{_streamUrl}"))
  901. {
  902. lessonRecord.hasVideo = 1;
  903. }
  904. }
  905. catch (Exception ex ) {
  906. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  907. }
  908. isReplace = true;
  909. break;
  910. //更新T分
  911. case "up-tScore":
  912. var tScore = int.Parse($"{update.data}");
  913. lessonRecord.tScore = tScore;
  914. msgs.Add(update);
  915. break;
  916. //更新课P分
  917. case "up-pScore":
  918. var pScore = int.Parse($"{update.data}");
  919. lessonRecord.pScore = pScore;
  920. msgs.Add(update);
  921. break;
  922. //更新 学生人数
  923. case "up-mCount":
  924. var mCount = int.Parse($"{update.data}");
  925. lessonRecord.mCount = mCount;
  926. msgs.Add(update);
  927. break;
  928. //更新 议课次数
  929. case "up-techCount":
  930. var techCount = int.Parse($"{update.data}");
  931. lessonRecord.mCount = techCount;
  932. msgs.Add(update);
  933. break;
  934. //更新 基础统计信息
  935. case "up-base":
  936. //如果有更新 则去读取/{_lessonId}/IES/base.json
  937. try
  938. {
  939. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  940. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  941. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  942. if (lessonBase != null && lessonBase.summary!=null)
  943. {
  944. lessonRecord.name = lessonBase.summary.activityName;
  945. lessonRecord.attendCount = lessonBase.summary.attendCount;
  946. lessonRecord.clientCount = lessonBase.summary.clientCount;
  947. lessonRecord.attendRate = lessonBase.summary.attendRate;
  948. lessonRecord.groupCount = lessonBase.summary.groupCount;
  949. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  950. lessonRecord.collateCount = lessonBase.summary.collateCount;
  951. lessonRecord.pushCount = lessonBase.summary.pushCount;
  952. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  953. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  954. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  955. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  956. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  957. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  958. lessonRecord.examCount = lessonBase.summary.examCount;
  959. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  960. }
  961. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  962. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  963. Bloblog bloblog = new Bloblog
  964. {
  965. id = lessonRecord.id,
  966. code = $"Bloblog-{blobname}",
  967. name = lessonRecord.name,
  968. pk = "Bloblog",
  969. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  970. type = "records",
  971. url = $"records/{_lessonId}",
  972. subjectId =string.IsNullOrWhiteSpace(lessonRecord.subjectId)?new List<string>(): new List<string> { lessonRecord.subjectId },
  973. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  974. size = size.HasValue ? size.Value : 0,
  975. };
  976. await client.GetContainer(Constant.TEAMModelOS,tbname).UpsertItemAsync(bloblog);
  977. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  978. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  979. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  980. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  981. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  982. msgs.Add(update);
  983. }
  984. catch (Exception ex)
  985. {
  986. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  987. }
  988. break;
  989. //更新 时间线
  990. case "up-TimeLine":
  991. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  992. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  993. msgs.Add(update);
  994. break;
  995. //更新 课堂总览信息
  996. case "up-ActivityInfo":
  997. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  998. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  999. msgs.Add(update);
  1000. break;
  1001. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1002. isReplace = true;
  1003. msgs.Add(update);
  1004. break;
  1005. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1006. try {
  1007. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1008. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1009. foreach (var record in records)
  1010. {
  1011. try
  1012. {
  1013. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1014. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1015. }
  1016. catch (Exception)
  1017. {
  1018. continue;
  1019. }
  1020. }
  1021. } catch (Exception) {
  1022. break;
  1023. }
  1024. isReplace = true;
  1025. msgs.Add(update);
  1026. break;
  1027. case "delete":
  1028. try
  1029. {
  1030. if (lessonRecord.expire > 0) {
  1031. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1032. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1033. foreach (var record in records)
  1034. {
  1035. try
  1036. {
  1037. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1038. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1039. }
  1040. catch (Exception)
  1041. {
  1042. continue;
  1043. }
  1044. }
  1045. }
  1046. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1047. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id,new PartitionKey ($"Bloblog-{blobname}"));
  1048. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1049. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1050. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1051. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1052. msgs.Add(update);
  1053. }
  1054. catch (CosmosException)
  1055. {
  1056. msgs.Add(update);
  1057. }
  1058. lessonRecord = null;
  1059. isReplace = false;
  1060. break;
  1061. case "create":
  1062. oldlessonRecord = null;
  1063. //处理课堂选用的课程信息
  1064. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  1065. lessonRecord.show = teacher.lessonShow;
  1066. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1067. {
  1068. Course course = null;
  1069. try
  1070. {
  1071. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1072. if (cresponse.Status == 200)
  1073. {
  1074. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1075. course = cJson.ToObject<Course>();
  1076. }
  1077. else
  1078. {
  1079. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1080. if (sresponse.Status == 200)
  1081. {
  1082. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1083. course = cJson.ToObject<Course>();
  1084. }
  1085. else
  1086. {
  1087. course = null;
  1088. }
  1089. }
  1090. }
  1091. catch (Exception ex) {
  1092. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1093. }
  1094. /*catch (CosmosException ex) when (ex.Status != 404)
  1095. {
  1096. try
  1097. {
  1098. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1099. }
  1100. catch (CosmosException e) when (e.Status != 404)
  1101. {
  1102. course = null;
  1103. }
  1104. }*/
  1105. if (course != null)
  1106. {
  1107. lessonRecord.periodId = course.period?.id;
  1108. lessonRecord.subjectId = course.subject?.id;
  1109. }
  1110. }
  1111. //处理课堂选用的名单
  1112. if (lessonRecord.groupIds.IsNotEmpty())
  1113. {
  1114. HashSet<string> grades = new HashSet<string>();
  1115. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1116. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1117. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1118. {
  1119. try
  1120. {
  1121. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1122. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1123. //年级算法
  1124. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1125. int? Count = period?.grades?.Count;
  1126. if (Count.HasValue)
  1127. {
  1128. int Day = DateTimeOffset.UtcNow.Day;
  1129. int Month = DateTimeOffset.UtcNow.Month;
  1130. int Year = DateTimeOffset.UtcNow.Year;
  1131. int start = int.Parse($"{Year}0901");
  1132. var se = period.semesters.Find(x => x.start == 1);
  1133. if (se == null)
  1134. {
  1135. se = period.semesters.First();
  1136. }
  1137. if (se != null)
  1138. {
  1139. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1140. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1141. start = int.Parse($"{Year}{sm}{sd}");
  1142. }
  1143. int curr = int.Parse(DateTimeOffset.UtcNow.ToString("yyyyMMdd"));
  1144. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  1145. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  1146. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  1147. int dis = start - curr;
  1148. foreach (int year in gplist.Select(x => x.year))
  1149. {
  1150. int grade;
  1151. if (dis > 0)
  1152. {
  1153. grade = (Year - year - 1) % Count.Value;
  1154. }
  1155. else
  1156. {
  1157. grade = (Year - year) % Count.Value;
  1158. }
  1159. grades.Add($"{grade}");
  1160. }
  1161. }
  1162. }
  1163. catch (CosmosException ex) when (ex.Status == 404)
  1164. {
  1165. }
  1166. catch (Exception ex) {
  1167. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1168. }
  1169. }
  1170. lessonRecord.grade= grades.ToList();
  1171. }
  1172. //个人课例保存规则
  1173. try {
  1174. if (scope.Equals("private"))
  1175. {
  1176. if (teacher.lessonLimit != -1)
  1177. {
  1178. HashSet<string> ids = new HashSet<string>();
  1179. //未定义的 以及过期时间小于等于0 的 课例
  1180. string private_count_sql = "select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) ";
  1181. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1182. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1183. {
  1184. ids.Add(item);
  1185. }
  1186. //包含收藏的本人的个人课例
  1187. string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.scope='private' ";
  1188. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1189. queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1190. {
  1191. ids.Add(item);
  1192. }
  1193. //教师个人预设的,可以通过设置的方式增加
  1194. int limit = teacher.lessonLimit;
  1195. if (teacher.lessonLimit == 0)
  1196. {
  1197. //未设置的的采用系统设置的默认值30
  1198. limit = Constant.private_lesson_limit;
  1199. }
  1200. if (ids.Count >= limit)
  1201. {
  1202. // 1-时间戳,7-时间戳
  1203. Dictionary<int, long> result = new Dictionary<int, long>();
  1204. //暂定7天
  1205. var now = DateTimeOffset.UtcNow;
  1206. //剩余3天的通知
  1207. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1208. //result.Add(3, day3);
  1209. //剩余1天的通知
  1210. var day1 = now.AddDays(Constant.private_lesson_expire -6).ToUnixTimeMilliseconds();
  1211. result.Add(1, day1);
  1212. //到期通知
  1213. lessonRecord.expire = now.AddDays(Constant.private_lesson_expire).ToUnixTimeMilliseconds();
  1214. result.Add(Constant.private_lesson_expire, lessonRecord.expire);
  1215. string biz = "expire";
  1216. Notification notification = new Notification
  1217. {
  1218. hubName = "hita",
  1219. type = "msg",
  1220. from = $"ies5:{ Environment.GetEnvironmentVariable("Option:Location")}:private",
  1221. to = new List<string> { tmdid },
  1222. label = $"{biz}_lessonRecord",
  1223. body = new {
  1224. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1225. biz = biz,
  1226. tmdid = teacher.id,
  1227. tmdname = teacher.name,
  1228. sid = lessonRecord.id,
  1229. sname = lessonRecord.name,
  1230. stime = lessonRecord.startTime,
  1231. expire = lessonRecord.expire,
  1232. status = 1,
  1233. day = Constant.private_lesson_expire,
  1234. time = now
  1235. }.ToJsonString(),
  1236. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1237. };
  1238. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1239. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1240. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1241. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1242. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1243. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1244. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1245. if (records.Count <= 0)
  1246. {
  1247. foreach (var item in result)
  1248. {
  1249. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  1250. //课堂的id ,
  1251. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1252. var message = new ServiceBusMessage(new
  1253. {
  1254. id = lessonRecord.id,
  1255. progress = item.Key,
  1256. code = lessonRecord.code,
  1257. scope = lessonRecord.scope,
  1258. school = lessonRecord.school,
  1259. opt = "delete",
  1260. expire = lessonRecord.expire,
  1261. tmdid = tmdid,
  1262. tmdname = teacher.name,
  1263. name = lessonRecord.name,
  1264. startTime = lessonRecord.startTime
  1265. }.ToJsonString());
  1266. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1267. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value));
  1268. ChangeRecord changeRecord = new ChangeRecord
  1269. {
  1270. RowKey = lessonRecord.id,
  1271. PartitionKey = PartitionKey,
  1272. sequenceNumber = start,
  1273. msgId = message.MessageId
  1274. };
  1275. await table.Save<ChangeRecord>(changeRecord);
  1276. }
  1277. }
  1278. }
  1279. }
  1280. else
  1281. {
  1282. //=-1 则表示不限制上传数量
  1283. }
  1284. }
  1285. } catch (Exception e) {
  1286. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1287. }
  1288. msgs.Add(update);
  1289. break;
  1290. default:
  1291. break;
  1292. }
  1293. }
  1294. //如果被删除则不能再被更新
  1295. if (isReplace) {
  1296. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1297. }
  1298. //计算课堂更新前后的差值
  1299. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1300. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1301. }
  1302. }
  1303. catch (CosmosException e)
  1304. {
  1305. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1306. }
  1307. catch (Exception ex)
  1308. {
  1309. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1310. }
  1311. }
  1312. [Function("LessonRecordExpire")]
  1313. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1314. {
  1315. try
  1316. {
  1317. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1318. jsonMsg.TryGetProperty("id", out JsonElement id);
  1319. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1320. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1321. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1322. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1323. jsonMsg.TryGetProperty("name", out JsonElement name);
  1324. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1325. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1326. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1327. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1328. var client = _azureCosmos.GetCosmosClient();
  1329. //处理到期删除
  1330. if ($"{progress}".Equals($"{Constant.private_lesson_expire}")) {
  1331. string lessonId = $"{id}";
  1332. string tbname;
  1333. string school=$"{_school}";
  1334. string code = "";
  1335. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1336. {
  1337. code = $"LessonRecord-{school}";
  1338. tbname = "School";
  1339. }
  1340. else if ($"{scope}".Equals("private"))
  1341. {
  1342. code = $"LessonRecord";
  1343. tbname = "Teacher";
  1344. }
  1345. else
  1346. {
  1347. return;
  1348. }
  1349. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1350. if (response.Status == 200)
  1351. {
  1352. LessonRecord lessonRecord;
  1353. var doc = JsonDocument.Parse(response.ContentStream);
  1354. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1355. lessonRecord.status = 404;
  1356. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1357. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1358. var messageChange = new ServiceBusMessage(new { delete_id =lessonId, tmdid =tmdid,scope=scope,opt="delete",school=school}.ToJsonString());
  1359. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1360. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1361. }
  1362. }
  1363. string biz = "expire";
  1364. Notification notification = new Notification
  1365. {
  1366. hubName = "hita",
  1367. type = "msg",
  1368. from = $"ies5:{_option.Location}:private",
  1369. to = new List<string> { $"{tmdid}" },
  1370. label = $"{biz}_lessonRecord",
  1371. body = new {
  1372. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1373. biz = biz,
  1374. tmdid = $"{tmdid}",
  1375. tmdname = tmdname,
  1376. sid =$"{id}",
  1377. sname = $"{name}",
  1378. stime = long.Parse($"{startTime}"),
  1379. expire = long.Parse($"{expire}"),
  1380. status = 1,
  1381. day = Constant.private_lesson_expire,
  1382. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1383. }.ToJsonString(),
  1384. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1385. };
  1386. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1387. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1388. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1389. var location =$"{Environment.GetEnvironmentVariable("Option:Location")}";
  1390. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1391. }
  1392. catch (Exception ex)
  1393. {
  1394. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  1395. }
  1396. }
  1397. /// <summary>
  1398. /// 完善课程变更
  1399. /// </summary>
  1400. /// <data msg>
  1401. /// CourseChange
  1402. ///// </data>
  1403. /// <param name="msg"></param>
  1404. /// <returns></returns>
  1405. [Function("Course")]
  1406. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1407. {
  1408. var client = _azureCosmos.GetCosmosClient();
  1409. try
  1410. {
  1411. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1412. var jsonMsg = JsonDocument.Parse(msg);
  1413. CourseChange courseChange = msg.ToObject<CourseChange>();
  1414. if (courseChange == null)
  1415. {
  1416. return;
  1417. }
  1418. foreach (var cls in courseChange.addClass)
  1419. {
  1420. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1421. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1422. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1423. foreach (var stu in addStudentsCls)
  1424. {
  1425. try
  1426. {
  1427. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1428. if (!stuCourse.Value.classId.Contains(cls))
  1429. {
  1430. stuCourse.Value.classId.Add(cls);
  1431. }
  1432. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1433. }
  1434. catch (CosmosException ex)
  1435. {
  1436. if (ex.Response.Status == 404)
  1437. {
  1438. var course = new StuCourse
  1439. {
  1440. id = courseChange.id,
  1441. scode = courseChange.code,
  1442. name = courseChange.name,
  1443. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1444. scope = courseChange.scope,
  1445. school = courseChange.school,
  1446. creatorId = courseChange.creatorId,
  1447. classId = new List<string> { cls },
  1448. pk = "StuCourse",
  1449. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1450. };
  1451. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1452. }
  1453. else
  1454. {
  1455. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1456. }
  1457. }
  1458. }
  1459. foreach (var tmd in addTmdidsCls)
  1460. {
  1461. try
  1462. {
  1463. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1464. if (!stuCourse.Value.classId.Contains(cls))
  1465. {
  1466. stuCourse.Value.classId.Add(cls);
  1467. }
  1468. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1469. }
  1470. catch (CosmosException ex)
  1471. {
  1472. if (ex.Response.Status == 404)
  1473. {
  1474. var course = new StuCourse
  1475. {
  1476. id = courseChange.id,
  1477. scode = courseChange.code,
  1478. name = courseChange.name,
  1479. code = $"StuCourse-{tmd.id}",
  1480. scope = courseChange.scope,
  1481. school = courseChange.school,
  1482. creatorId = courseChange.creatorId,
  1483. classId = new List<string> { cls },
  1484. pk = "StuCourse",
  1485. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1486. };
  1487. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1488. }
  1489. else
  1490. {
  1491. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1492. }
  1493. }
  1494. }
  1495. }
  1496. foreach (var list in courseChange.addList)
  1497. {
  1498. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1499. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1500. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1501. foreach (var stu in addStudentsCls)
  1502. {
  1503. try
  1504. {
  1505. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1506. if (!stuCourse.Value.stulist.Contains(list))
  1507. {
  1508. stuCourse.Value.stulist.Add(list);
  1509. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1510. }
  1511. }
  1512. catch (CosmosException ex)
  1513. {
  1514. if (ex.Response.Status == 404)
  1515. {
  1516. var course = new StuCourse
  1517. {
  1518. id = courseChange.id,
  1519. scode = courseChange.code,
  1520. name = courseChange.name,
  1521. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1522. scope = courseChange.scope,
  1523. school = courseChange.school,
  1524. creatorId = courseChange.creatorId,
  1525. stulist = new List<string> { list },
  1526. pk = "StuCourse",
  1527. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1528. };
  1529. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1530. }
  1531. else
  1532. {
  1533. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1534. }
  1535. }
  1536. }
  1537. foreach (var tmd in addTmdidsCls)
  1538. {
  1539. try
  1540. {
  1541. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1542. if (!stuCourse.Value.stulist.Contains(list))
  1543. {
  1544. stuCourse.Value.stulist.Add(list);
  1545. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1546. }
  1547. }
  1548. catch (CosmosException ex)
  1549. {
  1550. if (ex.Response.Status == 404)
  1551. {
  1552. var course = new StuCourse
  1553. {
  1554. id = courseChange.id,
  1555. scode = courseChange.code,
  1556. name = courseChange.name,
  1557. code = $"StuCourse-{tmd.id}",
  1558. scope = courseChange.scope,
  1559. school = courseChange.school,
  1560. creatorId = courseChange.creatorId,
  1561. stulist = new List<string> { list },
  1562. pk = "StuCourse",
  1563. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1564. };
  1565. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1566. }
  1567. else
  1568. {
  1569. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1570. }
  1571. }
  1572. }
  1573. }
  1574. foreach (var delCls in courseChange.delClass)
  1575. {
  1576. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1577. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1578. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1579. foreach (var stu in delStudentsCls)
  1580. {
  1581. try
  1582. {
  1583. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1584. if (stuCourse.Value.classId.Contains(delCls))
  1585. {
  1586. stuCourse.Value.classId.Remove(delCls);
  1587. }
  1588. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1589. {
  1590. //当两个列表都不存在时则直接删除
  1591. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1592. }
  1593. else
  1594. {
  1595. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1596. }
  1597. }
  1598. catch (CosmosException ex)
  1599. {
  1600. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1601. }
  1602. }
  1603. foreach (var tmd in delTmdidsCls)
  1604. {
  1605. try
  1606. {
  1607. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1608. if (stuCourse.Value.classId.Contains(delCls))
  1609. {
  1610. stuCourse.Value.classId.Remove(delCls);
  1611. }
  1612. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1613. {
  1614. //当两个列表都不存在时则直接删除
  1615. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1616. }
  1617. else
  1618. {
  1619. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1620. }
  1621. }
  1622. catch (CosmosException ex)
  1623. {
  1624. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1625. }
  1626. }
  1627. }
  1628. foreach (var delList in courseChange.delList)
  1629. {
  1630. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1631. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1632. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1633. foreach (var stu in delStudentsCls)
  1634. {
  1635. try
  1636. {
  1637. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1638. if (stuCourse.Value.stulist.Contains(delList))
  1639. {
  1640. stuCourse.Value.stulist.Remove(delList);
  1641. }
  1642. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1643. {
  1644. //当两个列表都不存在时则直接删除
  1645. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1646. }
  1647. else
  1648. {
  1649. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1650. }
  1651. }
  1652. catch (CosmosException ex)
  1653. {
  1654. continue;
  1655. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1656. }
  1657. }
  1658. foreach (var tmd in delTmdidsCls)
  1659. {
  1660. try
  1661. {
  1662. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1663. if (stuCourse.Value.stulist.Contains(delList))
  1664. {
  1665. stuCourse.Value.stulist.Remove(delList);
  1666. }
  1667. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1668. {
  1669. //当两个列表都不存在时则直接删除
  1670. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1671. }
  1672. else
  1673. {
  1674. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1675. }
  1676. }
  1677. catch (CosmosException ex)
  1678. {
  1679. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1680. }
  1681. }
  1682. }
  1683. }
  1684. catch (Exception ex)
  1685. {
  1686. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1687. }
  1688. }
  1689. }
  1690. }