IESServiceBusTrigger.cs 149 KB

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