IESServiceBusTrigger.cs 136 KB

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