ActiveTaskTopic.cs 138 KB

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