ActiveTaskTopic.cs 110 KB

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