ActiveTaskTopic.cs 136 KB

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