ActiveTaskTopic.cs 142 KB

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