ActiveTaskTopic.cs 152 KB

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