ActiveTaskTopic.cs 122 KB

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