ActiveTaskTopic.cs 140 KB

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