ActiveTaskTopic.cs 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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 code = "";
  621. element.TryGetProperty("Key", out JsonElement key);
  622. if (string.IsNullOrWhiteSpace($"{_code}"))
  623. {
  624. code = $"{key}";
  625. }
  626. else {
  627. code = $"{_code}";
  628. }
  629. if (string.IsNullOrWhiteSpace(code))
  630. {
  631. await _dingDing.SendBotMsg($"校本研修生成PDF时,学校id为空\n{msg}", GroupNames.成都开发測試群組);
  632. return;
  633. }
  634. string sname = string.Empty;
  635. string areaId = string.Empty;
  636. School school= await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{code}", new PartitionKey("Base"));
  637. sname = school.name;
  638. areaId = school.areaId;
  639. //var scquery = $"SELECT c.name,c.areaId from c where c.id = '{code}'";
  640. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: scquery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  641. //{
  642. // using var json = await JsonDocument.ParseAsync(item.ContentStream);
  643. // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  644. // {
  645. // var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  646. // while (accounts.MoveNext())
  647. // {
  648. // JsonElement account = accounts.Current;
  649. // sname = account.GetProperty("name").ToString();
  650. // areaId = account.GetProperty("areaId").ToString();
  651. // }
  652. // }
  653. //}
  654. if (string.IsNullOrWhiteSpace(areaId)) {
  655. await _dingDing.SendBotMsg($"校本研修生成PDF时,区级id为空\n{msg}",GroupNames.成都开发測試群組);
  656. return;
  657. }
  658. var blobclient = _azureStorage.GetBlobContainerClient($"teammodelos");
  659. foreach (string id in tIds)
  660. {
  661. List<Study> studies = new();
  662. StringBuilder stringBuilder = new StringBuilder();
  663. List<(List<string> tch, List<Dictionary<string, List<string>>> groupLists)> tchInfo = new();
  664. var query = $"SELECT top 1 c.tchLists,c.groupLists FROM c where array_contains(c.teacIds, '{id}') order by c.createTime desc";
  665. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
  666. {
  667. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  668. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  669. {
  670. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  671. while (accounts.MoveNext())
  672. {
  673. JsonElement account = accounts.Current;
  674. List<string> tchId = new();
  675. List<Dictionary<string, List<string>>> groupLists = new();
  676. if (account.TryGetProperty("tchLists", out JsonElement tchLists))
  677. {
  678. tchId = tchLists.ToObject<List<string>>();
  679. };
  680. if (account.TryGetProperty("groupLists", out JsonElement group))
  681. {
  682. groupLists = group.ToObject<List<Dictionary<string, List<string>>>>();
  683. };
  684. tchInfo.Add((tchId, groupLists));
  685. }
  686. }
  687. }
  688. string cname = string.Empty;
  689. string gname = string.Empty;
  690. foreach (var (tch, groupLists) in tchInfo)
  691. {
  692. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  693. if (groupLists.Count > 0)
  694. {
  695. var group = groupLists;
  696. foreach (var gp in group)
  697. {
  698. foreach (KeyValuePair<string, List<string>> pp in gp)
  699. {
  700. ps.Add((pp.Key, pp.Value));
  701. }
  702. }
  703. }
  704. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, tch, code, ps);
  705. if (tchList.Exists(c => c.id == id))
  706. {
  707. gname = tchList.Where(c => c.id == id).FirstOrDefault().groupName;
  708. cname = tchList.Where(c => c.id == id).FirstOrDefault().name;
  709. }
  710. }
  711. var queryInfo = $"select value(c) from c where (c.status<>404 or IS_DEFINED(c.status) = false) and array_contains(c.teacIds, '{id}')";
  712. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: queryInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
  713. {
  714. studies.Add(item);
  715. }
  716. List<string> details = new();
  717. foreach (Study study in studies)
  718. {
  719. var sresponse = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(study.id, new PartitionKey($"StudyRecord-{id}"));
  720. if (sresponse.Status == 200)
  721. {
  722. var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  723. StudyRecord record = json.ToObject<StudyRecord>();
  724. if (record.status == 1)
  725. {
  726. if (!string.IsNullOrEmpty(study.workId))
  727. {
  728. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(study.workId, new PartitionKey($"HomeworkRecord-{id}"));
  729. if (response.Status == 200)
  730. {
  731. var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd");
  732. var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd");
  733. string tname = string.Empty;
  734. List<string> setName = new();
  735. foreach (string setting in study.settings)
  736. {
  737. if (setting.Equals("sign"))
  738. {
  739. setName.Add("扫码签到");
  740. }
  741. else if (setting.Equals("hw"))
  742. {
  743. setName.Add("作业提交");
  744. }
  745. else if (setting.Equals("survey"))
  746. {
  747. setName.Add("问卷反馈");
  748. }
  749. else if (setting.Equals("exam"))
  750. {
  751. setName.Add("评测活动");
  752. }
  753. }
  754. switch (study.type)
  755. {
  756. case 1:
  757. tname = "信息化教学案例展示与分享";
  758. break;
  759. case 2:
  760. tname = "专家专题培训";
  761. break;
  762. case 3:
  763. tname = "同课同构";
  764. break;
  765. case 4:
  766. tname = "同课异构";
  767. break;
  768. case 5:
  769. tname = "校本2.0培训";
  770. break;
  771. case 6:
  772. tname = "自定义活动";
  773. break;
  774. };
  775. stringBuilder.Append($@"<tr>
  776. <td> {study.topic} </td>
  777. <td> {tname} </td >
  778. <td> {study.hour} </td >
  779. <td> {study.hour} </td >
  780. <td> {start} 到 {end} </td>
  781. <td>{study.desc}</td>
  782. <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
  783. <td> 已完成 </td >
  784. </tr> ");
  785. }
  786. else
  787. {
  788. continue;
  789. }
  790. }
  791. else
  792. {
  793. var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd");
  794. var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd");
  795. string tname = string.Empty;
  796. List<string> setName = new();
  797. foreach (string setting in study.settings)
  798. {
  799. if (setting.Equals("sign"))
  800. {
  801. setName.Add("扫码签到");
  802. }
  803. else if (setting.Equals("hw"))
  804. {
  805. setName.Add("作业提交");
  806. }
  807. else if (setting.Equals("survey"))
  808. {
  809. setName.Add("问卷反馈");
  810. }
  811. else if (setting.Equals("exam"))
  812. {
  813. setName.Add("评测活动");
  814. }
  815. }
  816. switch (study.type)
  817. {
  818. case 1:
  819. tname = "信息化教学案例展示与分享";
  820. break;
  821. case 2:
  822. tname = "专家专题培训";
  823. break;
  824. case 3:
  825. tname = "同课同构";
  826. break;
  827. case 4:
  828. tname = "同课异构";
  829. break;
  830. case 5:
  831. tname = "校本2.0培训";
  832. break;
  833. case 6:
  834. tname = "自定义活动";
  835. break;
  836. };
  837. stringBuilder.Append($@"<tr>
  838. <td> {study.topic} </td>
  839. <td> {tname} </td >
  840. <td> {study.hour} </td >
  841. <td> {study.hour} </td >
  842. <td> {start} 到 {end} </td>
  843. <td>{study.desc}</td>
  844. <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
  845. <td> 已完成 </td >
  846. </tr> ");
  847. }
  848. }
  849. else {
  850. continue;
  851. }
  852. }
  853. else {
  854. continue;
  855. }
  856. }
  857. string url = await StudyService.GenPdf(id, areaId, cname, sname, gname, stringBuilder.ToString(), _converter, _azureStorage,_dingDing);
  858. Azure.Response teacherTrainRes = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(id, new PartitionKey($"TeacherTrain-{code}"));
  859. if (teacherTrainRes.Status == 200) {
  860. TeacherTrain teacherTrain = JsonDocument.Parse(teacherTrainRes.Content).RootElement.Deserialize<TeacherTrain>();
  861. try {
  862. BlobDownloadInfo blobDownload = await blobclient.GetBlobClient(url).DownloadAsync(range: new HttpRange(0, 4 * 1048576), rangeGetContentHash: true);
  863. if (blobDownload.Details.ContentHash != null)
  864. {
  865. string hash = Md5Hash.GetbyteToString(blobDownload.Details.ContentHash);
  866. teacherTrain.offlineReport = new Attachment
  867. {
  868. hash = hash,
  869. url = url,
  870. blob = $"{blobclient.Uri}/{url}",
  871. extension = "pdf",
  872. name = $"{teacherTrain.nickname}-校本研修汇总报告.pdf",
  873. type = "doc",
  874. size = blobDownload.ContentLength
  875. };
  876. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(teacherTrain, id, new PartitionKey($"TeacherTrain-{code}"));
  877. }
  878. } catch {
  879. }
  880. }
  881. }
  882. /*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}') )";
  883. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey($"Study-{code}") }))
  884. {
  885. studies.Add(item);
  886. }*/
  887. //(List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(element, null, null, _azureCosmos, _azureRedis);
  888. // string blob = await StudyService.GenPdf(cname,sname,gname,"", _converter);
  889. }
  890. catch (CosmosException ex)
  891. {
  892. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  893. }
  894. catch (Exception ex)
  895. {
  896. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  897. }
  898. }
  899. //更新學校產品一覽表
  900. //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
  901. [Function("Product")]
  902. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  903. {
  904. try
  905. {
  906. var jsonMsg = JsonDocument.Parse(msg);
  907. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  908. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  909. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  910. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  911. var client = _azureCosmos.GetCosmosClient();
  912. string strQuery = string.Empty;
  913. //取得所有學校產品
  914. ////序號
  915. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  916. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  917. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  918. {
  919. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  920. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  921. {
  922. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  923. {
  924. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  925. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  926. if (serialProd == null)
  927. {
  928. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  929. serialProdAdd.prodCode = serialInfo.prodCode;
  930. serialProdAdd.ids.Add(serialInfo.id);
  931. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  932. serialsProductSumOrg.Add(serialProdAdd);
  933. }
  934. else
  935. {
  936. if (!serialProd.ids.Contains(serialInfo.id))
  937. {
  938. serialProd.ids.Add(serialInfo.id);
  939. }
  940. serialProd.avaliable = serialProd.ids.Count;
  941. }
  942. }
  943. }
  944. }
  945. ////服務
  946. List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
  947. //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
  948. long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  949. string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
  950. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  951. {
  952. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  953. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  954. {
  955. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  956. {
  957. SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
  958. SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
  959. if (serviceProd == null)
  960. {
  961. SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
  962. serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
  963. serviceProdAdd.avaliable = 0;
  964. serviceProdAdd.ids.Add(servicePeriodInfo.id);
  965. serviceProdAdd.avaliable += servicePeriodInfo.number;
  966. serviceProdAdd.startDate = servicePeriodInfo.startDate;
  967. serviceProdAdd.endDate = servicePeriodInfo.endDate;
  968. servicesProductSumOrg.Add(serviceProdAdd);
  969. }
  970. else
  971. {
  972. serviceProd.ids = new List<string>();
  973. serviceProd.ids.Add(servicePeriodInfo.id);
  974. serviceProd.startDate = servicePeriodInfo.startDate;
  975. serviceProd.endDate = servicePeriodInfo.endDate;
  976. }
  977. }
  978. }
  979. }
  980. ////服務產品特別對應項
  981. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  982. bool updSchool = false; //是否變更學校基本資料
  983. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  984. int schoolDefaultSize = 1; //學校空間初始值:1
  985. if (!string.IsNullOrWhiteSpace(school.id))
  986. {
  987. if (servicesProductSumOrg.Count > 0)
  988. {
  989. foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
  990. {
  991. //更新學校空間
  992. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  993. {
  994. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  995. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  996. updSchool = true;
  997. chgSchSizeCnt++;
  998. }
  999. }
  1000. }
  1001. if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  1002. {
  1003. school.size = schoolDefaultSize;
  1004. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  1005. updSchool = false;
  1006. }
  1007. }
  1008. //變更學校基本資料
  1009. if (updSchool)
  1010. {
  1011. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  1012. }
  1013. ////硬體
  1014. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  1015. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  1016. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  1017. {
  1018. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1019. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1020. {
  1021. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1022. {
  1023. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  1024. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  1025. if (hardProd == null)
  1026. {
  1027. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  1028. hardProdAdd.prodCode = hardInfo.prodCode;
  1029. hardProdAdd.model = hardInfo.model;
  1030. hardProdAdd.ids.Add(hardInfo.id);
  1031. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  1032. hardsProductSumOrg.Add(hardProdAdd);
  1033. }
  1034. else
  1035. {
  1036. if (!hardProd.ids.Contains(hardInfo.id))
  1037. {
  1038. hardProd.ids.Add(hardInfo.id);
  1039. }
  1040. hardProd.avaliable = hardProd.ids.Count;
  1041. }
  1042. }
  1043. }
  1044. }
  1045. //更新學校產品一覽表
  1046. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  1047. prodSum.serial = serialsProductSumOrg;
  1048. prodSum.service = servicesProductSumOrg;
  1049. prodSum.hard = hardsProductSumOrg;
  1050. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  1051. }
  1052. catch (CosmosException ex)
  1053. {
  1054. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1055. }
  1056. catch (Exception ex)
  1057. {
  1058. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\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("CopyStandardFile")]
  1067. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1068. {
  1069. try
  1070. {
  1071. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
  1072. var jsonMsg = JsonDocument.Parse(msg);
  1073. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  1074. //批量复制文件
  1075. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  1076. if (result == 200)
  1077. {
  1078. //发送消息实体
  1079. Notification notification = new Notification
  1080. {
  1081. hubName = "hita",
  1082. type = "msg",
  1083. from = $"BI:{_option.Location}:private",
  1084. to = bIBatchCopyFile.tmdIds,
  1085. label = $"{bIBatchCopyFile.codeKey}_finish",
  1086. body = new { location = $"{Environment.GetEnvironmentVariable("Option:Location")}", biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  1087. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1088. };
  1089. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1090. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1091. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1092. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1093. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1094. }
  1095. }
  1096. catch (Exception ex)
  1097. {
  1098. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1099. }
  1100. }
  1101. /// <summary>
  1102. /// 更新开课数据事件
  1103. /// </summary>
  1104. /// <param name="msg"></param>
  1105. /// <returns></returns>
  1106. [Function("LessonRecordEvent")]
  1107. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1108. {
  1109. JsonElement data = msg.ToObject<JsonElement>();
  1110. string scope = "";
  1111. string tmdid = "";
  1112. string lessonId;
  1113. string school;
  1114. string tbname;
  1115. string code;
  1116. string blobname;
  1117. List<LessonUpdate> updates = new List<LessonUpdate>();
  1118. //更新课堂记录
  1119. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  1120. {
  1121. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  1122. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  1123. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  1124. data.TryGetProperty("school", out JsonElement _school);
  1125. school = $"{_school}";
  1126. scope = $"{_scope}";
  1127. tmdid = $"{_tmdid}";
  1128. lessonId = $"{_lessonId}";
  1129. updates = _grant_types.ToObject<List<LessonUpdate>>();
  1130. }//创建课堂记录
  1131. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  1132. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  1133. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  1134. {
  1135. data.TryGetProperty("school", out JsonElement _school);
  1136. school = $"{_school}";
  1137. scope = $"{_scope}";
  1138. tmdid = $"{_tmdid}";
  1139. lessonId = $"{_id}";
  1140. updates.Add(new LessonUpdate { grant_type = "create" });
  1141. }//删除课堂记录
  1142. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  1143. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  1144. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  1145. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  1146. {
  1147. data.TryGetProperty("school", out JsonElement _dschool);
  1148. school = $"{_dschool}";
  1149. if ($"{_opt}".Equals("delete"))
  1150. {
  1151. scope = $"{_dscope}";
  1152. tmdid = $"{_dtmdid}";
  1153. lessonId = $"{_delete_id}";
  1154. updates.Add(new LessonUpdate { grant_type = "delete" });
  1155. }
  1156. else { return; }
  1157. }
  1158. else
  1159. {
  1160. return;
  1161. }
  1162. var client = _azureCosmos.GetCosmosClient();
  1163. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1164. {
  1165. blobname = $"{school}";
  1166. code = $"LessonRecord-{school}";
  1167. tbname = "School";
  1168. }
  1169. else if ($"{scope}".Equals("private"))
  1170. {
  1171. blobname = $"{tmdid}";
  1172. code = $"LessonRecord";
  1173. tbname = "Teacher";
  1174. }
  1175. else
  1176. {
  1177. return;
  1178. }
  1179. LessonDis lessonDis = new LessonDis();
  1180. List<LessonUpdate> msgs = new List<LessonUpdate>();
  1181. try
  1182. {
  1183. LessonRecord oldlessonRecord = null;
  1184. LessonRecord lessonRecord = null;
  1185. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1186. if (response.Status == 200)
  1187. {
  1188. var doc = JsonDocument.Parse(response.ContentStream);
  1189. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1190. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1191. }
  1192. else
  1193. {
  1194. lessonRecord = null;
  1195. }
  1196. bool isReplace = true;
  1197. if (updates.IsNotEmpty())
  1198. {
  1199. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  1200. foreach (LessonUpdate update in updates)
  1201. {
  1202. switch (update.grant_type)
  1203. {
  1204. //更新课堂时长
  1205. case "up-duration":
  1206. var duration = double.Parse($"{update.data}");
  1207. lessonRecord.duration = duration;
  1208. msgs.Add(update);
  1209. try
  1210. {
  1211. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  1212. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  1213. if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
  1214. {
  1215. var durationFile = double.Parse($"{_duration}");
  1216. if (duration < durationFile)
  1217. {
  1218. lessonRecord.duration = durationFile;
  1219. }
  1220. }
  1221. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
  1222. {
  1223. lessonRecord.hasVideo = 1;
  1224. }
  1225. }
  1226. catch (Exception ex)
  1227. {
  1228. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  1229. }
  1230. isReplace = true;
  1231. break;
  1232. //更新T分
  1233. case "up-tScore":
  1234. var tScore = int.Parse($"{update.data}");
  1235. lessonRecord.tScore = tScore;
  1236. msgs.Add(update);
  1237. break;
  1238. //更新课P分
  1239. case "up-pScore":
  1240. var pScore = int.Parse($"{update.data}");
  1241. lessonRecord.pScore = pScore;
  1242. msgs.Add(update);
  1243. break;
  1244. //更新 学生人数
  1245. case "up-mCount":
  1246. var mCount = int.Parse($"{update.data}");
  1247. lessonRecord.mCount = mCount;
  1248. msgs.Add(update);
  1249. break;
  1250. //更新 议课次数
  1251. case "up-techCount":
  1252. var techCount = int.Parse($"{update.data}");
  1253. lessonRecord.mCount = techCount;
  1254. msgs.Add(update);
  1255. break;
  1256. //更新 基础统计信息
  1257. case "up-base":
  1258. //如果有更新 则去读取/{_lessonId}/IES/base.json
  1259. try
  1260. {
  1261. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  1262. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  1263. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1264. if (lessonBase != null && lessonBase.summary != null)
  1265. {
  1266. //lessonRecord.name = lessonBase.summary.activityName;
  1267. lessonRecord.attendCount = lessonBase.summary.attendCount;
  1268. lessonRecord.clientCount = lessonBase.summary.clientCount;
  1269. lessonRecord.attendRate = lessonBase.summary.attendRate;
  1270. lessonRecord.groupCount = lessonBase.summary.groupCount;
  1271. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  1272. lessonRecord.collateCount = lessonBase.summary.collateCount;
  1273. lessonRecord.pushCount = lessonBase.summary.pushCount;
  1274. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  1275. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  1276. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  1277. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  1278. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  1279. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  1280. lessonRecord.examCount = lessonBase.summary.examCount;
  1281. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  1282. if (!string.IsNullOrWhiteSpace(lessonRecord.school)) {
  1283. lessonBase.student.ForEach(x => {
  1284. if (string.IsNullOrWhiteSpace(x.school))
  1285. {
  1286. x.school = lessonRecord.school;
  1287. }
  1288. });
  1289. }
  1290. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1291. //{
  1292. // clientSummaryList = lessonBase.report.clientSummaryList,
  1293. // students = lessonBase.student,
  1294. // name = lessonRecord.name,
  1295. // school = lessonRecord.school,
  1296. // id = lessonRecord.id,
  1297. // scope = lessonRecord.scope,
  1298. // tmdid = lessonRecord.tmdid,
  1299. // code = "LessonStudentRecord",
  1300. // pk = "LessonStudentRecord",
  1301. // courseId =lessonRecord.courseId,
  1302. // groupIds= lessonRecord.groupIds,
  1303. // periodId = lessonRecord.periodId,
  1304. // subjectId = lessonRecord.subjectId,
  1305. //};
  1306. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1307. }
  1308. //有上传 base.josn.
  1309. lessonRecord.upload = 1;
  1310. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1311. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _notificationService, _serviceBus, _azureStorage, _configuration);
  1312. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1313. Bloblog bloblog = new Bloblog
  1314. {
  1315. id = lessonRecord.id,
  1316. code = $"Bloblog-{blobname}",
  1317. name = lessonRecord.name,
  1318. pk = "Bloblog",
  1319. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1320. type = "records",
  1321. url = $"records/{_lessonId}",
  1322. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1323. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1324. size = size.HasValue ? size.Value : 0,
  1325. };
  1326. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1327. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1328. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1329. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1330. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1331. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1332. msgs.Add(update);
  1333. DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _notificationService, _serviceBus, _azureStorage, _configuration, lessonBase);
  1334. }
  1335. catch (Exception ex)
  1336. {
  1337. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1338. }
  1339. break;
  1340. //更新 时间线
  1341. case "up-TimeLine":
  1342. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1343. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1344. msgs.Add(update);
  1345. break;
  1346. //更新 课堂总览信息
  1347. case "up-ActivityInfo":
  1348. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1349. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1350. msgs.Add(update);
  1351. break;
  1352. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1353. isReplace = true;
  1354. msgs.Add(update);
  1355. break;
  1356. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1357. try
  1358. {
  1359. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1360. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1361. foreach (var record in records)
  1362. {
  1363. try
  1364. {
  1365. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1366. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1367. }
  1368. catch (Exception)
  1369. {
  1370. continue;
  1371. }
  1372. }
  1373. }
  1374. catch (Exception)
  1375. {
  1376. break;
  1377. }
  1378. isReplace = true;
  1379. msgs.Add(update);
  1380. break;
  1381. case "delete":
  1382. try
  1383. {
  1384. if (lessonRecord.expire > 0)
  1385. {
  1386. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1387. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1388. foreach (var record in records)
  1389. {
  1390. try
  1391. {
  1392. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1393. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1394. }
  1395. catch (Exception)
  1396. {
  1397. continue;
  1398. }
  1399. }
  1400. }
  1401. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1402. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1403. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1404. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1405. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1406. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1407. msgs.Add(update);
  1408. }
  1409. catch (CosmosException)
  1410. {
  1411. msgs.Add(update);
  1412. }
  1413. lessonRecord = null;
  1414. isReplace = false;
  1415. break;
  1416. case "create":
  1417. oldlessonRecord = null;
  1418. //处理课堂选用的课程信息
  1419. lessonRecord.show = teacher.lessonShow;
  1420. lessonRecord.upload = 0;
  1421. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1422. {
  1423. Course course = null;
  1424. try
  1425. {
  1426. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1427. if (cresponse.Status == 200)
  1428. {
  1429. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1430. course = cJson.ToObject<Course>();
  1431. }
  1432. else
  1433. {
  1434. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1435. if (sresponse.Status == 200)
  1436. {
  1437. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1438. course = cJson.ToObject<Course>();
  1439. }
  1440. else
  1441. {
  1442. course = null;
  1443. }
  1444. }
  1445. }
  1446. catch (Exception ex)
  1447. {
  1448. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1449. }
  1450. /*catch (CosmosException ex) when (ex.Status != 404)
  1451. {
  1452. try
  1453. {
  1454. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1455. }
  1456. catch (CosmosException e) when (e.Status != 404)
  1457. {
  1458. course = null;
  1459. }
  1460. }*/
  1461. if (course != null)
  1462. {
  1463. lessonRecord.periodId = course.period?.id;
  1464. lessonRecord.subjectId = course.subject?.id;
  1465. }
  1466. }
  1467. //处理课堂选用的名单
  1468. if (lessonRecord.groupIds.IsNotEmpty())
  1469. {
  1470. HashSet<string> grades = new HashSet<string>();
  1471. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1472. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1473. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1474. {
  1475. try
  1476. {
  1477. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1478. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1479. //年级算法
  1480. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1481. int? Count = period?.grades?.Count;
  1482. if (Count.HasValue)
  1483. {
  1484. int Day = DateTimeOffset.UtcNow.Day;
  1485. int Month = DateTimeOffset.UtcNow.Month;
  1486. int Year = DateTimeOffset.UtcNow.Year;
  1487. int start = int.Parse($"{Year}0901");
  1488. var se = period.semesters.Find(x => x.start == 1);
  1489. if (se == null)
  1490. {
  1491. se = period.semesters.First();
  1492. }
  1493. if (se != null)
  1494. {
  1495. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1496. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1497. start = int.Parse($"{Year}{sm}{sd}");
  1498. }
  1499. int curr = int.Parse(DateTimeOffset.UtcNow.ToString("yyyyMMdd"));
  1500. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  1501. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  1502. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  1503. int dis = start - curr;
  1504. foreach (int year in gplist.Select(x => x.year))
  1505. {
  1506. int grade;
  1507. if (dis > 0)
  1508. {
  1509. grade = (Year - year - 1) % Count.Value;
  1510. }
  1511. else
  1512. {
  1513. grade = (Year - year) % Count.Value;
  1514. }
  1515. grades.Add($"{grade}");
  1516. }
  1517. }
  1518. }
  1519. catch (CosmosException ex) when (ex.Status == 404)
  1520. {
  1521. }
  1522. catch (Exception ex)
  1523. {
  1524. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1525. }
  1526. }
  1527. lessonRecord.grade = grades.ToList();
  1528. }
  1529. //个人课例保存规则
  1530. try
  1531. {
  1532. if (scope.Equals("private"))
  1533. {
  1534. int lessonLimit = teacher.lessonLimit;
  1535. //获取已经使用的空间大小
  1536. long blobsize = 0;
  1537. var value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", tmdid);
  1538. if (value != default && !value.IsNullOrEmpty)
  1539. {
  1540. JsonElement record = value.ToString().ToObject<JsonElement>();
  1541. if (record.TryGetInt64(out blobsize))
  1542. {
  1543. }
  1544. }
  1545. int blobTotal = teacher.size;
  1546. blobTotal = teacher.size;
  1547. //累加学校分配的空间
  1548. foreach (var schoolInfo in teacher.schools)
  1549. {
  1550. SchoolTeacher st = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(lessonRecord.tmdid, new PartitionKey($"Teacher-{schoolInfo.schoolId}"));
  1551. blobTotal += st.size;
  1552. }
  1553. //剩余空间大于2G
  1554. if (blobTotal * 1073741824 - blobsize > 2147483648)
  1555. {
  1556. //大于2G 不限制
  1557. lessonLimit = -1;
  1558. }
  1559. if ( lessonLimit != -1)
  1560. {
  1561. HashSet<string> ids = new HashSet<string>();
  1562. //未定义的 以及过期时间小于等于0 的 课例
  1563. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  1564. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1565. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1566. {
  1567. ids.Add(item);
  1568. }
  1569. // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
  1570. //包含收藏的本人的个人课例
  1571. //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  1572. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1573. // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1574. //{
  1575. // ids.Add(item);
  1576. //}
  1577. //教师个人预设的,可以通过设置的方式增加
  1578. int limit = teacher.lessonLimit;
  1579. if (teacher.lessonLimit == 0)
  1580. {
  1581. //未设置的的采用系统设置的默认值50
  1582. limit = Constant.private_lesson_limit;
  1583. }
  1584. if (ids.Count >= limit)
  1585. {
  1586. LessonRecord lessonRecordExpire = null;
  1587. //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
  1588. string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
  1589. $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' order by c.startTime desc ";
  1590. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<LessonRecord>(
  1591. queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
  1592. {
  1593. lessonRecordExpire = item;break;
  1594. }
  1595. if (lessonRecordExpire != null) {
  1596. // 1-时间戳,7-时间戳
  1597. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1598. //暂定7天
  1599. var now = DateTimeOffset.UtcNow;
  1600. //剩余3天的通知
  1601. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1602. //result.Add(3, day3);
  1603. //剩余1天的通知
  1604. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  1605. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1606. //到期通知
  1607. //不到五点上传的课例,七天之后直接删除。
  1608. int addSecond = 0;
  1609. if (now.Hour > 5)
  1610. {
  1611. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1612. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  1613. //再加 00到05小时内的 随机秒数
  1614. Random rand = new Random();
  1615. int randInt = rand.Next(0, 18000);
  1616. addSecond += randInt;
  1617. }
  1618. else
  1619. {
  1620. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  1621. }
  1622. lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1623. //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
  1624. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
  1625. string biz = "expire";
  1626. Notification notification = new Notification
  1627. {
  1628. hubName = "hita",
  1629. type = "msg",
  1630. from = $"ies5:{Environment.GetEnvironmentVariable("Option:Location")}:private",
  1631. to = new List<string> { tmdid },
  1632. label = $"{biz}_lessonRecord",
  1633. body = new
  1634. {
  1635. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1636. biz = biz,
  1637. tmdid = teacher.id,
  1638. tmdname = teacher.name,
  1639. sid = lessonRecordExpire.id,
  1640. sname = lessonRecordExpire.name,
  1641. scope = scope,
  1642. stime = lessonRecordExpire.startTime,
  1643. expire = lessonRecordExpire.expire,
  1644. status = 1,
  1645. //day = Constant.private_lesson_expire,
  1646. time = now
  1647. }.ToJsonString(),
  1648. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1649. };
  1650. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1651. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1652. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1653. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1654. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1655. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1656. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
  1657. if (records.Count <= 0)
  1658. {
  1659. foreach (var item in result)
  1660. {
  1661. string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
  1662. //课堂的id ,
  1663. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1664. var message = new ServiceBusMessage(new
  1665. {
  1666. id = lessonRecordExpire.id,
  1667. progress = item.Key,
  1668. code = lessonRecordExpire.code,
  1669. scope = lessonRecordExpire.scope,
  1670. school = lessonRecordExpire.school,
  1671. opt = "delete",
  1672. expire = lessonRecordExpire.expire,
  1673. tmdid = tmdid,
  1674. tmdname = teacher.name,
  1675. name = lessonRecordExpire.name,
  1676. startTime = lessonRecordExpire.startTime,
  1677. tag = item.Value.tag
  1678. }.ToJsonString());
  1679. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1680. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1681. ChangeRecord changeRecord = new ChangeRecord
  1682. {
  1683. RowKey = lessonRecordExpire.id,
  1684. PartitionKey = PartitionKey,
  1685. sequenceNumber = start,
  1686. msgId = message.MessageId
  1687. };
  1688. await table.Save<ChangeRecord>(changeRecord);
  1689. }
  1690. }
  1691. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
  1692. }
  1693. }
  1694. }
  1695. else
  1696. {
  1697. //=-1 则表示不限制上传数量
  1698. }
  1699. }
  1700. }
  1701. catch (Exception e)
  1702. {
  1703. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1704. }
  1705. msgs.Add(update);
  1706. break;
  1707. default:
  1708. break;
  1709. }
  1710. }
  1711. //如果被删除则不能再被更新
  1712. if (isReplace)
  1713. {
  1714. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1715. }
  1716. //计算课堂更新前后的差值
  1717. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1718. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1719. }
  1720. }
  1721. catch (CosmosException e)
  1722. {
  1723. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1724. }
  1725. catch (Exception ex)
  1726. {
  1727. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1728. }
  1729. }
  1730. [Function("LessonRecordExpire")]
  1731. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1732. {
  1733. try
  1734. {
  1735. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1736. jsonMsg.TryGetProperty("id", out JsonElement id);
  1737. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1738. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1739. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1740. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1741. jsonMsg.TryGetProperty("name", out JsonElement name);
  1742. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1743. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1744. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1745. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1746. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  1747. var client = _azureCosmos.GetCosmosClient();
  1748. //处理到期删除
  1749. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  1750. {
  1751. string lessonId = $"{id}";
  1752. string tbname;
  1753. string school = $"{_school}";
  1754. string code = "";
  1755. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1756. {
  1757. code = $"LessonRecord-{school}";
  1758. tbname = "School";
  1759. }
  1760. else if ($"{scope}".Equals("private"))
  1761. {
  1762. code = $"LessonRecord";
  1763. tbname = "Teacher";
  1764. }
  1765. else
  1766. {
  1767. return;
  1768. }
  1769. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1770. if (response.Status == 200)
  1771. {
  1772. LessonRecord lessonRecord;
  1773. var doc = JsonDocument.Parse(response.ContentStream);
  1774. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1775. lessonRecord.status = 404;
  1776. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1777. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1778. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  1779. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1780. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1781. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  1782. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  1783. }
  1784. }
  1785. string biz = "expire";
  1786. Notification notification = new Notification
  1787. {
  1788. hubName = "hita",
  1789. type = "msg",
  1790. from = $"ies5:{_option.Location}:private",
  1791. to = new List<string> { $"{tmdid}" },
  1792. label = $"{biz}_lessonRecord",
  1793. body = new
  1794. {
  1795. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1796. biz = biz,
  1797. tmdid = $"{tmdid}",
  1798. tmdname = tmdname,
  1799. sid = $"{id}",
  1800. sname = $"{name}",
  1801. stime = long.Parse($"{startTime}"),
  1802. expire = long.Parse($"{expire}"),
  1803. status = 1,
  1804. //day = Constant.private_lesson_expire,
  1805. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1806. }.ToJsonString(),
  1807. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1808. };
  1809. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1810. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1811. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1812. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1813. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1814. }
  1815. catch (Exception ex)
  1816. {
  1817. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1818. }
  1819. }
  1820. /// <summary>
  1821. /// 完善课程变更
  1822. /// </summary>
  1823. /// <data msg>
  1824. /// CourseChange
  1825. ///// </data>
  1826. /// <param name="msg"></param>
  1827. /// <returns></returns>
  1828. [Function("Course")]
  1829. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1830. {
  1831. var client = _azureCosmos.GetCosmosClient();
  1832. try
  1833. {
  1834. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1835. var jsonMsg = JsonDocument.Parse(msg);
  1836. CourseChange courseChange = msg.ToObject<CourseChange>();
  1837. if (courseChange == null)
  1838. {
  1839. return;
  1840. }
  1841. foreach (var cls in courseChange.addClass)
  1842. {
  1843. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1844. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1845. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1846. foreach (var stu in addStudentsCls)
  1847. {
  1848. try
  1849. {
  1850. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1851. if (!stuCourse.Value.classId.Contains(cls))
  1852. {
  1853. stuCourse.Value.classId.Add(cls);
  1854. }
  1855. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1856. }
  1857. catch (CosmosException ex)
  1858. {
  1859. if (ex.Response.Status == 404)
  1860. {
  1861. var course = new StuCourse
  1862. {
  1863. id = courseChange.id,
  1864. scode = courseChange.code,
  1865. name = courseChange.name,
  1866. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1867. scope = courseChange.scope,
  1868. school = courseChange.school,
  1869. creatorId = courseChange.creatorId,
  1870. classId = new List<string> { cls },
  1871. pk = "StuCourse",
  1872. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1873. };
  1874. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1875. }
  1876. else
  1877. {
  1878. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1879. }
  1880. }
  1881. }
  1882. foreach (var tmd in addTmdidsCls)
  1883. {
  1884. try
  1885. {
  1886. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1887. if (!stuCourse.Value.classId.Contains(cls))
  1888. {
  1889. stuCourse.Value.classId.Add(cls);
  1890. }
  1891. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1892. }
  1893. catch (CosmosException ex)
  1894. {
  1895. if (ex.Response.Status == 404)
  1896. {
  1897. var course = new StuCourse
  1898. {
  1899. id = courseChange.id,
  1900. scode = courseChange.code,
  1901. name = courseChange.name,
  1902. code = $"StuCourse-{tmd.id}",
  1903. scope = courseChange.scope,
  1904. school = courseChange.school,
  1905. creatorId = courseChange.creatorId,
  1906. classId = new List<string> { cls },
  1907. pk = "StuCourse",
  1908. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1909. };
  1910. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1911. }
  1912. else
  1913. {
  1914. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1915. }
  1916. }
  1917. }
  1918. }
  1919. foreach (var list in courseChange.addList)
  1920. {
  1921. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1922. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1923. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1924. foreach (var stu in addStudentsCls)
  1925. {
  1926. try
  1927. {
  1928. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1929. if (!stuCourse.Value.stulist.Contains(list))
  1930. {
  1931. stuCourse.Value.stulist.Add(list);
  1932. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1933. }
  1934. }
  1935. catch (CosmosException ex)
  1936. {
  1937. if (ex.Response.Status == 404)
  1938. {
  1939. var course = new StuCourse
  1940. {
  1941. id = courseChange.id,
  1942. scode = courseChange.code,
  1943. name = courseChange.name,
  1944. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1945. scope = courseChange.scope,
  1946. school = courseChange.school,
  1947. creatorId = courseChange.creatorId,
  1948. stulist = new List<string> { list },
  1949. pk = "StuCourse",
  1950. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1951. };
  1952. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1953. }
  1954. else
  1955. {
  1956. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1957. }
  1958. }
  1959. }
  1960. foreach (var tmd in addTmdidsCls)
  1961. {
  1962. try
  1963. {
  1964. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1965. if (!stuCourse.Value.stulist.Contains(list))
  1966. {
  1967. stuCourse.Value.stulist.Add(list);
  1968. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1969. }
  1970. }
  1971. catch (CosmosException ex)
  1972. {
  1973. if (ex.Response.Status == 404)
  1974. {
  1975. var course = new StuCourse
  1976. {
  1977. id = courseChange.id,
  1978. scode = courseChange.code,
  1979. name = courseChange.name,
  1980. code = $"StuCourse-{tmd.id}",
  1981. scope = courseChange.scope,
  1982. school = courseChange.school,
  1983. creatorId = courseChange.creatorId,
  1984. stulist = new List<string> { list },
  1985. pk = "StuCourse",
  1986. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1987. };
  1988. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1989. }
  1990. else
  1991. {
  1992. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1993. }
  1994. }
  1995. }
  1996. }
  1997. foreach (var delCls in courseChange.delClass)
  1998. {
  1999. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  2000. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  2001. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  2002. foreach (var stu in delStudentsCls)
  2003. {
  2004. try
  2005. {
  2006. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2007. if (stuCourse.Value.classId.Contains(delCls))
  2008. {
  2009. stuCourse.Value.classId.Remove(delCls);
  2010. }
  2011. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2012. {
  2013. //当两个列表都不存在时则直接删除
  2014. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2015. }
  2016. else
  2017. {
  2018. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2019. }
  2020. }
  2021. catch (CosmosException ex)
  2022. {
  2023. //await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2024. }
  2025. }
  2026. foreach (var tmd in delTmdidsCls)
  2027. {
  2028. try
  2029. {
  2030. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2031. if (stuCourse.Value.classId.Contains(delCls))
  2032. {
  2033. stuCourse.Value.classId.Remove(delCls);
  2034. }
  2035. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2036. {
  2037. //当两个列表都不存在时则直接删除
  2038. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2039. }
  2040. else
  2041. {
  2042. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2043. }
  2044. }
  2045. catch (CosmosException ex)
  2046. {
  2047. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2048. }
  2049. }
  2050. }
  2051. foreach (var delList in courseChange.delList)
  2052. {
  2053. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  2054. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  2055. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  2056. foreach (var stu in delStudentsCls)
  2057. {
  2058. try
  2059. {
  2060. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2061. if (stuCourse.Value.stulist.Contains(delList))
  2062. {
  2063. stuCourse.Value.stulist.Remove(delList);
  2064. }
  2065. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2066. {
  2067. //当两个列表都不存在时则直接删除
  2068. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2069. }
  2070. else
  2071. {
  2072. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2073. }
  2074. }
  2075. catch (CosmosException ex)
  2076. {
  2077. continue;
  2078. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2079. }
  2080. }
  2081. foreach (var tmd in delTmdidsCls)
  2082. {
  2083. try
  2084. {
  2085. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2086. if (stuCourse.Value.stulist.Contains(delList))
  2087. {
  2088. stuCourse.Value.stulist.Remove(delList);
  2089. }
  2090. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2091. {
  2092. //当两个列表都不存在时则直接删除
  2093. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2094. }
  2095. else
  2096. {
  2097. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2098. }
  2099. }
  2100. catch (CosmosException ex)
  2101. {
  2102. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2103. }
  2104. }
  2105. }
  2106. }
  2107. catch (Exception ex)
  2108. {
  2109. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2110. }
  2111. }
  2112. }
  2113. }