ActiveTaskTopic.cs 133 KB

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