ActiveTaskTopic.cs 142 KB

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