ActiveTaskTopic.cs 138 KB

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