ActiveTaskTopic.cs 123 KB

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