IESServiceBusTrigger.cs 137 KB

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