IESServiceBusTrigger.cs 141 KB

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