ActiveTaskTopic.cs 130 KB

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