ActiveTaskTopic.cs 142 KB

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