ActiveTaskTopic.cs 134 KB

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