ActiveTaskTopic.cs 142 KB

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