ActiveTaskTopic.cs 141 KB

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