ActiveTaskTopic.cs 166 KB

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