ActiveTaskTopic.cs 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  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 code = "";
  621. element.TryGetProperty("Key", out JsonElement key);
  622. if (string.IsNullOrWhiteSpace($"{_code}"))
  623. {
  624. code = $"{key}";
  625. }
  626. else {
  627. code = $"{_code}";
  628. }
  629. if (string.IsNullOrWhiteSpace(code))
  630. {
  631. await _dingDing.SendBotMsg($"校本研修生成PDF时,学校id为空\n{msg}", GroupNames.成都开发測試群組);
  632. return;
  633. }
  634. string sname = string.Empty;
  635. string areaId = string.Empty;
  636. School school= await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{code}", new PartitionKey("Base"));
  637. sname = school.name;
  638. areaId = school.areaId;
  639. //var scquery = $"SELECT c.name,c.areaId from c where c.id = '{code}'";
  640. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: scquery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  641. //{
  642. // using var json = await JsonDocument.ParseAsync(item.ContentStream);
  643. // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  644. // {
  645. // var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  646. // while (accounts.MoveNext())
  647. // {
  648. // JsonElement account = accounts.Current;
  649. // sname = account.GetProperty("name").ToString();
  650. // areaId = account.GetProperty("areaId").ToString();
  651. // }
  652. // }
  653. //}
  654. if (string.IsNullOrWhiteSpace(areaId)) {
  655. await _dingDing.SendBotMsg($"校本研修生成PDF时,区级id为空\n{msg}",GroupNames.成都开发測試群組);
  656. return;
  657. }
  658. foreach (string id in tIds)
  659. {
  660. List<Study> studies = new();
  661. StringBuilder stringBuilder = new StringBuilder();
  662. List<(List<string> tch, List<Dictionary<string, List<string>>> groupLists)> tchInfo = new();
  663. var query = $"SELECT top 1 c.tchLists,c.groupLists FROM c where array_contains(c.teacIds, '{id}') order by c.createTime desc";
  664. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
  665. {
  666. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  667. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  668. {
  669. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  670. while (accounts.MoveNext())
  671. {
  672. JsonElement account = accounts.Current;
  673. List<string> tchId = new();
  674. List<Dictionary<string, List<string>>> groupLists = new();
  675. if (account.TryGetProperty("tchLists", out JsonElement tchLists))
  676. {
  677. tchId = tchLists.ToObject<List<string>>();
  678. };
  679. if (account.TryGetProperty("groupLists", out JsonElement group))
  680. {
  681. groupLists = group.ToObject<List<Dictionary<string, List<string>>>>();
  682. };
  683. tchInfo.Add((tchId, groupLists));
  684. }
  685. }
  686. }
  687. string cname = string.Empty;
  688. string gname = string.Empty;
  689. foreach (var (tch, groupLists) in tchInfo)
  690. {
  691. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  692. if (groupLists.Count > 0)
  693. {
  694. var group = groupLists;
  695. foreach (var gp in group)
  696. {
  697. foreach (KeyValuePair<string, List<string>> pp in gp)
  698. {
  699. ps.Add((pp.Key, pp.Value));
  700. }
  701. }
  702. }
  703. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, tch, code, ps);
  704. gname = tchList.Where(c => c.id == id).FirstOrDefault().groupName;
  705. cname = tchList.Where(c => c.id == id).FirstOrDefault().name;
  706. }
  707. var queryInfo = $"select value(c) from c where (c.status<>404 or IS_DEFINED(c.status) = false) and array_contains(c.teacIds, '{id}')";
  708. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: queryInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
  709. {
  710. studies.Add(item);
  711. }
  712. List<string> details = new();
  713. foreach (Study study in studies)
  714. {
  715. var sresponse = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(study.id, new PartitionKey($"StudyRecord-{id}"));
  716. if (sresponse.Status == 200)
  717. {
  718. var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  719. StudyRecord record = json.ToObject<StudyRecord>();
  720. if (record.status == 1)
  721. {
  722. if (!string.IsNullOrEmpty(study.workId))
  723. {
  724. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(study.workId, new PartitionKey($"HomeworkRecord-{id}"));
  725. if (response.Status == 200)
  726. {
  727. var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd");
  728. var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd");
  729. string tname = string.Empty;
  730. List<string> setName = new();
  731. foreach (string setting in study.settings)
  732. {
  733. if (setting.Equals("sign"))
  734. {
  735. setName.Add("扫码签到");
  736. }
  737. else if (setting.Equals("hw"))
  738. {
  739. setName.Add("作业提交");
  740. }
  741. else if (setting.Equals("survey"))
  742. {
  743. setName.Add("问卷反馈");
  744. }
  745. else if (setting.Equals("exam"))
  746. {
  747. setName.Add("评测活动");
  748. }
  749. }
  750. switch (study.type)
  751. {
  752. case 1:
  753. tname = "信息化教学案例展示与分享";
  754. break;
  755. case 2:
  756. tname = "专家专题培训";
  757. break;
  758. case 3:
  759. tname = "同课同构";
  760. break;
  761. case 4:
  762. tname = "同课异构";
  763. break;
  764. case 5:
  765. tname = "校本2.0培训";
  766. break;
  767. case 6:
  768. tname = "自定义活动";
  769. break;
  770. };
  771. stringBuilder.Append($@"<tr>
  772. <td> {study.topic} </td>
  773. <td> {tname} </td >
  774. <td> {study.hour} </td >
  775. <td> {study.hour} </td >
  776. <td> {start} 到 {end} </td>
  777. <td>{study.desc}</td>
  778. <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
  779. <td> 已完成 </td >
  780. </tr> ");
  781. }
  782. else
  783. {
  784. continue;
  785. }
  786. }
  787. else
  788. {
  789. var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd");
  790. var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd");
  791. string tname = string.Empty;
  792. List<string> setName = new();
  793. foreach (string setting in study.settings)
  794. {
  795. if (setting.Equals("sign"))
  796. {
  797. setName.Add("扫码签到");
  798. }
  799. else if (setting.Equals("hw"))
  800. {
  801. setName.Add("作业提交");
  802. }
  803. else if (setting.Equals("survey"))
  804. {
  805. setName.Add("问卷反馈");
  806. }
  807. else if (setting.Equals("exam"))
  808. {
  809. setName.Add("评测活动");
  810. }
  811. }
  812. switch (study.type)
  813. {
  814. case 1:
  815. tname = "信息化教学案例展示与分享";
  816. break;
  817. case 2:
  818. tname = "专家专题培训";
  819. break;
  820. case 3:
  821. tname = "同课同构";
  822. break;
  823. case 4:
  824. tname = "同课异构";
  825. break;
  826. case 5:
  827. tname = "校本2.0培训";
  828. break;
  829. case 6:
  830. tname = "自定义活动";
  831. break;
  832. };
  833. stringBuilder.Append($@"<tr>
  834. <td> {study.topic} </td>
  835. <td> {tname} </td >
  836. <td> {study.hour} </td >
  837. <td> {study.hour} </td >
  838. <td> {start} 到 {end} </td>
  839. <td>{study.desc}</td>
  840. <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
  841. <td> 已完成 </td >
  842. </tr> ");
  843. }
  844. }
  845. else {
  846. continue;
  847. }
  848. }
  849. else {
  850. continue;
  851. }
  852. }
  853. string url = await StudyService.GenPdf(id, areaId, cname, sname, gname, stringBuilder.ToString(), _converter, _azureStorage,_dingDing);
  854. Azure.Response teacherTrainRes = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(id, new PartitionKey($"TeacherTrain-{code}"));
  855. if (teacherTrainRes.Status == 200) {
  856. TeacherTrain teacherTrain = JsonDocument.Parse(teacherTrainRes.Content).RootElement.Deserialize<TeacherTrain>();
  857. if (string.IsNullOrWhiteSpace(teacherTrain.offlineUrl)) {
  858. teacherTrain.offlineUrl = url;
  859. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(teacherTrain, id, new PartitionKey($"TeacherTrain-{code}"));
  860. }
  861. }
  862. }
  863. /*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}') )";
  864. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey($"Study-{code}") }))
  865. {
  866. studies.Add(item);
  867. }*/
  868. //(List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(element, null, null, _azureCosmos, _azureRedis);
  869. // string blob = await StudyService.GenPdf(cname,sname,gname,"", _converter);
  870. }
  871. catch (CosmosException ex)
  872. {
  873. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  874. }
  875. catch (Exception ex)
  876. {
  877. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  878. }
  879. }
  880. //更新學校產品一覽表
  881. //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
  882. [Function("Product")]
  883. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  884. {
  885. try
  886. {
  887. var jsonMsg = JsonDocument.Parse(msg);
  888. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  889. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  890. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  891. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  892. var client = _azureCosmos.GetCosmosClient();
  893. string strQuery = string.Empty;
  894. //取得所有學校產品
  895. ////序號
  896. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  897. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  898. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  899. {
  900. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  901. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  902. {
  903. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  904. {
  905. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  906. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  907. if (serialProd == null)
  908. {
  909. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  910. serialProdAdd.prodCode = serialInfo.prodCode;
  911. serialProdAdd.ids.Add(serialInfo.id);
  912. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  913. serialsProductSumOrg.Add(serialProdAdd);
  914. }
  915. else
  916. {
  917. if (!serialProd.ids.Contains(serialInfo.id))
  918. {
  919. serialProd.ids.Add(serialInfo.id);
  920. }
  921. serialProd.avaliable = serialProd.ids.Count;
  922. }
  923. }
  924. }
  925. }
  926. ////服務
  927. List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
  928. //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
  929. long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  930. string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
  931. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  932. {
  933. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  934. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  935. {
  936. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  937. {
  938. SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
  939. SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
  940. if (serviceProd == null)
  941. {
  942. SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
  943. serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
  944. serviceProdAdd.avaliable = 0;
  945. serviceProdAdd.ids.Add(servicePeriodInfo.id);
  946. serviceProdAdd.avaliable += servicePeriodInfo.number;
  947. serviceProdAdd.startDate = servicePeriodInfo.startDate;
  948. serviceProdAdd.endDate = servicePeriodInfo.endDate;
  949. servicesProductSumOrg.Add(serviceProdAdd);
  950. }
  951. else
  952. {
  953. serviceProd.ids = new List<string>();
  954. serviceProd.ids.Add(servicePeriodInfo.id);
  955. serviceProd.startDate = servicePeriodInfo.startDate;
  956. serviceProd.endDate = servicePeriodInfo.endDate;
  957. }
  958. }
  959. }
  960. }
  961. ////服務產品特別對應項
  962. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  963. bool updSchool = false; //是否變更學校基本資料
  964. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  965. int schoolDefaultSize = 1; //學校空間初始值:1
  966. if (!string.IsNullOrWhiteSpace(school.id))
  967. {
  968. if (servicesProductSumOrg.Count > 0)
  969. {
  970. foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
  971. {
  972. //更新學校空間
  973. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  974. {
  975. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  976. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  977. updSchool = true;
  978. chgSchSizeCnt++;
  979. }
  980. }
  981. }
  982. if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  983. {
  984. school.size = schoolDefaultSize;
  985. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  986. updSchool = false;
  987. }
  988. }
  989. //變更學校基本資料
  990. if (updSchool)
  991. {
  992. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  993. }
  994. ////硬體
  995. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  996. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  997. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  998. {
  999. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1000. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1001. {
  1002. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1003. {
  1004. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  1005. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  1006. if (hardProd == null)
  1007. {
  1008. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  1009. hardProdAdd.prodCode = hardInfo.prodCode;
  1010. hardProdAdd.model = hardInfo.model;
  1011. hardProdAdd.ids.Add(hardInfo.id);
  1012. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  1013. hardsProductSumOrg.Add(hardProdAdd);
  1014. }
  1015. else
  1016. {
  1017. if (!hardProd.ids.Contains(hardInfo.id))
  1018. {
  1019. hardProd.ids.Add(hardInfo.id);
  1020. }
  1021. hardProd.avaliable = hardProd.ids.Count;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. //更新學校產品一覽表
  1027. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  1028. prodSum.serial = serialsProductSumOrg;
  1029. prodSum.service = servicesProductSumOrg;
  1030. prodSum.hard = hardsProductSumOrg;
  1031. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  1032. }
  1033. catch (CosmosException ex)
  1034. {
  1035. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1036. }
  1037. catch (Exception ex)
  1038. {
  1039. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1040. }
  1041. }
  1042. /// <summary>
  1043. /// 批量复制文件
  1044. /// </summary>
  1045. /// <param name="msg"></param>
  1046. /// <returns></returns>
  1047. [Function("CopyStandardFile")]
  1048. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1049. {
  1050. try
  1051. {
  1052. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
  1053. var jsonMsg = JsonDocument.Parse(msg);
  1054. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  1055. //批量复制文件
  1056. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  1057. if (result == 200)
  1058. {
  1059. //发送消息实体
  1060. Notification notification = new Notification
  1061. {
  1062. hubName = "hita",
  1063. type = "msg",
  1064. from = $"BI:{_option.Location}:private",
  1065. to = bIBatchCopyFile.tmdIds,
  1066. label = $"{bIBatchCopyFile.codeKey}_finish",
  1067. body = new { location = $"{Environment.GetEnvironmentVariable("Option:Location")}", biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  1068. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1069. };
  1070. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1071. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1072. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1073. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1074. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1075. }
  1076. }
  1077. catch (Exception ex)
  1078. {
  1079. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1080. }
  1081. }
  1082. /// <summary>
  1083. /// 更新开课数据事件
  1084. /// </summary>
  1085. /// <param name="msg"></param>
  1086. /// <returns></returns>
  1087. [Function("LessonRecordEvent")]
  1088. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1089. {
  1090. JsonElement data = msg.ToObject<JsonElement>();
  1091. string scope = "";
  1092. string tmdid = "";
  1093. string lessonId;
  1094. string school;
  1095. string tbname;
  1096. string code;
  1097. string blobname;
  1098. List<LessonUpdate> updates = new List<LessonUpdate>();
  1099. //更新课堂记录
  1100. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  1101. {
  1102. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  1103. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  1104. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  1105. data.TryGetProperty("school", out JsonElement _school);
  1106. school = $"{_school}";
  1107. scope = $"{_scope}";
  1108. tmdid = $"{_tmdid}";
  1109. lessonId = $"{_lessonId}";
  1110. updates = _grant_types.ToObject<List<LessonUpdate>>();
  1111. }//创建课堂记录
  1112. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  1113. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  1114. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  1115. {
  1116. data.TryGetProperty("school", out JsonElement _school);
  1117. school = $"{_school}";
  1118. scope = $"{_scope}";
  1119. tmdid = $"{_tmdid}";
  1120. lessonId = $"{_id}";
  1121. updates.Add(new LessonUpdate { grant_type = "create" });
  1122. }//删除课堂记录
  1123. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  1124. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  1125. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  1126. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  1127. {
  1128. data.TryGetProperty("school", out JsonElement _dschool);
  1129. school = $"{_dschool}";
  1130. if ($"{_opt}".Equals("delete"))
  1131. {
  1132. scope = $"{_dscope}";
  1133. tmdid = $"{_dtmdid}";
  1134. lessonId = $"{_delete_id}";
  1135. updates.Add(new LessonUpdate { grant_type = "delete" });
  1136. }
  1137. else { return; }
  1138. }
  1139. else
  1140. {
  1141. return;
  1142. }
  1143. var client = _azureCosmos.GetCosmosClient();
  1144. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1145. {
  1146. blobname = $"{school}";
  1147. code = $"LessonRecord-{school}";
  1148. tbname = "School";
  1149. }
  1150. else if ($"{scope}".Equals("private"))
  1151. {
  1152. blobname = $"{tmdid}";
  1153. code = $"LessonRecord";
  1154. tbname = "Teacher";
  1155. }
  1156. else
  1157. {
  1158. return;
  1159. }
  1160. LessonDis lessonDis = new LessonDis();
  1161. List<LessonUpdate> msgs = new List<LessonUpdate>();
  1162. try
  1163. {
  1164. LessonRecord oldlessonRecord = null;
  1165. LessonRecord lessonRecord = null;
  1166. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1167. if (response.Status == 200)
  1168. {
  1169. var doc = JsonDocument.Parse(response.ContentStream);
  1170. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1171. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1172. }
  1173. else
  1174. {
  1175. lessonRecord = null;
  1176. }
  1177. bool isReplace = true;
  1178. if (updates.IsNotEmpty())
  1179. {
  1180. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  1181. foreach (LessonUpdate update in updates)
  1182. {
  1183. switch (update.grant_type)
  1184. {
  1185. //更新课堂时长
  1186. case "up-duration":
  1187. var duration = double.Parse($"{update.data}");
  1188. lessonRecord.duration = duration;
  1189. msgs.Add(update);
  1190. try
  1191. {
  1192. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  1193. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  1194. if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
  1195. {
  1196. var durationFile = double.Parse($"{_duration}");
  1197. if (duration < durationFile)
  1198. {
  1199. lessonRecord.duration = durationFile;
  1200. }
  1201. }
  1202. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
  1203. {
  1204. lessonRecord.hasVideo = 1;
  1205. }
  1206. }
  1207. catch (Exception ex)
  1208. {
  1209. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  1210. }
  1211. isReplace = true;
  1212. break;
  1213. //更新T分
  1214. case "up-tScore":
  1215. var tScore = int.Parse($"{update.data}");
  1216. lessonRecord.tScore = tScore;
  1217. msgs.Add(update);
  1218. break;
  1219. //更新课P分
  1220. case "up-pScore":
  1221. var pScore = int.Parse($"{update.data}");
  1222. lessonRecord.pScore = pScore;
  1223. msgs.Add(update);
  1224. break;
  1225. //更新 学生人数
  1226. case "up-mCount":
  1227. var mCount = int.Parse($"{update.data}");
  1228. lessonRecord.mCount = mCount;
  1229. msgs.Add(update);
  1230. break;
  1231. //更新 议课次数
  1232. case "up-techCount":
  1233. var techCount = int.Parse($"{update.data}");
  1234. lessonRecord.mCount = techCount;
  1235. msgs.Add(update);
  1236. break;
  1237. //更新 基础统计信息
  1238. case "up-base":
  1239. //如果有更新 则去读取/{_lessonId}/IES/base.json
  1240. try
  1241. {
  1242. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  1243. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  1244. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1245. if (lessonBase != null && lessonBase.summary != null)
  1246. {
  1247. //lessonRecord.name = lessonBase.summary.activityName;
  1248. lessonRecord.attendCount = lessonBase.summary.attendCount;
  1249. lessonRecord.clientCount = lessonBase.summary.clientCount;
  1250. lessonRecord.attendRate = lessonBase.summary.attendRate;
  1251. lessonRecord.groupCount = lessonBase.summary.groupCount;
  1252. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  1253. lessonRecord.collateCount = lessonBase.summary.collateCount;
  1254. lessonRecord.pushCount = lessonBase.summary.pushCount;
  1255. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  1256. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  1257. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  1258. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  1259. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  1260. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  1261. lessonRecord.examCount = lessonBase.summary.examCount;
  1262. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  1263. if (!string.IsNullOrWhiteSpace(lessonRecord.school)) {
  1264. lessonBase.student.ForEach(x => {
  1265. if (string.IsNullOrWhiteSpace(x.school))
  1266. {
  1267. x.school = lessonRecord.school;
  1268. }
  1269. });
  1270. }
  1271. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1272. //{
  1273. // clientSummaryList = lessonBase.report.clientSummaryList,
  1274. // students = lessonBase.student,
  1275. // name = lessonRecord.name,
  1276. // school = lessonRecord.school,
  1277. // id = lessonRecord.id,
  1278. // scope = lessonRecord.scope,
  1279. // tmdid = lessonRecord.tmdid,
  1280. // code = "LessonStudentRecord",
  1281. // pk = "LessonStudentRecord",
  1282. // courseId =lessonRecord.courseId,
  1283. // groupIds= lessonRecord.groupIds,
  1284. // periodId = lessonRecord.periodId,
  1285. // subjectId = lessonRecord.subjectId,
  1286. //};
  1287. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1288. }
  1289. //有上传 base.josn.
  1290. lessonRecord.upload = 1;
  1291. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1292. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _notificationService, _serviceBus, _azureStorage, _configuration);
  1293. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1294. Bloblog bloblog = new Bloblog
  1295. {
  1296. id = lessonRecord.id,
  1297. code = $"Bloblog-{blobname}",
  1298. name = lessonRecord.name,
  1299. pk = "Bloblog",
  1300. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1301. type = "records",
  1302. url = $"records/{_lessonId}",
  1303. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1304. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1305. size = size.HasValue ? size.Value : 0,
  1306. };
  1307. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1308. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1309. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1310. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1311. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1312. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1313. msgs.Add(update);
  1314. DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _notificationService, _serviceBus, _azureStorage, _configuration, lessonBase);
  1315. }
  1316. catch (Exception ex)
  1317. {
  1318. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1319. }
  1320. break;
  1321. //更新 时间线
  1322. case "up-TimeLine":
  1323. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1324. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1325. msgs.Add(update);
  1326. break;
  1327. //更新 课堂总览信息
  1328. case "up-ActivityInfo":
  1329. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1330. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1331. msgs.Add(update);
  1332. break;
  1333. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1334. isReplace = true;
  1335. msgs.Add(update);
  1336. break;
  1337. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1338. try
  1339. {
  1340. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1341. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1342. foreach (var record in records)
  1343. {
  1344. try
  1345. {
  1346. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1347. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1348. }
  1349. catch (Exception)
  1350. {
  1351. continue;
  1352. }
  1353. }
  1354. }
  1355. catch (Exception)
  1356. {
  1357. break;
  1358. }
  1359. isReplace = true;
  1360. msgs.Add(update);
  1361. break;
  1362. case "delete":
  1363. try
  1364. {
  1365. if (lessonRecord.expire > 0)
  1366. {
  1367. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1368. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1369. foreach (var record in records)
  1370. {
  1371. try
  1372. {
  1373. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1374. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1375. }
  1376. catch (Exception)
  1377. {
  1378. continue;
  1379. }
  1380. }
  1381. }
  1382. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1383. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1384. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1385. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1386. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1387. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1388. msgs.Add(update);
  1389. }
  1390. catch (CosmosException)
  1391. {
  1392. msgs.Add(update);
  1393. }
  1394. lessonRecord = null;
  1395. isReplace = false;
  1396. break;
  1397. case "create":
  1398. oldlessonRecord = null;
  1399. //处理课堂选用的课程信息
  1400. lessonRecord.show = teacher.lessonShow;
  1401. lessonRecord.upload = 0;
  1402. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1403. {
  1404. Course course = null;
  1405. try
  1406. {
  1407. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1408. if (cresponse.Status == 200)
  1409. {
  1410. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1411. course = cJson.ToObject<Course>();
  1412. }
  1413. else
  1414. {
  1415. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1416. if (sresponse.Status == 200)
  1417. {
  1418. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1419. course = cJson.ToObject<Course>();
  1420. }
  1421. else
  1422. {
  1423. course = null;
  1424. }
  1425. }
  1426. }
  1427. catch (Exception ex)
  1428. {
  1429. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1430. }
  1431. /*catch (CosmosException ex) when (ex.Status != 404)
  1432. {
  1433. try
  1434. {
  1435. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1436. }
  1437. catch (CosmosException e) when (e.Status != 404)
  1438. {
  1439. course = null;
  1440. }
  1441. }*/
  1442. if (course != null)
  1443. {
  1444. lessonRecord.periodId = course.period?.id;
  1445. lessonRecord.subjectId = course.subject?.id;
  1446. }
  1447. }
  1448. //处理课堂选用的名单
  1449. if (lessonRecord.groupIds.IsNotEmpty())
  1450. {
  1451. HashSet<string> grades = new HashSet<string>();
  1452. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1453. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1454. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1455. {
  1456. try
  1457. {
  1458. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1459. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1460. //年级算法
  1461. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1462. int? Count = period?.grades?.Count;
  1463. if (Count.HasValue)
  1464. {
  1465. int Day = DateTimeOffset.UtcNow.Day;
  1466. int Month = DateTimeOffset.UtcNow.Month;
  1467. int Year = DateTimeOffset.UtcNow.Year;
  1468. int start = int.Parse($"{Year}0901");
  1469. var se = period.semesters.Find(x => x.start == 1);
  1470. if (se == null)
  1471. {
  1472. se = period.semesters.First();
  1473. }
  1474. if (se != null)
  1475. {
  1476. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1477. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1478. start = int.Parse($"{Year}{sm}{sd}");
  1479. }
  1480. int curr = int.Parse(DateTimeOffset.UtcNow.ToString("yyyyMMdd"));
  1481. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  1482. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  1483. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  1484. int dis = start - curr;
  1485. foreach (int year in gplist.Select(x => x.year))
  1486. {
  1487. int grade;
  1488. if (dis > 0)
  1489. {
  1490. grade = (Year - year - 1) % Count.Value;
  1491. }
  1492. else
  1493. {
  1494. grade = (Year - year) % Count.Value;
  1495. }
  1496. grades.Add($"{grade}");
  1497. }
  1498. }
  1499. }
  1500. catch (CosmosException ex) when (ex.Status == 404)
  1501. {
  1502. }
  1503. catch (Exception ex)
  1504. {
  1505. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1506. }
  1507. }
  1508. lessonRecord.grade = grades.ToList();
  1509. }
  1510. //个人课例保存规则
  1511. try
  1512. {
  1513. if (scope.Equals("private"))
  1514. {
  1515. int lessonLimit = teacher.lessonLimit;
  1516. //获取已经使用的空间大小
  1517. long blobsize = 0;
  1518. var value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", tmdid);
  1519. if (value != default && !value.IsNullOrEmpty)
  1520. {
  1521. JsonElement record = value.ToString().ToObject<JsonElement>();
  1522. if (record.TryGetInt64(out blobsize))
  1523. {
  1524. }
  1525. }
  1526. int blobTotal = teacher.size;
  1527. blobTotal = teacher.size;
  1528. //累加学校分配的空间
  1529. foreach (var schoolInfo in teacher.schools)
  1530. {
  1531. SchoolTeacher st = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(lessonRecord.tmdid, new PartitionKey($"Teacher-{schoolInfo.schoolId}"));
  1532. blobTotal += st.size;
  1533. }
  1534. //剩余空间大于2G
  1535. if (blobTotal * 1073741824 - blobsize > 2147483648)
  1536. {
  1537. //大于2G 不限制
  1538. lessonLimit = -1;
  1539. }
  1540. if ( lessonLimit != -1)
  1541. {
  1542. HashSet<string> ids = new HashSet<string>();
  1543. //未定义的 以及过期时间小于等于0 的 课例
  1544. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  1545. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1546. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1547. {
  1548. ids.Add(item);
  1549. }
  1550. // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
  1551. //包含收藏的本人的个人课例
  1552. //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  1553. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1554. // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1555. //{
  1556. // ids.Add(item);
  1557. //}
  1558. //教师个人预设的,可以通过设置的方式增加
  1559. int limit = teacher.lessonLimit;
  1560. if (teacher.lessonLimit == 0)
  1561. {
  1562. //未设置的的采用系统设置的默认值50
  1563. limit = Constant.private_lesson_limit;
  1564. }
  1565. if (ids.Count >= limit)
  1566. {
  1567. LessonRecord lessonRecordExpire = null;
  1568. //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
  1569. string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
  1570. $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' order by c.startTime desc ";
  1571. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<LessonRecord>(
  1572. queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
  1573. {
  1574. lessonRecordExpire = item;break;
  1575. }
  1576. if (lessonRecordExpire != null) {
  1577. // 1-时间戳,7-时间戳
  1578. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1579. //暂定7天
  1580. var now = DateTimeOffset.UtcNow;
  1581. //剩余3天的通知
  1582. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1583. //result.Add(3, day3);
  1584. //剩余1天的通知
  1585. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  1586. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1587. //到期通知
  1588. //不到五点上传的课例,七天之后直接删除。
  1589. int addSecond = 0;
  1590. if (now.Hour > 5)
  1591. {
  1592. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1593. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  1594. //再加 00到05小时内的 随机秒数
  1595. Random rand = new Random();
  1596. int randInt = rand.Next(0, 18000);
  1597. addSecond += randInt;
  1598. }
  1599. else
  1600. {
  1601. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  1602. }
  1603. lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1604. //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
  1605. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
  1606. string biz = "expire";
  1607. Notification notification = new Notification
  1608. {
  1609. hubName = "hita",
  1610. type = "msg",
  1611. from = $"ies5:{Environment.GetEnvironmentVariable("Option:Location")}:private",
  1612. to = new List<string> { tmdid },
  1613. label = $"{biz}_lessonRecord",
  1614. body = new
  1615. {
  1616. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1617. biz = biz,
  1618. tmdid = teacher.id,
  1619. tmdname = teacher.name,
  1620. sid = lessonRecordExpire.id,
  1621. sname = lessonRecordExpire.name,
  1622. scope = scope,
  1623. stime = lessonRecordExpire.startTime,
  1624. expire = lessonRecordExpire.expire,
  1625. status = 1,
  1626. //day = Constant.private_lesson_expire,
  1627. time = now
  1628. }.ToJsonString(),
  1629. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1630. };
  1631. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1632. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1633. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1634. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1635. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1636. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1637. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
  1638. if (records.Count <= 0)
  1639. {
  1640. foreach (var item in result)
  1641. {
  1642. string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
  1643. //课堂的id ,
  1644. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1645. var message = new ServiceBusMessage(new
  1646. {
  1647. id = lessonRecordExpire.id,
  1648. progress = item.Key,
  1649. code = lessonRecordExpire.code,
  1650. scope = lessonRecordExpire.scope,
  1651. school = lessonRecordExpire.school,
  1652. opt = "delete",
  1653. expire = lessonRecordExpire.expire,
  1654. tmdid = tmdid,
  1655. tmdname = teacher.name,
  1656. name = lessonRecordExpire.name,
  1657. startTime = lessonRecordExpire.startTime,
  1658. tag = item.Value.tag
  1659. }.ToJsonString());
  1660. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1661. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1662. ChangeRecord changeRecord = new ChangeRecord
  1663. {
  1664. RowKey = lessonRecordExpire.id,
  1665. PartitionKey = PartitionKey,
  1666. sequenceNumber = start,
  1667. msgId = message.MessageId
  1668. };
  1669. await table.Save<ChangeRecord>(changeRecord);
  1670. }
  1671. }
  1672. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
  1673. }
  1674. }
  1675. }
  1676. else
  1677. {
  1678. //=-1 则表示不限制上传数量
  1679. }
  1680. }
  1681. }
  1682. catch (Exception e)
  1683. {
  1684. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1685. }
  1686. msgs.Add(update);
  1687. break;
  1688. default:
  1689. break;
  1690. }
  1691. }
  1692. //如果被删除则不能再被更新
  1693. if (isReplace)
  1694. {
  1695. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1696. }
  1697. //计算课堂更新前后的差值
  1698. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1699. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1700. }
  1701. }
  1702. catch (CosmosException e)
  1703. {
  1704. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1705. }
  1706. catch (Exception ex)
  1707. {
  1708. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1709. }
  1710. }
  1711. [Function("LessonRecordExpire")]
  1712. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1713. {
  1714. try
  1715. {
  1716. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1717. jsonMsg.TryGetProperty("id", out JsonElement id);
  1718. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1719. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1720. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1721. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1722. jsonMsg.TryGetProperty("name", out JsonElement name);
  1723. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1724. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1725. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1726. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1727. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  1728. var client = _azureCosmos.GetCosmosClient();
  1729. //处理到期删除
  1730. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  1731. {
  1732. string lessonId = $"{id}";
  1733. string tbname;
  1734. string school = $"{_school}";
  1735. string code = "";
  1736. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1737. {
  1738. code = $"LessonRecord-{school}";
  1739. tbname = "School";
  1740. }
  1741. else if ($"{scope}".Equals("private"))
  1742. {
  1743. code = $"LessonRecord";
  1744. tbname = "Teacher";
  1745. }
  1746. else
  1747. {
  1748. return;
  1749. }
  1750. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1751. if (response.Status == 200)
  1752. {
  1753. LessonRecord lessonRecord;
  1754. var doc = JsonDocument.Parse(response.ContentStream);
  1755. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1756. lessonRecord.status = 404;
  1757. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1758. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1759. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  1760. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1761. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1762. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  1763. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  1764. }
  1765. }
  1766. string biz = "expire";
  1767. Notification notification = new Notification
  1768. {
  1769. hubName = "hita",
  1770. type = "msg",
  1771. from = $"ies5:{_option.Location}:private",
  1772. to = new List<string> { $"{tmdid}" },
  1773. label = $"{biz}_lessonRecord",
  1774. body = new
  1775. {
  1776. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1777. biz = biz,
  1778. tmdid = $"{tmdid}",
  1779. tmdname = tmdname,
  1780. sid = $"{id}",
  1781. sname = $"{name}",
  1782. stime = long.Parse($"{startTime}"),
  1783. expire = long.Parse($"{expire}"),
  1784. status = 1,
  1785. //day = Constant.private_lesson_expire,
  1786. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1787. }.ToJsonString(),
  1788. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1789. };
  1790. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1791. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1792. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1793. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1794. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1795. }
  1796. catch (Exception ex)
  1797. {
  1798. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1799. }
  1800. }
  1801. /// <summary>
  1802. /// 完善课程变更
  1803. /// </summary>
  1804. /// <data msg>
  1805. /// CourseChange
  1806. ///// </data>
  1807. /// <param name="msg"></param>
  1808. /// <returns></returns>
  1809. [Function("Course")]
  1810. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1811. {
  1812. var client = _azureCosmos.GetCosmosClient();
  1813. try
  1814. {
  1815. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1816. var jsonMsg = JsonDocument.Parse(msg);
  1817. CourseChange courseChange = msg.ToObject<CourseChange>();
  1818. if (courseChange == null)
  1819. {
  1820. return;
  1821. }
  1822. foreach (var cls in courseChange.addClass)
  1823. {
  1824. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1825. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1826. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1827. foreach (var stu in addStudentsCls)
  1828. {
  1829. try
  1830. {
  1831. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1832. if (!stuCourse.Value.classId.Contains(cls))
  1833. {
  1834. stuCourse.Value.classId.Add(cls);
  1835. }
  1836. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1837. }
  1838. catch (CosmosException ex)
  1839. {
  1840. if (ex.Response.Status == 404)
  1841. {
  1842. var course = new StuCourse
  1843. {
  1844. id = courseChange.id,
  1845. scode = courseChange.code,
  1846. name = courseChange.name,
  1847. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1848. scope = courseChange.scope,
  1849. school = courseChange.school,
  1850. creatorId = courseChange.creatorId,
  1851. classId = new List<string> { cls },
  1852. pk = "StuCourse",
  1853. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1854. };
  1855. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1856. }
  1857. else
  1858. {
  1859. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1860. }
  1861. }
  1862. }
  1863. foreach (var tmd in addTmdidsCls)
  1864. {
  1865. try
  1866. {
  1867. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1868. if (!stuCourse.Value.classId.Contains(cls))
  1869. {
  1870. stuCourse.Value.classId.Add(cls);
  1871. }
  1872. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1873. }
  1874. catch (CosmosException ex)
  1875. {
  1876. if (ex.Response.Status == 404)
  1877. {
  1878. var course = new StuCourse
  1879. {
  1880. id = courseChange.id,
  1881. scode = courseChange.code,
  1882. name = courseChange.name,
  1883. code = $"StuCourse-{tmd.id}",
  1884. scope = courseChange.scope,
  1885. school = courseChange.school,
  1886. creatorId = courseChange.creatorId,
  1887. classId = new List<string> { cls },
  1888. pk = "StuCourse",
  1889. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1890. };
  1891. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1892. }
  1893. else
  1894. {
  1895. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1896. }
  1897. }
  1898. }
  1899. }
  1900. foreach (var list in courseChange.addList)
  1901. {
  1902. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1903. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1904. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1905. foreach (var stu in addStudentsCls)
  1906. {
  1907. try
  1908. {
  1909. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1910. if (!stuCourse.Value.stulist.Contains(list))
  1911. {
  1912. stuCourse.Value.stulist.Add(list);
  1913. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1914. }
  1915. }
  1916. catch (CosmosException ex)
  1917. {
  1918. if (ex.Response.Status == 404)
  1919. {
  1920. var course = new StuCourse
  1921. {
  1922. id = courseChange.id,
  1923. scode = courseChange.code,
  1924. name = courseChange.name,
  1925. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1926. scope = courseChange.scope,
  1927. school = courseChange.school,
  1928. creatorId = courseChange.creatorId,
  1929. stulist = new List<string> { list },
  1930. pk = "StuCourse",
  1931. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1932. };
  1933. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1934. }
  1935. else
  1936. {
  1937. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1938. }
  1939. }
  1940. }
  1941. foreach (var tmd in addTmdidsCls)
  1942. {
  1943. try
  1944. {
  1945. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1946. if (!stuCourse.Value.stulist.Contains(list))
  1947. {
  1948. stuCourse.Value.stulist.Add(list);
  1949. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1950. }
  1951. }
  1952. catch (CosmosException ex)
  1953. {
  1954. if (ex.Response.Status == 404)
  1955. {
  1956. var course = new StuCourse
  1957. {
  1958. id = courseChange.id,
  1959. scode = courseChange.code,
  1960. name = courseChange.name,
  1961. code = $"StuCourse-{tmd.id}",
  1962. scope = courseChange.scope,
  1963. school = courseChange.school,
  1964. creatorId = courseChange.creatorId,
  1965. stulist = new List<string> { list },
  1966. pk = "StuCourse",
  1967. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1968. };
  1969. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1970. }
  1971. else
  1972. {
  1973. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1974. }
  1975. }
  1976. }
  1977. }
  1978. foreach (var delCls in courseChange.delClass)
  1979. {
  1980. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1981. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1982. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1983. foreach (var stu in delStudentsCls)
  1984. {
  1985. try
  1986. {
  1987. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1988. if (stuCourse.Value.classId.Contains(delCls))
  1989. {
  1990. stuCourse.Value.classId.Remove(delCls);
  1991. }
  1992. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1993. {
  1994. //当两个列表都不存在时则直接删除
  1995. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1996. }
  1997. else
  1998. {
  1999. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2000. }
  2001. }
  2002. catch (CosmosException ex)
  2003. {
  2004. //await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2005. }
  2006. }
  2007. foreach (var tmd in delTmdidsCls)
  2008. {
  2009. try
  2010. {
  2011. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2012. if (stuCourse.Value.classId.Contains(delCls))
  2013. {
  2014. stuCourse.Value.classId.Remove(delCls);
  2015. }
  2016. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2017. {
  2018. //当两个列表都不存在时则直接删除
  2019. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2020. }
  2021. else
  2022. {
  2023. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2024. }
  2025. }
  2026. catch (CosmosException ex)
  2027. {
  2028. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2029. }
  2030. }
  2031. }
  2032. foreach (var delList in courseChange.delList)
  2033. {
  2034. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  2035. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  2036. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  2037. foreach (var stu in delStudentsCls)
  2038. {
  2039. try
  2040. {
  2041. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2042. if (stuCourse.Value.stulist.Contains(delList))
  2043. {
  2044. stuCourse.Value.stulist.Remove(delList);
  2045. }
  2046. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2047. {
  2048. //当两个列表都不存在时则直接删除
  2049. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2050. }
  2051. else
  2052. {
  2053. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2054. }
  2055. }
  2056. catch (CosmosException ex)
  2057. {
  2058. continue;
  2059. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2060. }
  2061. }
  2062. foreach (var tmd in delTmdidsCls)
  2063. {
  2064. try
  2065. {
  2066. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2067. if (stuCourse.Value.stulist.Contains(delList))
  2068. {
  2069. stuCourse.Value.stulist.Remove(delList);
  2070. }
  2071. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2072. {
  2073. //当两个列表都不存在时则直接删除
  2074. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2075. }
  2076. else
  2077. {
  2078. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2079. }
  2080. }
  2081. catch (CosmosException ex)
  2082. {
  2083. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2084. }
  2085. }
  2086. }
  2087. }
  2088. catch (Exception ex)
  2089. {
  2090. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2091. }
  2092. }
  2093. }
  2094. }