IESServiceBusTrigger.cs 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165
  1. using System;
  2. using System.Threading.Tasks;
  3. using Azure.Messaging.ServiceBus;
  4. using DinkToPdf.Contracts;
  5. using Microsoft.Azure.Functions.Worker;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.Logging;
  8. using TEAMModelOS.SDK.DI;
  9. using TEAMModelOS.SDK;
  10. using TEAMModelOS.Models;
  11. using Microsoft.Extensions.Options;
  12. using static Microsoft.Azure.Amqp.Serialization.SerializableType;
  13. using System.Text.Json;
  14. using TEAMModelOS.SDK.Models;
  15. using Microsoft.Azure.Cosmos;
  16. using TEAMModelOS.SDK.Extension;
  17. using TEAMModelOS.SDK.Models.Cosmos;
  18. using TEAMModelOS.SDK.Models.Cosmos;
  19. using StackExchange.Redis;
  20. using static TEAMModelOS.SDK.StatisticsService;
  21. using Azure;
  22. using TEAMModelOS.SDK.Models.Dtos;
  23. using TEAMModelOS.SDK.Models.Service.BI;
  24. using TEAMModelOS.SDK.Models.Service;
  25. using TEAMModelOS.SDK.Services;
  26. using Azure.Storage.Blobs.Models;
  27. using static TEAMModelOS.SDK.Models.Service.LessonService;
  28. using System.Text;
  29. using Microsoft.Azure.Cosmos.Linq;
  30. using System.Net.Http.Json;
  31. using System.Threading;
  32. using System.Text.Json.Nodes;
  33. using System.Web;
  34. using Azure.Storage.Blobs;
  35. using static TEAMModelOS.SDK.CoreAPIHttpService;
  36. using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
  37. using System.Net;
  38. using Newtonsoft.Json;
  39. using System.Security.Policy;
  40. using System.Net.Http.Headers;
  41. using Microsoft.AspNetCore.Hosting;
  42. using Newtonsoft.Json.Linq;
  43. using HTEX.Lib.ETL.Lesson;
  44. using System.Globalization;
  45. using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
  46. using static TEAMModelOS.SDK.Models.Service.SystemService;
  47. using System.Xml;
  48. using System.Reflection;
  49. using System.Text.RegularExpressions;
  50. using Microsoft.Azure.Cosmos.Core;
  51. namespace TEAMModelOS.Function
  52. {
  53. public class IESServiceBusTrigger
  54. {
  55. private readonly ILogger<IESServiceBusTrigger> _logger;
  56. private readonly int psize = 20;
  57. private readonly AzureCosmosFactory _azureCosmos;
  58. private readonly DingDing _dingDing;
  59. private readonly AzureStorageFactory _azureStorage;
  60. private readonly AzureRedisFactory _azureRedis;
  61. private readonly AzureServiceBusFactory _serviceBus;
  62. private readonly Option _option;
  63. private readonly CoreAPIHttpService _coreAPIHttpService;
  64. private readonly IConfiguration _configuration;
  65. // private readonly IConverter _converter;
  66. private readonly SnowflakeId _snowflakeId;
  67. private readonly HttpTrigger _httpTrigger;
  68. private readonly BackgroundWorkerQueue _backgroundWorkerQueue;
  69. private readonly IHttpClientFactory _httpClient;
  70. private readonly IWebHostEnvironment _environment;
  71. public IESServiceBusTrigger(ILogger<IESServiceBusTrigger> logger, HttpTrigger httpTrigger, SnowflakeId snowflakeId, CoreAPIHttpService coreAPIHttpService,
  72. AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis,
  73. AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option,
  74. IConfiguration configuration, BackgroundWorkerQueue backgroundWorkerQueue, IHttpClientFactory httpClient, IWebHostEnvironment hostingEnvironment)
  75. {
  76. _logger = logger;
  77. _azureCosmos = azureCosmos;
  78. _dingDing = dingDing;
  79. _azureStorage = azureStorage;
  80. _azureRedis = azureRedis;
  81. _serviceBus = serviceBus;
  82. _option = option?.Value;
  83. _configuration = configuration;
  84. _coreAPIHttpService = coreAPIHttpService;
  85. _snowflakeId = snowflakeId;
  86. _httpTrigger = httpTrigger;
  87. _backgroundWorkerQueue = backgroundWorkerQueue;
  88. _httpClient=httpClient;
  89. _environment = hostingEnvironment;
  90. }
  91. [Function("GenPdf")]
  92. public async Task GenPdfFunc([ServiceBusTrigger("%Azure:ServiceBus:GenPdfQueue%", Connection = "Azure:ServiceBus:ConnectionString", IsBatched = false)] ServiceBusReceivedMessage message,
  93. ServiceBusMessageActions messageActions)
  94. {
  95. //https://github.com/aafgani/AzFuncWithServiceBus/blob/a0da42f59b5fc45655b73b85bae932e84520db70/ServiceBusTriggerFunction/host.json
  96. // messageHandlerOptions 设置
  97. // https://dotblogs.com.tw/yc421206/2013/04/25/102300 // C# 原子操作。Interlocked
  98. // ConcurrentQueue http://t.zoukankan.com/hohoa-p-12622459.html
  99. // await messageActions.RenewMessageLockAsync(message);
  100. long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  101. Console.WriteLine($"開始:{time}");
  102. string apiUri = "http://52.130.252.100:13000";
  103. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  104. _logger.LogInformation("Message ID: {id}", message.MessageId);
  105. _logger.LogInformation("Message Body: {body}", message.Body);
  106. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  107. var json = JsonDocument.Parse(message.Body).RootElement;
  108. try
  109. {
  110. switch (true)
  111. {
  112. case bool when json.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("OfflineRecord"):
  113. //处理教师线下研修报告的生成。
  114. //await GenOfflineRecordPdf(element, msg);
  115. break;
  116. case bool when json.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("ArtStudentPdf"):
  117. json.TryGetProperty("studentIds", out JsonElement _studentIds);
  118. json.TryGetProperty("artId", out JsonElement _artId);
  119. json.TryGetProperty("schoolCode", out JsonElement _schoolId);
  120. json.TryGetProperty("headLang", out JsonElement headLang);
  121. List<string> studentIds = _studentIds.ToObject<List<string>>();
  122. var data = await GenPDFService.GenArtStudentPdf(_azureRedis, _azureCosmos, _coreAPIHttpService, _dingDing, _azureStorage,_configuration, studentIds,$"{_artId}",$"{_schoolId}",$"{headLang}");
  123. await GenPDFService. PushScreenTask(_azureRedis, _configuration, $"{_artId}",data. art,data. studentPdfs,_httpClient,_dingDing);
  124. break;
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  130. }
  131. finally
  132. { // Complete the message
  133. await messageActions.CompleteMessageAsync(message);
  134. }
  135. }
  136. // [Function("GenPDF")]
  137. public async Task Run(
  138. [ServiceBusTrigger("dep-genpdf", Connection = "Azure:ServiceBus:ConnectionString" , IsBatched =false) ]
  139. ServiceBusReceivedMessage message,
  140. ServiceBusMessageActions messageActions)
  141. {
  142. // await messageActions.RenewMessageLockAsync(message);
  143. long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  144. Console.WriteLine($"開始:{time}");
  145. string apiUri = "http://52.130.252.100:13000";
  146. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  147. _logger.LogInformation("Message ID: {id}", message.MessageId);
  148. _logger.LogInformation("Message Body: {body}", message.Body);
  149. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  150. var json = JsonDocument.Parse(message.Body);
  151. try
  152. {
  153. // Complete the message
  154. PDFGenQueue genQueueData = json.RootElement.ToObject<PDFGenQueue>();
  155. RedisValue redisValue= await _azureRedis.GetRedisClient(8).HashGetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id);
  156. PDFGenRedis genRedis = null ;
  157. if (redisValue!=default)
  158. {
  159. genRedis = redisValue.ToString().ToObject<PDFGenRedis>();
  160. //计算等待了多久的时间才开始生成。
  161. var wait = now- genRedis.join;
  162. genRedis.wait = wait;
  163. genRedis.status= 1;
  164. await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
  165. var client = _httpClient.CreateClient();
  166. ///再加5秒
  167. client.Timeout= TimeSpan.FromMilliseconds(genQueueData.timeout+ genQueueData.delay+5000);
  168. try
  169. {
  170. string urlpdf =$"{apiUri}/api/pdf";
  171. string jsonElement= new {
  172. pageUrl = genQueueData.pageUrl,
  173. timeout = genQueueData.timeout,
  174. delay = genQueueData.delay,
  175. checkPageCompleteJs = genQueueData.checkPageCompleteJs
  176. }.ToJsonString();
  177. var request = new HttpRequestMessage
  178. {
  179. Method = new HttpMethod("POST"),
  180. RequestUri = new Uri(urlpdf),
  181. Content = new StringContent(jsonElement)
  182. };
  183. var mediaTypeHeader = new MediaTypeHeaderValue("application/json")
  184. {
  185. CharSet = "UTF-8"
  186. };
  187. request.Content.Headers.ContentType = mediaTypeHeader;
  188. HttpResponseMessage responseMessage = await client.SendAsync(request);
  189. if (responseMessage.IsSuccessStatusCode)
  190. {
  191. string content = await responseMessage.Content.ReadAsStringAsync();
  192. JsonNode jsonNode = content.ToObject<JsonNode>();
  193. var code = jsonNode["code"];
  194. var file = jsonNode["data"]?["file"];
  195. if (code!=null && $"{code}".Equals("0") && file!= null && !string.IsNullOrWhiteSpace($"{file}"))
  196. {
  197. try
  198. {
  199. Stream stream = await client.GetStreamAsync($"{apiUri}/{file}");
  200. Uri uri = new Uri(genQueueData.pageUrl);
  201. var query = HttpUtility.ParseQueryString(uri.Query);
  202. string? url = query["url"];
  203. if (!string.IsNullOrWhiteSpace(url))
  204. {
  205. url= HttpUtility.UrlDecode(url);
  206. uri = new Uri(url);
  207. string host = uri.Host;
  208. var blobServiceClient = _azureStorage.GetBlobServiceClient();
  209. if (blobServiceClient.Uri.Host.Equals(host))
  210. {
  211. // 获取容器名,它是路径的第一个部分
  212. string containerName = uri.Segments[1].TrimEnd('/');
  213. // 获取文件的完整同级目录,这是文件路径中除了文件名和扩展名之外的部分
  214. // 由于文件名是路径的最后一个部分,我们可以通过连接除了最后一个部分之外的所有部分来获取目录路径
  215. string directoryPath = string.Join("", uri.Segments, 2, uri.Segments.Length - 3);
  216. string? fileName = Path.GetFileNameWithoutExtension(uri.AbsolutePath);
  217. string blobPath = $"{directoryPath}{fileName}.pdf";
  218. var blockBlob = _azureStorage.GetBlobContainerClient(containerName).GetBlobClient(blobPath);
  219. string content_type = "application/octet-stream";
  220. ContentTypeDict.dict.TryGetValue(".pdf", out string? contenttype);
  221. if (!string.IsNullOrEmpty(contenttype))
  222. {
  223. content_type = contenttype;
  224. }
  225. await blockBlob.UploadAsync(stream, true);
  226. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  227. genRedis.blob= blockBlob.Name;
  228. genRedis.status=2;
  229. }
  230. else
  231. {
  232. genRedis.status=6;
  233. }
  234. }
  235. else
  236. {
  237. genRedis.status=6;
  238. }
  239. }
  240. catch (Exception ex)
  241. {
  242. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  243. genRedis.status=6;
  244. }
  245. }
  246. else
  247. {
  248. if (code!= null && $"{code}".Equals("99999"))
  249. {
  250. genRedis.status= 4;
  251. }
  252. else {
  253. genRedis.status= 3;
  254. }
  255. }
  256. }
  257. else {
  258. genRedis.status= 3;
  259. }
  260. }
  261. catch (TaskCanceledException ex)
  262. {
  263. if (ex.CancellationToken.IsCancellationRequested)
  264. {
  265. // Console.WriteLine("请求被取消。");
  266. genRedis.status= 5;
  267. }
  268. else
  269. {
  270. //Console.WriteLine("请求超时。");
  271. genRedis.status= 4;
  272. }
  273. }
  274. catch (Exception ex)
  275. {
  276. genRedis.status=3;
  277. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  278. }
  279. }
  280. else
  281. {
  282. genRedis= new PDFGenRedis { id =genQueueData.id, status= 5, cost=0, join=now, wait=0,name= genQueueData .name };
  283. //被取消的
  284. }
  285. long nowNew = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  286. genRedis.cost=nowNew-now;
  287. await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
  288. //如果全部 生成,需要发送通知
  289. HashEntry[] datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"PDFGen:{genQueueData.sessionId}");
  290. List<PDFGenRedis> dbgenRedis = new List<PDFGenRedis>();
  291. List<string> notifyUsers = new List<string>();
  292. string taskName = string.Empty;
  293. string taskType = string.Empty;
  294. if (datas!= null && datas.Length > 0)
  295. {
  296. foreach (var item in datas)
  297. {
  298. if (!$"{item.Name}".Contains("notifyUsers"))
  299. {
  300. dbgenRedis.Add(item.Value.ToString().ToObject<PDFGenRedis>());
  301. }
  302. else
  303. {
  304. var jsonData = item.Value.ToString().ToObject<JsonElement>();
  305. notifyUsers= jsonData.GetProperty("notifyUsers").ToObject<List<string>>();
  306. taskType = jsonData.GetProperty("taskType").ToString();
  307. taskName = jsonData.GetProperty("taskName").ToString();
  308. }
  309. }
  310. }
  311. if (notifyUsers.IsNotEmpty())
  312. {
  313. string lang = Environment.GetEnvironmentVariable("Option:Location")!.Contains("China") ? "zh-cn" : "en-us";
  314. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", notifyUsers.Select(x => $"'{x}'"))})";
  315. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  316. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  317. .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  318. {
  319. idNameCodes.Add(item);
  320. }
  321. idNameCodes.FindAll(x => string.IsNullOrWhiteSpace(x.code) || (!x.code.Equals("zh-cn") && !x.code.Equals("zh-tw") && !x.code.Equals("en-us"))).ForEach(x => { x.code = lang; });
  322. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  323. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  324. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  325. string location = "China";
  326. if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("China"))
  327. {
  328. location = "China";
  329. }
  330. else if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("Global"))
  331. {
  332. location = "Global";
  333. }
  334. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
  335. var client = _httpClient.CreateClient();
  336. if (client.DefaultRequestHeaders.Contains("Authorization"))
  337. {
  338. client.DefaultRequestHeaders.Remove("Authorization");
  339. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  340. }
  341. else
  342. {
  343. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  344. }
  345. //检查dbgenRedis的状态是否全部已经不是0和1
  346. var unfinished = dbgenRedis.FindAll(x => (x.status==0||x.status==1));
  347. if (unfinished==null || unfinished.Count==0)
  348. {
  349. // 数据大于60一个班,发送报告的总耗时等概要信息, 小于60的发送 生成报告的细则消息,小于五个的,可以列出报告的链接.
  350. long joinTime = dbgenRedis.Min(x => x.join);
  351. long totalTime = (now-joinTime)/1000;
  352. long costTime = dbgenRedis.Sum(x => x.cost)/1000;
  353. long avgTime = costTime / dbgenRedis.Count;
  354. long maxTime = dbgenRedis.Max(x => x.cost)/1000;
  355. long minTime = dbgenRedis.Min(x => x.cost)/1000;
  356. long statusOk = dbgenRedis.Where(x => x.status==2).Count();
  357. long statusFailed = dbgenRedis.Where(x => x.status!=2).Count();
  358. string key = "pdf-gen-notify-higher60";
  359. if (dbgenRedis.Count>60)
  360. {
  361. key = "pdf-gen-notify-higher60";
  362. }
  363. else
  364. {
  365. key ="pdf-gen-notify-below60";
  366. }
  367. foreach (var teacher in idNameCodes)
  368. {
  369. string path = Path.Combine("", $"Lang/{teacher.code}.json");
  370. var sampleJson = File.ReadAllText(path);
  371. JsonElement jsonElement = sampleJson.ToObject<JsonElement>();
  372. JsonElement msgsJson = jsonElement.GetProperty(key);
  373. List<string> msgs = msgsJson.ToObject<List<string>>();
  374. string msg1 = msgs[1].Replace("{tmdname}", teacher.name).Replace("{taskName}", taskName).Replace("{totalTime}",$"{totalTime}")
  375. .Replace("{avgTime}",$"{avgTime}").Replace("{maxTime}",$"{maxTime}").Replace("{minTime}",$"{minTime}").Replace("{statusOk}",$"{statusOk}").Replace("{statusFailed}",$"{statusFailed}");
  376. StringBuilder sb = new StringBuilder($"{msg1}");
  377. if (dbgenRedis.Count<=60)
  378. {
  379. string status = string.Empty;
  380. dbgenRedis.ForEach(x => {
  381. switch (x.status)
  382. {
  383. case 0:
  384. status= teacher.code.Equals("zh-cn") ? "未执行" : teacher.code.Equals("zh-tw") ? "未執行" : "unexecuted";
  385. break;
  386. case 1:
  387. status= teacher.code.Equals("zh-cn") ? "执行中" : teacher.code.Equals("zh-tw") ? "執行中" : "executing";
  388. break;
  389. case 2:
  390. status= teacher.code.Equals("zh-cn") ? "成功" : teacher.code.Equals("zh-tw") ? "成功" : "success";
  391. break;
  392. case 3:
  393. status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
  394. break;
  395. case 4:
  396. status= teacher.code.Equals("zh-cn") ? "超时" : teacher.code.Equals("zh-tw") ? "超時" : "timeout";
  397. break;
  398. case 5:
  399. status= teacher.code.Equals("zh-cn") ? "取消" : teacher.code.Equals("zh-tw") ? "取消" : "canceled";
  400. break;
  401. case 6:
  402. status= teacher.code.Equals("zh-cn") ? "存放异常" : teacher.code.Equals("zh-tw") ? "存放異常" : "SaveError";
  403. break;
  404. default:
  405. status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
  406. break;
  407. }
  408. string msg2 = msgs[2].Replace("{studentName}",x.name).Replace("{status}", $"{status}").Replace("{wait}", $"{x.wait/1000}").Replace("{cost}", $"{x.cost/1000}").Replace("{total}", $"{(x.wait+x.cost)/1000}");
  409. sb.Append(msg2);
  410. });
  411. }
  412. NotifyData notifyData = new NotifyData
  413. {
  414. hubName = "hita5",
  415. sender = "IES",
  416. tags = new List<string> { $"{teacher.id}_{Constant.NotifyType_IES5_Course}"},
  417. title = msgs[0],
  418. eventId = $"{key}_{_snowflakeId.NextId()}",
  419. eventName =msgs[0],
  420. data = "{\"value\":{}}",
  421. body=sb.ToString(),
  422. };
  423. string result = "";
  424. try
  425. {
  426. HttpResponseMessage responseMessage =await client.PostAsJsonAsync($"{url}/service/PushNotify", notifyData);
  427. if (responseMessage.StatusCode == HttpStatusCode.OK)
  428. {
  429. string content = await responseMessage.Content.ReadAsStringAsync();
  430. result = content;
  431. }
  432. else
  433. {
  434. result = $"{responseMessage.StatusCode},推送返回的状态码。";
  435. }
  436. }
  437. catch (Exception exm)
  438. {
  439. _= _dingDing.SendBotMsg($"{location}站点发送消息异常,{exm.Message}\n{exm.StackTrace}:\n{url}/service/PushNotify \nheader: {token.AccessToken} \nresult:{result}\n params:{notifyData.ToJsonString()}", GroupNames.成都开发測試群組);
  440. }
  441. }
  442. }
  443. }
  444. Console.WriteLine($"結束:{time}");
  445. }
  446. catch (Exception ex)
  447. {
  448. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  449. }
  450. finally
  451. { // Complete the message
  452. await messageActions.CompleteMessageAsync(message);
  453. }
  454. }
  455. /// <summary>
  456. /// UseDevelopmentStorage=true
  457. /// </summary>
  458. /// <param name="message"></param>
  459. /// <param name="messageActions"></param>
  460. /// <returns></returns>
  461. [Function("Exam")]
  462. public async Task ExamFunc(
  463. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")]
  464. ServiceBusReceivedMessage message,
  465. ServiceBusMessageActions messageActions)
  466. {
  467. _logger.LogInformation("Message ID: {id}", message.MessageId);
  468. _logger.LogInformation("Message Body: {body}", message.Body);
  469. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  470. var json = JsonDocument.Parse(message.Body);
  471. try
  472. {
  473. json.RootElement.TryGetProperty("id", out JsonElement id);
  474. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  475. json.RootElement.TryGetProperty("code", out JsonElement code);
  476. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  477. var client = _azureCosmos.GetCosmosClient();
  478. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  479. exam.progress = progress.ToString();
  480. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  481. }
  482. catch (CosmosException e)
  483. {
  484. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  485. }
  486. catch (Exception ex)
  487. {
  488. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  489. }
  490. finally
  491. { // Complete the message
  492. await messageActions.CompleteMessageAsync(message);
  493. }
  494. }
  495. /// <summary>
  496. /// UseDevelopmentStorage=true
  497. /// </summary>
  498. /// <param name="message"></param>
  499. /// <param name="messageActions"></param>
  500. /// <returns></returns>
  501. [Function("Vote")]
  502. public async Task VoteFunc(
  503. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")]
  504. ServiceBusReceivedMessage message,
  505. ServiceBusMessageActions messageActions)
  506. {
  507. _logger.LogInformation("Message ID: {id}", message.MessageId);
  508. _logger.LogInformation("Message Body: {body}", message.Body);
  509. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  510. var jsonMsg = JsonDocument.Parse(message.Body);
  511. try
  512. {
  513. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  514. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  515. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  516. var client = _azureCosmos.GetCosmosClient();
  517. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  518. vote.progress = progress.ToString();
  519. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  520. }
  521. catch (CosmosException e)
  522. {
  523. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  524. }
  525. catch (Exception ex)
  526. {
  527. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  528. }
  529. finally
  530. { // Complete the message
  531. await messageActions.CompleteMessageAsync(message);
  532. }
  533. }
  534. /// <summary>
  535. /// UseDevelopmentStorage=true
  536. /// </summary>
  537. /// <param name="message"></param>
  538. /// <param name="messageActions"></param>
  539. /// <returns></returns>
  540. [Function("Correct")]
  541. public async Task CorrectFunc(
  542. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")]
  543. ServiceBusReceivedMessage message,
  544. ServiceBusMessageActions messageActions)
  545. {
  546. _logger.LogInformation("Message ID: {id}", message.MessageId);
  547. _logger.LogInformation("Message Body: {body}", message.Body);
  548. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  549. var jsonMsg = JsonDocument.Parse(message.Body);
  550. try
  551. {
  552. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  553. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  554. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  555. var client = _azureCosmos.GetCosmosClient();
  556. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  557. correct.progress = progress.ToString();
  558. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  559. }
  560. catch (CosmosException e)
  561. {
  562. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  563. }
  564. catch (Exception ex)
  565. {
  566. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  567. }
  568. finally
  569. { // Complete the message
  570. await messageActions.CompleteMessageAsync(message);
  571. }
  572. }
  573. /// <summary>
  574. /// UseDevelopmentStorage=true
  575. /// </summary>
  576. /// <param name="message"></param>
  577. /// <param name="messageActions"></param>
  578. /// <returns></returns>
  579. [Function("Survey")]
  580. public async Task SurveyFunc(
  581. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")]
  582. ServiceBusReceivedMessage message,
  583. ServiceBusMessageActions messageActions)
  584. {
  585. _logger.LogInformation("Message ID: {id}", message.MessageId);
  586. _logger.LogInformation("Message Body: {body}", message.Body);
  587. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  588. var jsonMsg = JsonDocument.Parse(message.Body);
  589. try
  590. {
  591. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  592. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  593. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  594. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  595. var client = _azureCosmos.GetCosmosClient();
  596. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  597. survey.progress = progress.ToString();
  598. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  599. }
  600. catch (CosmosException e)
  601. {
  602. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  603. }
  604. catch (Exception ex)
  605. {
  606. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  607. }
  608. finally
  609. { // Complete the message
  610. await messageActions.CompleteMessageAsync(message);
  611. }
  612. }
  613. /// <summary>
  614. /// UseDevelopmentStorage=true
  615. /// </summary>
  616. /// <param name="message"></param>
  617. /// <param name="messageActions"></param>
  618. /// <returns></returns>
  619. [Function("Homework")]
  620. public async Task HomeworkFunc(
  621. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")]
  622. ServiceBusReceivedMessage message,
  623. ServiceBusMessageActions messageActions)
  624. {
  625. _logger.LogInformation("Message ID: {id}", message.MessageId);
  626. _logger.LogInformation("Message Body: {body}", message.Body);
  627. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  628. var jsonMsg = JsonDocument.Parse(message.Body);
  629. try
  630. {
  631. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  632. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  633. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  634. var client = _azureCosmos.GetCosmosClient();
  635. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  636. homework.progress = progress.ToString();
  637. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  638. }
  639. catch (CosmosException e)
  640. {
  641. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  642. }
  643. catch (Exception ex)
  644. {
  645. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  646. }
  647. finally
  648. { // Complete the message
  649. await messageActions.CompleteMessageAsync(message);
  650. }
  651. }
  652. /// <summary>
  653. /// UseDevelopmentStorage=true
  654. /// </summary>
  655. /// <param name="message"></param>
  656. /// <param name="messageActions"></param>
  657. /// <returns></returns>
  658. [Function("Study")]
  659. public async Task StudyFunc(
  660. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")]
  661. ServiceBusReceivedMessage message,
  662. ServiceBusMessageActions messageActions)
  663. {
  664. _logger.LogInformation("Message ID: {id}", message.MessageId);
  665. _logger.LogInformation("Message Body: {body}", message.Body);
  666. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  667. string activityId = string.Empty;
  668. var jsonMsg = JsonDocument.Parse(message.Body);
  669. try
  670. {
  671. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  672. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  673. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  674. var client = _azureCosmos.GetCosmosClient();
  675. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  676. study.progress = progress.ToString();
  677. activityId = id.ToString();
  678. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  679. }
  680. catch (CosmosException e)
  681. {
  682. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  683. }
  684. catch (Exception ex)
  685. {
  686. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  687. }
  688. finally
  689. { // Complete the message
  690. await messageActions.CompleteMessageAsync(message);
  691. }
  692. }
  693. /// <summary>
  694. /// UseDevelopmentStorage=true
  695. /// </summary>
  696. /// <param name="message"></param>
  697. /// <param name="messageActions"></param>
  698. /// <returns></returns>
  699. [Function("Art")]
  700. public async Task ArtFunc(
  701. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "art", Connection = "Azure:ServiceBus:ConnectionString")]
  702. ServiceBusReceivedMessage message,
  703. ServiceBusMessageActions messageActions)
  704. {
  705. _logger.LogInformation("Message ID: {id}", message.MessageId);
  706. _logger.LogInformation("Message Body: {body}", message.Body);
  707. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  708. string activityId = string.Empty;
  709. var jsonMsg = JsonDocument.Parse(message.Body);
  710. try
  711. {
  712. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  713. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  714. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  715. var client = _azureCosmos.GetCosmosClient();
  716. ArtEvaluation art = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ArtEvaluation>(id.ToString(), new PartitionKey($"{code}"));
  717. art.progress = progress.ToString();
  718. activityId = id.ToString();
  719. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(art, id.ToString(), new PartitionKey($"{code}"));
  720. }
  721. catch (CosmosException e)
  722. {
  723. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Art()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  724. }
  725. catch (Exception ex)
  726. {
  727. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Art()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  728. }
  729. finally
  730. { // Complete the message
  731. await messageActions.CompleteMessageAsync(message);
  732. }
  733. }
  734. /// <summary>
  735. /// UseDevelopmentStorage=true
  736. /// </summary>
  737. /// <param name="message"></param>
  738. /// <param name="messageActions"></param>
  739. /// <returns></returns>
  740. [Function("ExamLite")]
  741. public async Task ExamLiteFunc(
  742. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")]
  743. ServiceBusReceivedMessage message,
  744. ServiceBusMessageActions messageActions)
  745. {
  746. _logger.LogInformation("Message ID: {id}", message.MessageId);
  747. _logger.LogInformation("Message Body: {body}", message.Body);
  748. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  749. var jsonMsg = JsonDocument.Parse(message.Body);
  750. try
  751. {
  752. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  753. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  754. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  755. var client = _azureCosmos.GetCosmosClient();
  756. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  757. lite.progress = progress.ToString();
  758. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  759. }
  760. catch (CosmosException e)
  761. {
  762. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  763. }
  764. catch (Exception ex)
  765. {
  766. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  767. }
  768. finally
  769. { // Complete the message
  770. await messageActions.CompleteMessageAsync(message);
  771. }
  772. }
  773. /// <summary>
  774. /// UseDevelopmentStorage=true
  775. /// </summary>
  776. /// <param name="message"></param>
  777. /// <param name="messageActions"></param>
  778. /// <returns></returns>
  779. [Function("TeacherTrainChange")]
  780. public async Task TeacherTrainChangeFunc(
  781. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")]
  782. ServiceBusReceivedMessage message,
  783. ServiceBusMessageActions messageActions)
  784. {
  785. _logger.LogInformation("Message ID: {id}", message.MessageId);
  786. _logger.LogInformation("Message Body: {body}", message.Body);
  787. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  788. var data = JsonDocument.Parse(message.Body).RootElement.ToObject<TeacherTrainChangeMsg>();
  789. try
  790. {
  791. var client = _azureCosmos.GetCosmosClient();
  792. List<TeacherTrain> trains = new List<TeacherTrain>();
  793. //redis锁
  794. bool lockKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Train:Statistics:Lock:{data.areaId}");
  795. if (!lockKey)
  796. {
  797. await _azureRedis.GetRedisClient(8).SetAddAsync($"Train:Statistics:Lock:{data.areaId}", new RedisValue(data.areaId));
  798. DateTime minutes = DateTime.UtcNow.AddMinutes(15); //15分钟
  799. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Train:Statistics:Lock:{data.areaId}", minutes);
  800. Area area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{data.areaId}", new PartitionKey("Base-Area"));
  801. AreaSetting setting = null;
  802. if (area != null)
  803. {
  804. try
  805. {
  806. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  807. }
  808. catch (CosmosException)
  809. {
  810. setting = null;
  811. }
  812. }
  813. if (setting == null)
  814. {
  815. setting = new AreaSetting
  816. {
  817. allTime = 50,
  818. classTime = 5,
  819. submitTime = 15,
  820. onlineTime = 20,
  821. offlineTime = 10,
  822. lessonMinutes = 45,
  823. };
  824. }
  825. foreach (var school in data.schools)
  826. {
  827. List<Study> studies = new List<Study>();
  828. await foreach (var item in client.GetContainer("TEAMModelOS", "Common")
  829. .GetItemQueryIteratorSql<Study>(queryText: $"select value(c) from c where c.owner<>'area' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{school.school}") }))
  830. {
  831. studies.Add(item);
  832. }
  833. if (school.teachers.Any())
  834. {
  835. string trainSql = $"select value(c) from c where c.id in ({string.Join(",", school.teachers.Select(x => $"'{x}'"))}) ";
  836. await foreach (var item in client.GetContainer("TEAMModelOS", Constant.Teacher)
  837. .GetItemQueryIteratorSql<TeacherTrain>(queryText: trainSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{school.school}") }))
  838. {
  839. trains.Add(item);
  840. }
  841. }
  842. await StatisticsService.GetStatisticsTeacher(trains, setting, area, client, studies);
  843. }
  844. area.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  845. await client.GetContainer(Constant.TEAMModelOS, "Normal").ReplaceItemAsync<Area>(area, $"{data.areaId}", new PartitionKey("Base-Area"));
  846. }
  847. }
  848. catch (Exception ex)
  849. {
  850. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-TeacherTrainChange\n{ex.Message}\n{ex.StackTrace}\n\n{message.Body}", GroupNames.醍摩豆服務運維群組);
  851. }
  852. finally
  853. { // Complete the message
  854. await messageActions.CompleteMessageAsync(message);
  855. }
  856. }
  857. /// <summary>
  858. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  859. /// </summary>
  860. /// <data msg>
  861. /// CourseChange
  862. ///// </data>
  863. /// <param name="msg"></param>
  864. /// <returns></returns>
  865. [Function("GroupChange")]
  866. public async Task GroupChangeFunc(
  867. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")]
  868. ServiceBusReceivedMessage message,
  869. ServiceBusMessageActions messageActions)
  870. {
  871. _logger.LogInformation("Message ID: {id}", message.MessageId);
  872. _logger.LogInformation("Message Body: {body}", message.Body);
  873. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  874. var client = _azureCosmos.GetCosmosClient();
  875. var jsonMsg = JsonDocument.Parse(message.Body);
  876. GroupChange groupChange = jsonMsg.RootElement.ToObject<GroupChange>();
  877. try
  878. {
  879. _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
  880. {
  881. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.醍摩豆服務運維群組);
  882. //await _dingDing.SendBotMsg($"名单变化{msg}", GroupNames.成都开发測試群組);
  883. int add = groupChange.tmdjoin.Count - groupChange.tmdleave.Count + groupChange.stujoin.Count - groupChange.stuleave.Count;
  884. if (groupChange.scope.Equals("private") && (groupChange.type.Equals("student") || groupChange.type.Equals("class") || groupChange.type.Equals("teach")))
  885. {
  886. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new Accumulate { client = groupChange.client, count = add, id = groupChange.listid, scope = "teacher", key = "grouplist", name = groupChange.name, target = groupChange.creatorId });
  887. }
  888. if (groupChange.scope.Equals("school") && (groupChange.type.Equals("student") || groupChange.type.Equals("class") || groupChange.type.Equals("teach")))
  889. {
  890. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new Accumulate { client = groupChange.client, count = add, id = groupChange.listid, scope = "school", key = "grouplist", name = groupChange.name, target = groupChange.school });
  891. }
  892. //名单变动修改学生课程关联信息
  893. //await StuListService.FixStuCourse(client, stuListChange);
  894. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  895. //名单变动修改学生问卷关联信息
  896. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
  897. //名单变动修改学生投票关联信息
  898. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
  899. //名单变动修改学生评测关联信息
  900. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
  901. //名单变动修改学生研修关联信息
  902. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  903. //名单变动修改学生简易评测关联信息
  904. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  905. //名单变动修改学生作业活动信息
  906. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  907. //名单变动修改学生艺术评价活动信息
  908. //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Art");
  909. //TODO学习活动
  910. //await FixActivity(client, stuListChange, "Learn");
  911. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  912. {
  913. //课程名单变动修改学生课程关联信息
  914. // await IESActivityService.FixStuCourse(client, _dingDing, groupChange);
  915. //名单变动修改课例关联信息
  916. //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
  917. }
  918. if (groupChange.type.Equals("class") || groupChange.type.Equals("teach") || groupChange.type.Equals("student"))
  919. {
  920. await _httpTrigger.RequestHttpTrigger(new { data = groupChange }, Environment.GetEnvironmentVariable("Option:Location"), "webhook/group-member-change");
  921. if (groupChange.stujoin.Count > 0)
  922. await BIStats.SetTypeAddStats(client, _dingDing, groupChange.school, "Student", groupChange.stujoin.Count);//BI统计增/减量
  923. if (groupChange.stuleave.Count > 0)
  924. await BIStats.SetTypeAddStats(client, _dingDing, groupChange.school, "Student", -groupChange.stuleave.Count);//BI统计增/减量
  925. }
  926. if ((groupChange.type.Equals("class") || groupChange.type.Equals("teach") || groupChange.type.Equals("student")) && "school".Equals(groupChange.scope) && "upsert".Equals(groupChange.status) && !string.IsNullOrWhiteSpace(groupChange.school))
  927. {
  928. var data = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { groupChange.listid }, groupChange.school);
  929. if (data.groups.IsNotEmpty())
  930. {
  931. School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(groupChange.school, new PartitionKey("Base"));
  932. var period = school.period.Find(z => z.id.Equals(data.groups.First().periodId));
  933. if (period != null)
  934. {
  935. var dataSemester = SchoolService.GetSemester(period, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  936. string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{data.groups.First().id}";
  937. string code = $"GroupListSemester-{groupChange.school}";
  938. GroupListSemester groupListSemester = data.groups.First().ToJsonString().ToObject<GroupListSemester>();
  939. groupListSemester.id = id;
  940. groupListSemester.code = code;
  941. groupListSemester.pk = "GroupListSemester";
  942. groupListSemester.semesterId = dataSemester.currSemester.id;
  943. groupListSemester.groupListId = data.groups.First().id;
  944. groupListSemester.studyYear = dataSemester.studyYear;
  945. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  946. }
  947. }
  948. }
  949. });
  950. }
  951. catch (Exception ex)
  952. {
  953. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  954. }
  955. finally
  956. { // Complete the message
  957. await messageActions.CompleteMessageAsync(message);
  958. }
  959. }
  960. /// <summary>
  961. /// UseDevelopmentStorage=true
  962. /// </summary>
  963. /// <param name="message"></param>
  964. /// <param name="messageActions"></param>
  965. /// <returns></returns>
  966. [Function("ItemCondDel")]
  967. public async Task ItemCondDelFunc(
  968. [ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%/$DeadLetterQueue", Connection = "Azure:ServiceBus:ConnectionString")]
  969. ServiceBusReceivedMessage message,
  970. ServiceBusMessageActions messageActions)
  971. {
  972. _logger.LogInformation("Message ID: {id}", message.MessageId);
  973. _logger.LogInformation("Message Body: {body}", message.Body);
  974. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  975. await _dingDing.SendBotMsg($"{message.Body}", GroupNames.成都开发測試群組);
  976. // Complete the message
  977. await messageActions.CompleteMessageAsync(message);
  978. }
  979. /// <summary>
  980. /// UseDevelopmentStorage=true
  981. /// </summary>
  982. /// <param name="message"></param>
  983. /// <param name="messageActions"></param>
  984. /// <returns></returns>
  985. [Function("ItemCond")]
  986. public async Task ItemCondFunc(
  987. [ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")]
  988. ServiceBusReceivedMessage message,
  989. ServiceBusMessageActions messageActions)
  990. {
  991. _logger.LogInformation("Message ID: {id}", message.MessageId);
  992. _logger.LogInformation("Message Body: {body}", message.Body);
  993. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  994. var jsonMsg = JsonDocument.Parse(message.Body);
  995. List<ItemCondDto> itemCondDtos = jsonMsg.RootElement.ToObject<List<ItemCondDto>>();
  996. try
  997. {
  998. var client = _azureCosmos.GetCosmosClient();
  999. foreach (var itemCondDto in itemCondDtos)
  1000. {
  1001. if (itemCondDto.scope.Equals("school"))
  1002. {
  1003. ItemCond itemCond = null;
  1004. List<ItemInfo> items = new List<ItemInfo>();
  1005. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{itemCondDto.key}", new PartitionKey("Base"));
  1006. var period = school.period.Find(z => z.id.Equals(itemCondDto.filed));
  1007. string subjectIn = string.Empty;
  1008. if (period != null && period.subjects.IsNotEmpty())
  1009. {
  1010. subjectIn = $" and c.subjectId in({string.Join(",", period.subjects.Select(x => $"'{x.id}'"))})";
  1011. }
  1012. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.periodId='{itemCondDto.filed}' and c.pid= null {subjectIn} ";
  1013. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
  1014. {
  1015. items.Add(item);
  1016. }
  1017. itemCond = new ItemCond()
  1018. {
  1019. id = $"{itemCondDto.filed}",
  1020. code = $"ItemCond-{itemCondDto.key}",
  1021. pk = "ItemCond",
  1022. ttl = -1,
  1023. count = items.Count,
  1024. grades = new List<GradeCount>(),
  1025. subjects = new List<SubjectItemCount>()
  1026. };
  1027. items.ForEach(z =>
  1028. {
  1029. if (!string.IsNullOrEmpty(z.type))
  1030. {
  1031. ItemService.CountItemCond(z, null, itemCond);
  1032. }
  1033. });
  1034. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
  1035. }
  1036. else
  1037. {
  1038. ItemCond itemCond = null;
  1039. List<ItemInfo> items = new List<ItemInfo>();
  1040. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
  1041. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
  1042. {
  1043. items.Add(item);
  1044. }
  1045. itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
  1046. items.ForEach(z =>
  1047. {
  1048. if (!string.IsNullOrEmpty(z.type))
  1049. {
  1050. ItemService.CountItemCond(z, null, itemCond);
  1051. }
  1052. });
  1053. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
  1054. }
  1055. }
  1056. }
  1057. catch (CosmosException ex)
  1058. {
  1059. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1060. }
  1061. catch (Exception ex)
  1062. {
  1063. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1064. }
  1065. finally
  1066. { // Complete the message
  1067. await messageActions.CompleteMessageAsync(message);
  1068. }
  1069. }
  1070. /// <summary>
  1071. /// UseDevelopmentStorage=true
  1072. /// </summary>
  1073. /// <param name="message"></param>
  1074. /// <param name="messageActions"></param>
  1075. /// <returns></returns>
  1076. [Function("Product")]
  1077. public async Task ProductFunc(
  1078. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")]
  1079. ServiceBusReceivedMessage message,
  1080. ServiceBusMessageActions messageActions)
  1081. {
  1082. _logger.LogInformation("Message ID: {id}", message.MessageId);
  1083. _logger.LogInformation("Message Body: {body}", message.Body);
  1084. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  1085. var jsonMsg = JsonDocument.Parse(message.Body);
  1086. try
  1087. {
  1088. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  1089. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1090. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  1091. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  1092. var client = _azureCosmos.GetCosmosClient();
  1093. string strQuery = string.Empty;
  1094. //取得所有學校產品
  1095. ////序號
  1096. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  1097. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  1098. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  1099. {
  1100. using var json = await JsonDocument.ParseAsync(item.Content);
  1101. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1102. {
  1103. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1104. {
  1105. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  1106. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  1107. if (serialProd == null)
  1108. {
  1109. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  1110. serialProdAdd.prodCode = serialInfo.prodCode;
  1111. serialProdAdd.ids.Add(serialInfo.id);
  1112. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  1113. serialsProductSumOrg.Add(serialProdAdd);
  1114. }
  1115. else
  1116. {
  1117. if (!serialProd.ids.Contains(serialInfo.id))
  1118. {
  1119. serialProd.ids.Add(serialInfo.id);
  1120. }
  1121. serialProd.avaliable = serialProd.ids.Count;
  1122. }
  1123. }
  1124. }
  1125. }
  1126. ////服務
  1127. List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
  1128. //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
  1129. long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  1130. string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
  1131. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  1132. {
  1133. using var json = await JsonDocument.ParseAsync(item.Content);
  1134. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1135. {
  1136. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1137. {
  1138. SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
  1139. SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
  1140. if (serviceProd == null)
  1141. {
  1142. SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
  1143. serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
  1144. serviceProdAdd.avaliable = 0;
  1145. serviceProdAdd.ids.Add(servicePeriodInfo.id);
  1146. serviceProdAdd.avaliable += servicePeriodInfo.number;
  1147. serviceProdAdd.startDate = servicePeriodInfo.startDate;
  1148. serviceProdAdd.endDate = servicePeriodInfo.endDate;
  1149. servicesProductSumOrg.Add(serviceProdAdd);
  1150. }
  1151. else
  1152. {
  1153. serviceProd.ids = new List<string>();
  1154. serviceProd.ids.Add(servicePeriodInfo.id);
  1155. serviceProd.startDate = servicePeriodInfo.startDate;
  1156. serviceProd.endDate = servicePeriodInfo.endDate;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. ////服務產品特別對應項
  1162. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  1163. bool updSchool = false; //是否變更學校基本資料
  1164. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  1165. int schoolDefaultSize = 1; //學校空間初始值:1
  1166. if (!string.IsNullOrWhiteSpace(school.id))
  1167. {
  1168. if (servicesProductSumOrg.Count > 0)
  1169. {
  1170. foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
  1171. {
  1172. //更新學校空間
  1173. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  1174. {
  1175. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  1176. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  1177. updSchool = true;
  1178. chgSchSizeCnt++;
  1179. }
  1180. }
  1181. }
  1182. if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  1183. {
  1184. school.size = schoolDefaultSize;
  1185. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  1186. updSchool = false;
  1187. }
  1188. }
  1189. //變更學校基本資料
  1190. if (updSchool)
  1191. {
  1192. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  1193. }
  1194. ////硬體
  1195. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  1196. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  1197. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  1198. {
  1199. using var json = await JsonDocument.ParseAsync(item.Content);
  1200. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1201. {
  1202. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1203. {
  1204. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  1205. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  1206. if (hardProd == null)
  1207. {
  1208. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  1209. hardProdAdd.prodCode = hardInfo.prodCode;
  1210. hardProdAdd.model = hardInfo.model;
  1211. hardProdAdd.ids.Add(hardInfo.id);
  1212. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  1213. hardsProductSumOrg.Add(hardProdAdd);
  1214. }
  1215. else
  1216. {
  1217. if (!hardProd.ids.Contains(hardInfo.id))
  1218. {
  1219. hardProd.ids.Add(hardInfo.id);
  1220. }
  1221. hardProd.avaliable = hardProd.ids.Count;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. //更新學校產品一覽表
  1227. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  1228. prodSum.serial = serialsProductSumOrg;
  1229. prodSum.service = servicesProductSumOrg;
  1230. prodSum.hard = hardsProductSumOrg;
  1231. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  1232. ///更新学生端学校列表
  1233. var res = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<dynamic>("select c.id,c.city,c.name,c.province,c.picture,c.region from c ", "Base");
  1234. var schools = new { schools = res.list };
  1235. var blockBlob = _azureStorage.GetBlobContainerClient("0-public").GetBlobClient("schools.json");
  1236. string content_type = "application/octet-stream";
  1237. ContentTypeDict.dict.TryGetValue(".json", out string contenttype);
  1238. if (!string.IsNullOrEmpty(contenttype))
  1239. {
  1240. content_type = contenttype;
  1241. }
  1242. byte[] bytes = System.Text.Encoding.Default.GetBytes(schools.ToJsonString());
  1243. Stream streamBlob = new MemoryStream(bytes);
  1244. await blockBlob.UploadAsync(streamBlob, true);
  1245. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  1246. }
  1247. catch (CosmosException ex)
  1248. {
  1249. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1250. }
  1251. catch (Exception ex)
  1252. {
  1253. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1254. }
  1255. finally
  1256. {
  1257. // Complete the message
  1258. await messageActions.CompleteMessageAsync(message);
  1259. }
  1260. }
  1261. /// <summary>
  1262. /// 更新开课数据事件
  1263. /// </summary>
  1264. /// <param name="msg"></param>
  1265. /// <returns></returns>
  1266. [Function("LessonRecordEvent")]
  1267. public async Task LessonRecordFunc(
  1268. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")]
  1269. ServiceBusReceivedMessage message,
  1270. ServiceBusMessageActions messageActions)
  1271. {
  1272. _logger.LogInformation("Message ID: {id}", message.MessageId);
  1273. _logger.LogInformation("Message Body: {body}", message.Body);
  1274. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  1275. JsonElement data = JsonDocument.Parse(message.Body).RootElement;
  1276. string scope = "";
  1277. string tmdid = "";
  1278. string lessonId;
  1279. string school;
  1280. string tbname;
  1281. string code = string.Empty;
  1282. string blobname;
  1283. List<LessonUpdate> updates = new List<LessonUpdate>();
  1284. try
  1285. {
  1286. _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
  1287. {
  1288. //更新课堂记录
  1289. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  1290. {
  1291. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  1292. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  1293. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  1294. data.TryGetProperty("school", out JsonElement _school);
  1295. school = $"{_school}";
  1296. scope = $"{_scope}";
  1297. tmdid = $"{_tmdid}";
  1298. lessonId = $"{_lessonId}";
  1299. updates = _grant_types.ToObject<List<LessonUpdate>>();
  1300. }//创建课堂记录
  1301. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  1302. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  1303. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  1304. {
  1305. data.TryGetProperty("school", out JsonElement _school);
  1306. school = $"{_school}";
  1307. scope = $"{_scope}";
  1308. tmdid = $"{_tmdid}";
  1309. lessonId = $"{_id}";
  1310. updates.Add(new LessonUpdate { grant_type = "create" });
  1311. }//删除课堂记录
  1312. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  1313. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  1314. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  1315. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  1316. {
  1317. data.TryGetProperty("school", out JsonElement _dschool);
  1318. school = $"{_dschool}";
  1319. if ($"{_opt}".Equals("delete"))
  1320. {
  1321. scope = $"{_dscope}";
  1322. tmdid = $"{_dtmdid}";
  1323. lessonId = $"{_delete_id}";
  1324. updates.Add(new LessonUpdate { grant_type = "delete" });
  1325. }
  1326. else { return; }
  1327. }
  1328. else
  1329. {
  1330. return;
  1331. }
  1332. //if (!string.IsNullOrWhiteSpace(school) && school.Equals("habook"))
  1333. //{
  1334. // await _dingDing.SendBotMsg($"研发学校课堂记录事件触发:\n{msg}", GroupNames.成都开发測試群組);
  1335. //}
  1336. var client = _azureCosmos.GetCosmosClient();
  1337. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1338. {
  1339. blobname = $"{school}";
  1340. code = $"LessonRecord-{school}";
  1341. tbname = "School";
  1342. }
  1343. else if ($"{scope}".Equals("private"))
  1344. {
  1345. blobname = $"{tmdid}";
  1346. code = $"LessonRecord";
  1347. tbname = "Teacher";
  1348. }
  1349. else
  1350. {
  1351. return;
  1352. }
  1353. LessonDis lessonDis = new LessonDis();
  1354. List<LessonUpdate> msgs = new List<LessonUpdate>();
  1355. LessonRecord oldlessonRecord = null;
  1356. LessonRecord lessonRecord = null;
  1357. ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1358. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  1359. {
  1360. var doc = JsonDocument.Parse(response.Content);
  1361. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1362. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1363. }
  1364. else
  1365. {
  1366. lessonRecord = null;
  1367. }
  1368. bool isReplace = true;
  1369. if (updates.IsNotEmpty())
  1370. {
  1371. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  1372. foreach (LessonUpdate update in updates)
  1373. {
  1374. switch (update.grant_type)
  1375. {
  1376. //更新课堂时长
  1377. case "up-duration":
  1378. double.TryParse($"{update.data}", out double duration);
  1379. lessonRecord.duration = duration;
  1380. msgs.Add(update);
  1381. try
  1382. {
  1383. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  1384. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  1385. if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
  1386. {
  1387. var durationFile = double.Parse($"{_duration}");
  1388. if (duration < durationFile)
  1389. {
  1390. lessonRecord.duration = durationFile;
  1391. }
  1392. }
  1393. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
  1394. {
  1395. lessonRecord.hasVideo = 1;
  1396. }
  1397. }
  1398. catch (Exception ex)
  1399. {
  1400. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  1401. }
  1402. isReplace = true;
  1403. break;
  1404. //更新T分
  1405. case "up-tScore":
  1406. var tScore = int.Parse($"{update.data}");
  1407. lessonRecord.tScore = tScore;
  1408. msgs.Add(update);
  1409. break;
  1410. //更新课P分
  1411. case "up-pScore":
  1412. var pScore = int.Parse($"{update.data}");
  1413. lessonRecord.pScore = pScore;
  1414. msgs.Add(update);
  1415. break;
  1416. //更新 学生人数
  1417. case "up-mCount":
  1418. var mCount = int.Parse($"{update.data}");
  1419. lessonRecord.mCount = mCount;
  1420. msgs.Add(update);
  1421. break;
  1422. //更新 议课次数
  1423. case "up-techCount":
  1424. var techCount = int.Parse($"{update.data}");
  1425. lessonRecord.mCount = techCount;
  1426. msgs.Add(update);
  1427. break;
  1428. //更新 基础统计信息
  1429. case "up-base":
  1430. //读取TimeLine.json
  1431. List<int> PickupMemberIds = new List<int>();
  1432. TimeLineData timeLineData = new TimeLineData();
  1433. try
  1434. {
  1435. BlobDownloadResult timeLineBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1436. timeLineData = timeLineBlobDownload.Content.ToObjectFromJson<TimeLineData>();
  1437. lessonRecord.hitaClientCmpCount = timeLineData.events.Where(z => !string.IsNullOrWhiteSpace(z.WrkCmpSrcType) && z.WrkCmpSrcType.Equals("HitaClientCmp")).Count();
  1438. //lessonRecord.collateTaskCount = lessonRecord.hitaClientCmpCount;
  1439. List<TimeLineEvent> timeLineEvents = timeLineData.events.FindAll(z => !string.IsNullOrWhiteSpace(z.Event) && z.Event.Equals("PickupResult"));
  1440. if (timeLineEvents.IsNotEmpty())
  1441. {
  1442. foreach (var timeLineEvent in timeLineEvents)
  1443. {
  1444. var memberIds = timeLineEvent.PickupMemberId.ToObject<List<int>>();
  1445. PickupMemberIds.AddRange(memberIds);
  1446. }
  1447. }
  1448. }
  1449. catch (Exception ex)
  1450. {
  1451. if (!ex.Message.Contains("The specified blob does not exist"))
  1452. {
  1453. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},TimeLine.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1454. }
  1455. }
  1456. //读取Task.json
  1457. ///Event 过滤类型 : 'WrkSpaceLoad', 'WrkCmp' 文件:Task.json 根据clientWorks 中的seatID 匹配base.json 中的 student
  1458. List<TaskData> taskDatas = new List<TaskData>();
  1459. try
  1460. {
  1461. BlobDownloadResult taskBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/Task.json").DownloadContentAsync();
  1462. taskDatas = taskBlobDownload.Content.ToObjectFromJson<List<TaskData>>();
  1463. }
  1464. catch (Exception ex)
  1465. {
  1466. if (!ex.Message.Contains("The specified blob does not exist"))
  1467. {
  1468. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},Task.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1469. }
  1470. }
  1471. //读取互评信息
  1472. //Event 过滤类型 'RatingStart'
  1473. //smartRateSummary.mutualSummary.mutualType 互评【All(每人多件评分) Two(随机分配互评) Self(自评)】 smartRateSummary.meteor_VoteSummary 投票
  1474. //读取IRS.json
  1475. List<SmartRatingData> smartRatingDatas = new List<SmartRatingData>();
  1476. try
  1477. {
  1478. BlobDownloadResult smartRatingBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/IRS.json").DownloadContentAsync();
  1479. smartRatingDatas = smartRatingBlobDownload.Content.ToObjectFromJson<List<SmartRatingData>>();
  1480. }
  1481. catch (Exception ex)
  1482. {
  1483. if (!ex.Message.Contains("The specified blob does not exist"))
  1484. {
  1485. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1486. }
  1487. }
  1488. //读取互动信息
  1489. //Event 过滤类型 'PopQuesLoad', 'ReAtmpAnsStrt', 'BuzrAns','BuzrLoad'
  1490. //TimeLine.json 中找到对应类型,根据Pgid 去 IRS.json 中找到对应数据,从clientAnswers 的下标对应 base.json 中的 student 找到对应学生信息 clientAnswers.length > 1 则表示有二次作答
  1491. //读取IRS.json
  1492. List<IRSData> irsDatas = new List<IRSData>();
  1493. try
  1494. {
  1495. BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/IRS.json").DownloadContentAsync();
  1496. irsDatas = irsBlobDownload.Content.ToObjectFromJson<List<IRSData>>();
  1497. }
  1498. catch (Exception ex)
  1499. {
  1500. if (!ex.Message.Contains("The specified blob does not exist"))
  1501. {
  1502. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1503. }
  1504. }
  1505. //读取协作信息
  1506. ///Event 过滤类型 'CoworkLoad'
  1507. //TimeLine.json 中找到对应类型,根据Pgid 去 Cowork.json 中找到对应数据
  1508. List<CoworkData> coworkDatas = new List<CoworkData>();
  1509. try
  1510. {
  1511. BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/Cowork.json").DownloadContentAsync();
  1512. coworkDatas = irsBlobDownload.Content.ToObjectFromJson<List<CoworkData>>();
  1513. }
  1514. catch (Exception ex)
  1515. {
  1516. if (!ex.Message.Contains("The specified blob does not exist"))
  1517. {
  1518. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1519. }
  1520. }
  1521. //苏格拉底文件信息
  1522. //Sokrates/SokratesRecords.json
  1523. List<TimeLineEvent> sokratesDatas = new List<TimeLineEvent>();
  1524. try
  1525. {
  1526. BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/Sokrates/SokratesRecords.json").DownloadContentAsync();
  1527. sokratesDatas = irsBlobDownload.Content.ToObjectFromJson<List<TimeLineEvent>>();
  1528. }
  1529. catch (Exception ex)
  1530. {
  1531. if (!ex.Message.Contains("The specified blob does not exist"))
  1532. {
  1533. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1534. }
  1535. }
  1536. //读取base.json信息
  1537. //如果有更新 则去读取/{_lessonId}/IES/base.json
  1538. List<LocalStudent> studentLessonDatas = new List<LocalStudent>();
  1539. LessonBase lessonBase = null;
  1540. try
  1541. {
  1542. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  1543. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  1544. //attendState
  1545. string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall", "0");
  1546. try
  1547. {
  1548. lessonBase = basejson.ToObject<LessonBase>();
  1549. }
  1550. catch (Exception ex)
  1551. {
  1552. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},base.json转换异常,{ex.Message}{ex.StackTrace}{basejson},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1553. //lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1554. }
  1555. //await _dingDing.SendBotMsg($"课例记录文件base.json:{lessonBase.ToJsonString()}", GroupNames.成都开发測試群組);
  1556. if (lessonBase != null && lessonBase.summary != null)
  1557. {
  1558. var baseData =LessonETLService. GetBaseData(lessonBase!);
  1559. studentLessonDatas= baseData.studentLessonDatas;
  1560. //lessonRecord.name = lessonBase.summary.activityName;
  1561. lessonRecord.attendCount = lessonBase.summary.attendCount;
  1562. lessonRecord.clientCount = lessonBase.summary.clientCount;
  1563. lessonRecord.attendRate = lessonBase.summary.attendRate;
  1564. lessonRecord.groupCount = lessonBase.summary.groupCount;
  1565. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  1566. lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount + lessonRecord.hitaClientCmpCount;
  1567. lessonRecord.collateCount = lessonBase.summary.collateCount;
  1568. lessonRecord.pushCount = lessonBase.summary.pushCount;
  1569. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  1570. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  1571. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  1572. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  1573. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  1574. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  1575. lessonRecord.examCount = lessonBase.summary.examCount;
  1576. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  1577. lessonRecord.engagementIndexAverge= lessonBase.summary.engagementIndexAverge;
  1578. lessonRecord.learningCategory = lessonBase.summary.learningCategory;
  1579. if (lessonRecord.learningCategory == null)
  1580. {
  1581. lessonRecord.learningCategory = new LearningCategory();
  1582. }
  1583. if (lessonRecord.hitaClientCmpCount > 0)
  1584. {
  1585. lessonRecord.learningCategory.cooperation = 1;
  1586. }
  1587. if (!string.IsNullOrWhiteSpace(lessonRecord.school))
  1588. {
  1589. lessonBase.student.ForEach(x =>
  1590. {
  1591. if (string.IsNullOrWhiteSpace(x.school))
  1592. {
  1593. x.school = lessonRecord.school;
  1594. }
  1595. });
  1596. }
  1597. //计算TP灯
  1598. {
  1599. int T = -1;
  1600. int P = -1;
  1601. if (lessonRecord.clientInteractionAverge <= 0)
  1602. {
  1603. T = 0;
  1604. }
  1605. else if (lessonRecord.clientInteractionAverge > 0 && lessonRecord.clientInteractionAverge < 2)
  1606. // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
  1607. {
  1608. T = 1;
  1609. }
  1610. else
  1611. {
  1612. T = 2;
  1613. }
  1614. //if (lessonRecord.examCount > 0)
  1615. //{
  1616. // //有评测次数大于0则P是直接绿灯
  1617. // P = 2;
  1618. //}
  1619. //else {
  1620. //}
  1621. int a = lessonRecord.hitaClientCmpCount;
  1622. int b = lessonRecord.pushCount;
  1623. int c = lessonRecord.examCount;
  1624. switch (true)
  1625. {
  1626. case bool when T == 0:
  1627. P = 0;
  1628. break;
  1629. case bool when T == 1 || T == 2:
  1630. if (a == 0 && b == 0 && c == 0)
  1631. {
  1632. P = 0;
  1633. }
  1634. else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
  1635. {
  1636. P = 2;
  1637. }
  1638. else
  1639. {
  1640. P = 1;
  1641. }
  1642. break;
  1643. }
  1644. lessonRecord.tLevel = T;
  1645. lessonRecord.pLevel = P;
  1646. }
  1647. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1648. //{
  1649. // clientSummaryList = lessonBase.report.clientSummaryList,
  1650. // students = lessonBase.student,
  1651. // name = lessonRecord.name,
  1652. // school = lessonRecord.school,
  1653. // id = lessonRecord.id,
  1654. // scope = lessonRecord.scope,
  1655. // tmdid = lessonRecord.tmdid,
  1656. // code = "LessonStudentRecord",
  1657. // pk = "LessonStudentRecord",
  1658. // courseId =lessonRecord.courseId,
  1659. // groupIds= lessonRecord.groupIds,
  1660. // periodId = lessonRecord.periodId,
  1661. // subjectId = lessonRecord.subjectId,
  1662. //};
  1663. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1664. }
  1665. //有上传 base.josn.
  1666. lessonRecord.upload = 1;
  1667. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1668. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, _coreAPIHttpService, _dingDing, _azureRedis);
  1669. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1670. Bloblog bloblog = new Bloblog
  1671. {
  1672. id = lessonRecord.id,
  1673. code = $"Bloblog-{blobname}",
  1674. name = lessonRecord.name,
  1675. pk = "Bloblog",
  1676. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1677. type = "records",
  1678. url = $"records/{_lessonId}",
  1679. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1680. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1681. size = size.HasValue ? size.Value : 0,
  1682. };
  1683. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1684. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1685. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1686. msgs.Add(update);
  1687. List<ExamData> examDatas = new List<ExamData>();
  1688. if (lessonBase!=null && lessonBase.student!=null)
  1689. {
  1690. string owner = lessonRecord.scope.Equals("school") ? lessonRecord.school : lessonRecord.tmdid;
  1691. examDatas = await LessonETLService.GetExamInfo(lessonRecord, timeLineData, _azureStorage, owner);
  1692. sokratesDatas= sokratesDatas.IsNotEmpty() ? sokratesDatas : timeLineData!=null ? timeLineData.events : new List<TimeLineEvent>();
  1693. }
  1694. LessonLocal lessonLocal = new LessonLocal()
  1695. {
  1696. lessonBase=lessonBase,
  1697. timeLineData= timeLineData,
  1698. lessonRecord= lessonRecord,
  1699. taskDatas= taskDatas,
  1700. smartRatingDatas= smartRatingDatas,
  1701. irsDatas= irsDatas,
  1702. coworkDatas= coworkDatas,
  1703. examDatas=examDatas,
  1704. sokratesDatas= sokratesDatas,
  1705. studentLessonDatas=studentLessonDatas
  1706. };
  1707. try {
  1708. if (lessonRecord.duration>0 && lessonRecord.scope.Equals("school"))
  1709. {
  1710. var location = Environment.GetEnvironmentVariable("Option:Location");
  1711. var studatas = LessonETLService.GenStudentLessonData(lessonLocal, Constant.objectiveTypes );
  1712. string owner = lessonRecord.scope.Equals("school") ? lessonRecord.school : lessonRecord.tmdid;
  1713. if (location.Equals("China", StringComparison.OrdinalIgnoreCase))
  1714. {
  1715. List<School> schools = new List<School>();
  1716. List<StudentSemesterRecord> studentSemesterRecords = new List<StudentSemesterRecord>();
  1717. List<OverallEducation> overallEducations = new List<OverallEducation>();
  1718. List<Student> studentsBase = new List<Student>();
  1719. List<StudentSemesterRecord> students = new List<StudentSemesterRecord>();
  1720. LessonDataAnalysisModel lessonDataAnalysis = null;
  1721. bool exists = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient($"/lesson/analysis/analysis-model.json").ExistsAsync();
  1722. if (exists)
  1723. {
  1724. BlobDownloadResult blobDownload = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient($"/lesson/analysis/analysis-model.json").DownloadContentAsync();
  1725. lessonDataAnalysis = blobDownload.Content.ToObjectFromJson<LessonDataAnalysisModel>();
  1726. string studentSql = $"select value c from c where c.id in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))})";
  1727. var studentResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(studentSql, $"Base-{school}");
  1728. if (studentResults.list.IsNotEmpty())
  1729. {
  1730. studentsBase.AddRange(studentResults.list);
  1731. }
  1732. School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  1733. schools.Add(schoolBase);
  1734. string? periodId = !string.IsNullOrWhiteSpace(lessonLocal.lessonRecord.periodId) ? lessonLocal.lessonRecord.periodId : schoolBase.period.FirstOrDefault()?.id;
  1735. var period = schoolBase.period.Find(x => x.id.Equals(periodId));
  1736. var semester = SchoolService.GetSemester(period, lessonLocal.lessonRecord.startTime);
  1737. string code = $"StudentSemesterRecord-{schoolBase.id}";
  1738. string studentSemesterRecordSql = $"select value c from c where c.stuid in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))}) and c.semesterId='{semester.currSemester.id}' and c.studyYear={semester.studyYear}";
  1739. var studentSemesterRecordResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<StudentSemesterRecord>(studentSemesterRecordSql, code);
  1740. if (studentSemesterRecordResults.list.IsNotEmpty())
  1741. {
  1742. studentSemesterRecords.AddRange(studentSemesterRecordResults.list);
  1743. }
  1744. string overallEducationSql = $"select value c from c where c.studentId in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))}) and c.semesterId='{semester.currSemester.id}' and c.year={semester.studyYear}";
  1745. var overallEducationResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<OverallEducation>(overallEducationSql, $"OverallEducation-{schoolBase.id}");
  1746. if (overallEducationResults.list.IsNotEmpty())
  1747. {
  1748. overallEducations.AddRange(overallEducationResults.list);
  1749. }
  1750. var studata = LessonETLService.DoStudentLessonDataV2(Constant.objectiveTypes, lessonLocal, location, studentSemesterRecords, overallEducations, lessonDataAnalysis, studentsBase, schools);
  1751. await Parallel.ForEachAsync(studentSemesterRecords, async (studentSemester, cancellationToken) =>
  1752. {
  1753. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(studentSemester, new PartitionKey(studentSemester.code));
  1754. });
  1755. await Parallel.ForEachAsync(overallEducations, async (overallEducation, cancellationToken) =>
  1756. {
  1757. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(overallEducation, partitionKey: new PartitionKey(overallEducation.code));
  1758. string key = $"OverallEducation:{overallEducation.schoolCode}:{overallEducation.periodId}:{overallEducation.year}:{overallEducation.semesterId}:{overallEducation?.classId}";
  1759. await _azureRedis.GetRedisClient(8).HashSetAsync(key, overallEducation.studentId, overallEducation.ToJsonString());
  1760. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 *24, 0, 0));
  1761. });
  1762. await _azureStorage.GetBlobContainerClient(owner).UploadFileByContainer(studata.studentLessonDatas.ToJsonString(), "records", $"{lessonRecord.id}/student-analysis.json");
  1763. XmlDocument xmlDocument = new XmlDocument();
  1764. var runtimePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  1765. xmlDocument.Load($"{runtimePath}\\summary.xml");
  1766. PropertyInfo[] properties = typeof(StudentLessonItem).GetProperties();
  1767. List<string> summaryes = new List<string>();
  1768. for (int i = 0; i < properties.Length; i++)
  1769. {
  1770. string summary = Regex.Replace(LessonETLService.GetPropertySummary(properties[i], xmlDocument), @"\s+", "");
  1771. summaryes.Add(summary);
  1772. }
  1773. await LessonETLService.ExportToExcelAzureBlob(studata.lessonItems, _azureStorage, owner, $"{lessonRecord.id}/student-analysis.xlsx", xmlDocument, summaryes, properties);
  1774. }
  1775. }
  1776. else {
  1777. await _azureStorage.GetBlobContainerClient(owner).UploadFileByContainer(studatas.studentLessonDatas.ToJsonString(), "records", $"{lessonRecord.id}/student-analysis.json");
  1778. }
  1779. // 使用当前文化设置的日历
  1780. CultureInfo cultureInfo = CultureInfo.CurrentCulture;
  1781. Calendar calendar = cultureInfo.Calendar;
  1782. //表示如果一年的第一个星期至少有4天在同一年,则该星期被视为第一周,DayOfWeek.Monday和DayOfWeek.Sunday分别表示一周的第一天是星期一或星期日。
  1783. var week = calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
  1784. string key = $"LessonWeekly:{lessonRecord.scope}:{DateTime.Now.Year}-{week}";
  1785. _azureRedis.GetRedisClient(8).HashSet(key, $"{lessonRecord.tmdid}:{lessonRecord.id}",
  1786. new LessonWeek
  1787. {
  1788. week=week,
  1789. id = lessonRecord.id,
  1790. cid=lessonRecord.courseId,
  1791. sid= lessonRecord.subjectId,
  1792. school=lessonRecord.school,
  1793. gid= lessonRecord.groupIds?.FirstOrDefault(),
  1794. //pid= lessonRecord.periodId,
  1795. scope= lessonRecord.scope,
  1796. }.ToJsonString()
  1797. );
  1798. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, TimeSpan.FromDays(10));
  1799. }
  1800. } catch (Exception ex) {
  1801. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}处理学生课中数据发生异常,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1802. }
  1803. // DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase, _azureRedis, PickupMemberIds, taskDatas, irsDatas);
  1804. }
  1805. catch (Exception ex)
  1806. {
  1807. if (!ex.Message.Contains("The specified blob does not exist"))
  1808. {
  1809. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1810. }
  1811. }
  1812. await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
  1813. break;
  1814. //更新 时间线
  1815. case "up-TimeLine":
  1816. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1817. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1818. msgs.Add(update);
  1819. break;
  1820. //更新 课堂总览信息
  1821. case "up-ActivityInfo":
  1822. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1823. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1824. msgs.Add(update);
  1825. break;
  1826. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1827. isReplace = true;
  1828. msgs.Add(update);
  1829. break;
  1830. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1831. try
  1832. {
  1833. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1834. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1835. foreach (var record in records)
  1836. {
  1837. try
  1838. {
  1839. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1840. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1841. }
  1842. catch (Exception)
  1843. {
  1844. continue;
  1845. }
  1846. }
  1847. }
  1848. catch (Exception)
  1849. {
  1850. break;
  1851. }
  1852. isReplace = true;
  1853. msgs.Add(update);
  1854. break;
  1855. case "delete":
  1856. try
  1857. {
  1858. if (lessonRecord.expire > 0)
  1859. {
  1860. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1861. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1862. foreach (var record in records)
  1863. {
  1864. try
  1865. {
  1866. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1867. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1868. }
  1869. catch (Exception)
  1870. {
  1871. continue;
  1872. }
  1873. }
  1874. }
  1875. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1876. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1877. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1878. msgs.Add(update);
  1879. }
  1880. catch (CosmosException)
  1881. {
  1882. msgs.Add(update);
  1883. }
  1884. lessonRecord = null;
  1885. isReplace = false;
  1886. break;
  1887. case "create":
  1888. oldlessonRecord = null;
  1889. //处理课堂选用的课程信息
  1890. lessonRecord.show = teacher.lessonShow;
  1891. lessonRecord.upload = 0;
  1892. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1893. {
  1894. CourseBase course = null;
  1895. try
  1896. {
  1897. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase-{lessonRecord.school}"));
  1898. if (cresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1899. {
  1900. using var cJson = await JsonDocument.ParseAsync(cresponse.Content);
  1901. course = cJson.ToObject<CourseBase>();
  1902. }
  1903. else
  1904. {
  1905. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase"));
  1906. if (sresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1907. {
  1908. using var cJson = await JsonDocument.ParseAsync(sresponse.Content);
  1909. course = cJson.ToObject<CourseBase>();
  1910. }
  1911. else
  1912. {
  1913. course = null;
  1914. }
  1915. }
  1916. }
  1917. catch (Exception ex)
  1918. {
  1919. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1920. }
  1921. /*catch (CosmosException ex) when (ex.Status != 404)
  1922. {
  1923. try
  1924. {
  1925. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1926. }
  1927. catch (CosmosException e) when (e.Status != 404)
  1928. {
  1929. course = null;
  1930. }
  1931. }*/
  1932. if (course != null)
  1933. {
  1934. lessonRecord.periodId = course.period?.id;
  1935. lessonRecord.subjectId = course.subject?.id;
  1936. }
  1937. }
  1938. //处理课堂选用的名单
  1939. if (lessonRecord.groupIds.IsNotEmpty())
  1940. {
  1941. List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1942. if (!string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1943. {
  1944. HashSet<string> grades = new HashSet<string>();
  1945. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1946. HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
  1947. groups.ForEach(y =>
  1948. {
  1949. if (y.type.Equals("teach") || y.type.Equals("class"))
  1950. {
  1951. gd.Add(y.year);
  1952. }
  1953. });
  1954. var gpdata = SchoolService.GetGrades(schoolObj, lessonRecord.periodId, gd);
  1955. lessonRecord.grade = gpdata.grades.ToList();
  1956. }
  1957. }
  1958. try
  1959. {
  1960. if (scope.Equals("school"))
  1961. {
  1962. School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  1963. {
  1964. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  1965. { client = "hiteach", count = 1, id = schoolBase.id, key = "lesson-create", name = schoolBase.name, scope = "school", target = schoolBase.id });
  1966. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  1967. { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
  1968. }
  1969. var space = await BlobService.GetSurplusSpace(school, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
  1970. SchoolSetting setting = null;
  1971. ResponseMessage schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
  1972. if (schoolSetting.StatusCode == System.Net.HttpStatusCode.OK)
  1973. {
  1974. setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
  1975. if (setting.lessonSetting != null)
  1976. {
  1977. //两种状态都不属于,则默认未开启。
  1978. if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
  1979. {
  1980. setting.lessonSetting.openAutoClean = 0;
  1981. setting.lessonSetting.expireDays = Constant.school_lesson_expire;
  1982. }
  1983. else
  1984. {
  1985. //属于 要么开启1,要么关闭0
  1986. }
  1987. }
  1988. else
  1989. {
  1990. setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
  1991. }
  1992. }
  1993. else
  1994. {
  1995. setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
  1996. }
  1997. int school_lesson_expire = 0;
  1998. bool save = true;
  1999. if (space.surplus > 0)
  2000. {
  2001. save = true;
  2002. }
  2003. else
  2004. {
  2005. save = false;
  2006. school_lesson_expire = Constant.school_lesson_expire;
  2007. }
  2008. if (!save && school_lesson_expire > 0)
  2009. {
  2010. // 1-时间戳,7-时间戳
  2011. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2012. //暂定7天
  2013. var now = DateTimeOffset.UtcNow;
  2014. //剩余3天的通知
  2015. //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
  2016. //result.Add(3, day3);
  2017. //剩余1天的通知
  2018. var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2019. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2020. //到期通知
  2021. //不到五点上传的课例,七天之后直接删除。
  2022. int addSecond = 0;
  2023. if (now.Hour > 5)
  2024. {
  2025. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2026. addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
  2027. //再加 00到05小时内的 随机秒数
  2028. Random rand = new Random();
  2029. int randInt = rand.Next(0, 18000);
  2030. addSecond += randInt;
  2031. }
  2032. else
  2033. {
  2034. addSecond = school_lesson_expire * 24 * 60 * 60;
  2035. }
  2036. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2037. result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  2038. // result.Add(school_lesson_expire, lessonRecord.expire);
  2039. string biz = "expire";
  2040. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2041. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  2042. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-school_lessonRecord", Constant.NotifyType_IES5_Course,
  2043. new Dictionary<string, object> { { "tmdid", teacher.id }, { "tmdname", teacher.name }, { "schoolName", schoolBase.name },
  2044. { "schoolId", $"{school}" },{ "lessonId",lessonRecord.id }, { "expireTime", expireTime },{ "lessonName",lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2045. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2046. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  2047. if (records.Count <= 0)
  2048. {
  2049. foreach (var item in result)
  2050. {
  2051. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  2052. //课堂的id ,
  2053. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2054. var servicebus_message = new ServiceBusMessage(new
  2055. {
  2056. id = lessonRecord.id,
  2057. progress = item.Key,
  2058. code = lessonRecord.code,
  2059. scope = lessonRecord.scope,
  2060. school = lessonRecord.school,
  2061. opt = "delete",
  2062. expire = lessonRecord.expire,
  2063. tmdid = tmdid,
  2064. tmdname = teacher.name,
  2065. name = lessonRecord.name,
  2066. startTime = lessonRecord.startTime,
  2067. tag = item.Value.tag
  2068. }.ToJsonString());
  2069. servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2070. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2071. ChangeRecord changeRecord = new ChangeRecord
  2072. {
  2073. RowKey = lessonRecord.id,
  2074. PartitionKey = PartitionKey,
  2075. sequenceNumber = start,
  2076. msgId = servicebus_message.MessageId
  2077. };
  2078. await table.Save<ChangeRecord>(changeRecord);
  2079. }
  2080. }
  2081. }
  2082. }
  2083. //个人课例保存规则
  2084. if (scope.Equals("private"))
  2085. {
  2086. int lessonLimit = teacher.lessonLimit;
  2087. var space = await BlobService.GetSurplusSpace(tmdid, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
  2088. //20230208调整之前 if (blobTotal * 1073741824 - blobsize > 2147483648) //剩余空间大于2G
  2089. //剩余空间不足,则开启自动清理机制
  2090. if (space.surplus > 0)
  2091. {
  2092. //大于0则表示空间充足
  2093. lessonLimit = -1;
  2094. }
  2095. else
  2096. {
  2097. //20230208调整增加逻辑,之前lessonLimit用于处理默认保存50条,现在用于处理标记是否空间不足,不足则标记清理。
  2098. if ($"{Environment.GetEnvironmentVariable("Option:Location")}".Contains("Test", StringComparison.OrdinalIgnoreCase))
  2099. {
  2100. lessonLimit = 0;
  2101. }
  2102. else
  2103. {
  2104. lessonLimit = -1;
  2105. }
  2106. }
  2107. if (lessonLimit != -1)
  2108. {
  2109. #region 20230208 调整之后
  2110. {
  2111. // 1-时间戳,7-时间戳
  2112. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2113. //暂定7天
  2114. var now = DateTimeOffset.UtcNow;
  2115. //剩余3天的通知
  2116. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  2117. //result.Add(3, day3);
  2118. //剩余1天的通知
  2119. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2120. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2121. //到期通知
  2122. //不到五点上传的课例,七天之后直接删除。
  2123. int addSecond = 0;
  2124. if (now.Hour > 5)
  2125. {
  2126. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2127. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  2128. //再加 00到05小时内的 随机秒数
  2129. Random rand = new Random();
  2130. int randInt = rand.Next(0, 18000);
  2131. addSecond += randInt;
  2132. }
  2133. else
  2134. {
  2135. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  2136. }
  2137. //将当前课例标记为 自动清理
  2138. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2139. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  2140. string biz = "expire";
  2141. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2142. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2143. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecord.id }, { "lessonName", lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2144. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2145. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  2146. if (records.Count <= 0)
  2147. {
  2148. foreach (var item in result)
  2149. {
  2150. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  2151. //课堂的id ,
  2152. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2153. var servicebus_message = new ServiceBusMessage(new
  2154. {
  2155. id = lessonRecord.id,
  2156. progress = item.Key,
  2157. code = lessonRecord.code,
  2158. scope = lessonRecord.scope,
  2159. school = lessonRecord.school,
  2160. opt = "delete",
  2161. expire = lessonRecord.expire,
  2162. tmdid = tmdid,
  2163. tmdname = teacher.name,
  2164. name = lessonRecord.name,
  2165. startTime = lessonRecord.startTime,
  2166. tag = item.Value.tag
  2167. }.ToJsonString());
  2168. servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2169. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2170. ChangeRecord changeRecord = new ChangeRecord
  2171. {
  2172. RowKey = lessonRecord.id,
  2173. PartitionKey = PartitionKey,
  2174. sequenceNumber = start,
  2175. msgId = servicebus_message.MessageId
  2176. };
  2177. await table.Save<ChangeRecord>(changeRecord);
  2178. }
  2179. }
  2180. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  2181. }
  2182. #endregion 20230208 调整之后
  2183. #region 20230208 调整之前
  2184. /** 20230208 调整之前
  2185. HashSet<string> ids = new HashSet<string>();
  2186. //未定义的 以及过期时间小于等于0 的 课例
  2187. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  2188. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  2189. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  2190. {
  2191. ids.Add(item);
  2192. }
  2193. // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
  2194. //包含收藏的本人的个人课例
  2195. //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  2196. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  2197. // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  2198. //{
  2199. // ids.Add(item);
  2200. //}
  2201. //教师个人预设的,可以通过设置的方式增加
  2202. int limit = teacher.lessonLimit;
  2203. if (teacher.lessonLimit == 0)
  2204. {
  2205. //未设置的的采用系统设置的默认值50
  2206. limit = Constant.private_lesson_limit;
  2207. }
  2208. if (ids.Count >= limit)
  2209. {
  2210. LessonRecord lessonRecordExpire = null;
  2211. //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
  2212. //220712 讨论,将desc去掉,获取最旧的那一笔数据。删除最旧的
  2213. string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
  2214. $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' and c.status<>404 order by c.startTime ";
  2215. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<LessonRecord>(
  2216. queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
  2217. {
  2218. lessonRecordExpire = item; break;
  2219. }
  2220. if (lessonRecordExpire != null)
  2221. {
  2222. // 1-时间戳,7-时间戳
  2223. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2224. //暂定7天
  2225. var now = DateTimeOffset.UtcNow;
  2226. //剩余3天的通知
  2227. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  2228. //result.Add(3, day3);
  2229. //剩余1天的通知
  2230. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2231. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2232. //到期通知
  2233. //不到五点上传的课例,七天之后直接删除。
  2234. int addSecond = 0;
  2235. if (now.Hour > 5)
  2236. {
  2237. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2238. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  2239. //再加 00到05小时内的 随机秒数
  2240. Random rand = new Random();
  2241. int randInt = rand.Next(0, 18000);
  2242. addSecond += randInt;
  2243. }
  2244. else
  2245. {
  2246. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  2247. }
  2248. lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2249. //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
  2250. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
  2251. string biz = "expire";
  2252. string expireTime= DateTimeOffset.FromUnixTimeMilliseconds(lessonRecordExpire.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2253. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2254. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecordExpire.id }, { "lessonName", lessonRecordExpire. name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2255. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2256. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
  2257. if (records.Count <= 0)
  2258. {
  2259. foreach (var item in result)
  2260. {
  2261. string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
  2262. //课堂的id ,
  2263. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2264. var message = new ServiceBusMessage(new
  2265. {
  2266. id = lessonRecordExpire.id,
  2267. progress = item.Key,
  2268. code = lessonRecordExpire.code,
  2269. scope = lessonRecordExpire.scope,
  2270. school = lessonRecordExpire.school,
  2271. opt = "delete",
  2272. expire = lessonRecordExpire.expire,
  2273. tmdid = tmdid,
  2274. tmdname = teacher.name,
  2275. name = lessonRecordExpire.name,
  2276. startTime = lessonRecordExpire.startTime,
  2277. tag = item.Value.tag
  2278. }.ToJsonString());
  2279. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2280. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2281. ChangeRecord changeRecord = new ChangeRecord
  2282. {
  2283. RowKey = lessonRecordExpire.id,
  2284. PartitionKey = PartitionKey,
  2285. sequenceNumber = start,
  2286. msgId = message.MessageId
  2287. };
  2288. await table.Save<ChangeRecord>(changeRecord);
  2289. }
  2290. }
  2291. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
  2292. }
  2293. }**/
  2294. #endregion 20230208 调整之前
  2295. }
  2296. else
  2297. {
  2298. //=-1 则表示不限制上传数量
  2299. }
  2300. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  2301. { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
  2302. }
  2303. }
  2304. catch (Exception e)
  2305. {
  2306. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2307. }
  2308. msgs.Add(update);
  2309. await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 1, 0);//BI统计增/减量
  2310. break;
  2311. default:
  2312. break;
  2313. }
  2314. }
  2315. //如果被删除则不能再被更新
  2316. if (isReplace)
  2317. {
  2318. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  2319. }
  2320. //计算课堂更新前后的差值
  2321. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  2322. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  2323. }
  2324. });
  2325. }
  2326. catch (CosmosException e)
  2327. {
  2328. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2329. }
  2330. catch (Exception ex)
  2331. {
  2332. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错IESServiceBusTrigger\n{ex.Message}{ex.StackTrace}{data}{code}", GroupNames.醍摩豆服務運維群組);
  2333. }
  2334. finally
  2335. {
  2336. // Complete the message
  2337. await messageActions.CompleteMessageAsync(message);
  2338. }
  2339. }
  2340. /// <summary>
  2341. /// UseDevelopmentStorage=true
  2342. /// </summary>
  2343. /// <param name="message"></param>
  2344. /// <param name="messageActions"></param>
  2345. /// <returns></returns>
  2346. [Function("LessonRecordExpire")]
  2347. public async Task LessonRecordExpireFunc(
  2348. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%","lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")]
  2349. ServiceBusReceivedMessage message,
  2350. ServiceBusMessageActions messageActions)
  2351. {
  2352. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2353. _logger.LogInformation("Message Body: {body}", message.Body);
  2354. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2355. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2356. try
  2357. {
  2358. jsonMsg.TryGetProperty("id", out JsonElement id);
  2359. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  2360. jsonMsg.TryGetProperty("code", out JsonElement _code);
  2361. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  2362. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  2363. jsonMsg.TryGetProperty("name", out JsonElement name);
  2364. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  2365. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  2366. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  2367. jsonMsg.TryGetProperty("school", out JsonElement _school);
  2368. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  2369. var client = _azureCosmos.GetCosmosClient();
  2370. //处理到期删除
  2371. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  2372. {
  2373. string lessonId = $"{id}";
  2374. string tbname;
  2375. string school = $"{_school}";
  2376. string code = "";
  2377. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  2378. {
  2379. code = $"LessonRecord-{school}";
  2380. tbname = "School";
  2381. }
  2382. else if ($"{scope}".Equals("private"))
  2383. {
  2384. code = $"LessonRecord";
  2385. tbname = "Teacher";
  2386. }
  2387. else
  2388. {
  2389. return;
  2390. }
  2391. ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  2392. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  2393. {
  2394. LessonRecord lessonRecord;
  2395. var doc = JsonDocument.Parse(response.Content);
  2396. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  2397. lessonRecord.status = 404;
  2398. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  2399. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  2400. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  2401. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  2402. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  2403. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  2404. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  2405. }
  2406. }
  2407. string biz = "expire";
  2408. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  2409. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
  2410. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2411. new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid", tmdid }, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName", name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2412. }
  2413. catch (Exception ex)
  2414. {
  2415. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2416. }
  2417. finally
  2418. {
  2419. // Complete the message
  2420. await messageActions.CompleteMessageAsync(message);
  2421. }
  2422. }
  2423. /// <summary>
  2424. /// UseDevelopmentStorage=true
  2425. /// </summary>
  2426. /// <param name="message"></param>
  2427. /// <param name="messageActions"></param>
  2428. /// <returns></returns>
  2429. [Function("Imei")]
  2430. public async Task ImeiFunc(
  2431. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")]
  2432. ServiceBusReceivedMessage message,
  2433. ServiceBusMessageActions messageActions)
  2434. {
  2435. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2436. _logger.LogInformation("Message Body: {body}", message.Body);
  2437. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2438. var json = JsonDocument.Parse(message.Body);
  2439. try
  2440. {
  2441. var db = _azureCosmos.GetCosmosClient();
  2442. //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
  2443. if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
  2444. json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
  2445. json.RootElement.TryGetProperty("school", out JsonElement school) &&
  2446. json.RootElement.TryGetProperty("stus", out JsonElement stus))
  2447. {
  2448. try {
  2449. List<string>? stuids = System.Text.Json.JsonSerializer.Deserialize<List<string>>(stus);
  2450. if (stuids.IsNotEmpty())
  2451. {
  2452. string sqls = $"SELECT value c from c where c.channel='{channel.GetString()}' and c.school='{school.GetString()}' and c.stuid not in ({string.Join(",", stuids!.Select(x => $"'{x}'"))}) ";
  2453. var rs = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Imei>(sqls, "Imei");
  2454. if (rs.list.IsNotEmpty())
  2455. {
  2456. foreach (var imei in rs.list)
  2457. {
  2458. imei.channel=null;
  2459. imei.lessonId=null;
  2460. await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id, new PartitionKey(imei.code));
  2461. }
  2462. //await _dingDing.SendBotMsg($"{_option.Location},清理占用频道号的电子学生证,清理成功,频道号{channel},清理人数{rs.list.Count()}", GroupNames.成都开发測試群組);
  2463. }
  2464. }
  2465. } catch (Exception ex)
  2466. {
  2467. await _dingDing.SendBotMsg($"{_option.Location},清理占用频道号的电子学生证,出现异常", GroupNames.成都开发測試群組);
  2468. }
  2469. json.RootElement.TryGetProperty("imeiType", out JsonElement imeiType);
  2470. json.RootElement.TryGetProperty("lessonId", out JsonElement lessonId);
  2471. foreach (var stu in stus.EnumerateArray())
  2472. {
  2473. await foreach (var item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIteratorSql(
  2474. queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}' and c.school='{school}' ",
  2475. requestOptions: new() { PartitionKey = new($"Imei") }))
  2476. {
  2477. using var root = await JsonDocument.ParseAsync(item.Content);
  2478. if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2479. {
  2480. var doc = root.RootElement.GetProperty("Documents").EnumerateArray().First();
  2481. var imei = doc.ToObject<Imei>();
  2482. imei.channel = channel.GetString();
  2483. imei.userid = userid.GetString();
  2484. imei.lessonId = $"{lessonId}";
  2485. if (!string.IsNullOrWhiteSpace($"{imeiType}"))
  2486. {
  2487. imei.imeiType = $"{imeiType}";
  2488. }
  2489. else
  2490. {
  2491. if (imei.id.Length == 11)
  2492. {
  2493. imei.imeiType = "139zhxy";
  2494. }
  2495. else if (imei.id.Length == 15)
  2496. {
  2497. imei.imeiType = "tianbo";
  2498. }
  2499. }
  2500. await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id,new PartitionKey(imei.code));
  2501. }
  2502. }
  2503. }
  2504. }
  2505. }
  2506. catch (Exception ex)
  2507. {
  2508. await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF error\n{ex.Message}\n{ex.StackTrace}{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2509. }
  2510. finally
  2511. {
  2512. // Complete the message
  2513. await messageActions.CompleteMessageAsync(message);
  2514. }
  2515. }
  2516. /// <summary>
  2517. /// UseDevelopmentStorage=true
  2518. /// </summary>
  2519. /// <param name="message"></param>
  2520. /// <param name="messageActions"></param>
  2521. /// <returns></returns>
  2522. [Function("BlobRoot")]
  2523. public async Task BlobRoot(
  2524. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")]
  2525. ServiceBusReceivedMessage message,
  2526. ServiceBusMessageActions messageActions)
  2527. {
  2528. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2529. _logger.LogInformation("Message Body: {body}", message.Body);
  2530. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2531. try
  2532. {
  2533. _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
  2534. {
  2535. var jsonMsg = JsonDocument.Parse(message.Body).RootElement.ToObject<BlobRefreshMessage>();
  2536. if (!string.IsNullOrWhiteSpace($"{jsonMsg.root}") && !string.IsNullOrWhiteSpace($"{jsonMsg.name}"))
  2537. {
  2538. string lockKey = $"Blob:Lock:{jsonMsg.name}:{jsonMsg.root}";
  2539. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  2540. if (exist)
  2541. {
  2542. string[] uls = System.Web.HttpUtility.UrlDecode($"{jsonMsg.root}", Encoding.UTF8).Split("/");
  2543. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  2544. string name = $"{jsonMsg.name}";
  2545. await RefreshBlob(name, u);
  2546. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  2547. }
  2548. }
  2549. });
  2550. }
  2551. catch { }
  2552. finally
  2553. {
  2554. // Complete the message
  2555. await messageActions.CompleteMessageAsync(message);
  2556. }
  2557. }
  2558. /// <summary>
  2559. /// 統測評量開始結束
  2560. /// </summary>
  2561. /// <param name="message"></param>
  2562. /// <param name="messageActions"></param>
  2563. /// <returns></returns>
  2564. [Function("JointExam")]
  2565. public async Task JointExamFunc(
  2566. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointexam", Connection = "Azure:ServiceBus:ConnectionString")]
  2567. ServiceBusReceivedMessage message,
  2568. ServiceBusMessageActions messageActions)
  2569. {
  2570. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2571. _logger.LogInformation("Message Body: {body}", message.Body);
  2572. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2573. var json = JsonDocument.Parse(message.Body);
  2574. try
  2575. {
  2576. json.RootElement.TryGetProperty("id", out JsonElement id);
  2577. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  2578. json.RootElement.TryGetProperty("code", out JsonElement code);
  2579. var client = _azureCosmos.GetCosmosClient();
  2580. JointExam jointExam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<JointExam>(id.ToString(), new PartitionKey($"{code}"));
  2581. jointExam.progress = progress.ToString();
  2582. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(jointExam, id.ToString(), new PartitionKey($"{code}"));
  2583. }
  2584. catch (CosmosException e)
  2585. {
  2586. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2587. }
  2588. catch (Exception ex)
  2589. {
  2590. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2591. }
  2592. finally
  2593. { // Complete the message
  2594. await messageActions.CompleteMessageAsync(message);
  2595. }
  2596. }
  2597. /// <summary>
  2598. /// 統測活動行程進行狀況更新
  2599. /// </summary>
  2600. /// <param name="message"></param>
  2601. /// <param name="messageActions"></param>
  2602. /// <returns></returns>
  2603. [Function("JointEventSchedule")]
  2604. public async Task JointEventFunc(
  2605. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointevent-schedule", Connection = "Azure:ServiceBus:ConnectionString")]
  2606. ServiceBusReceivedMessage message,
  2607. ServiceBusMessageActions messageActions,
  2608. ExecutionContext context)
  2609. {
  2610. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2611. _logger.LogInformation("Message Body: {body}", message.Body);
  2612. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2613. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2614. jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
  2615. jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
  2616. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  2617. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2618. try
  2619. {
  2620. //多國語字典
  2621. //string rootPath = _environment.ContentRootPath;
  2622. //List<string> langList = new List<string>() { "en-us", "zh-cn", "zh-tw" };
  2623. //Dictionary<string, JObject> langDic = new Dictionary<string, JObject>();
  2624. //foreach (string langCode in langList)
  2625. //{
  2626. // string path = Path.Combine(rootPath, $"Lang/{langCode}.json");
  2627. // if (File.Exists(path))
  2628. // {
  2629. // string jsonContent = await File.ReadAllTextAsync(path);
  2630. // JObject jsonObject = JObject.Parse(jsonContent);
  2631. // langDic.Add(langCode, jsonObject);
  2632. // }
  2633. //}
  2634. bool updFlg = false;
  2635. string code = "JointEvent";
  2636. var client = _azureCosmos.GetCosmosClient();
  2637. JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<JointEvent>(jointEventId.ToString(), new PartitionKey($"{code}"));
  2638. if (jointEvent != null)
  2639. {
  2640. JointEvent.JointEventSchedule jointEventSchedule = jointEvent.schedule.Where(s => s.id.Equals($"{jointScheduleId}")).FirstOrDefault();
  2641. if (jointEventSchedule != null)
  2642. {
  2643. //DB資料處理
  2644. if (!jointEventSchedule.progress.Equals($"{progress}"))
  2645. {
  2646. jointEventSchedule.progress = $"{progress}";
  2647. updFlg = true;
  2648. }
  2649. if (updFlg)
  2650. {
  2651. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(jointEvent, jointEvent.id);
  2652. }
  2653. //訊息處理
  2654. switch (jointEventSchedule.progress)
  2655. {
  2656. case "pending":
  2657. //going訊息寄送
  2658. var msg = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "going" }.ToJsonString());
  2659. msg.ApplicationProperties.Add("name", "JointEventSchedule");
  2660. string PartitionKeyGo = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "going");
  2661. List<ChangeRecord> recordsGo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKeyGo } });
  2662. if (recordsGo.Count > 0)
  2663. {
  2664. try
  2665. {
  2666. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordsGo[0].sequenceNumber);
  2667. }
  2668. catch (ServiceBusException e) { }
  2669. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
  2670. recordsGo[0].sequenceNumber = start;
  2671. await table.SaveOrUpdate<ChangeRecord>(recordsGo[0]);
  2672. }
  2673. else
  2674. {
  2675. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
  2676. ChangeRecord changeRecord = new ChangeRecord
  2677. {
  2678. RowKey = jointEventSchedule.id,
  2679. PartitionKey = PartitionKeyGo,
  2680. sequenceNumber = start,
  2681. msgId = message.MessageId
  2682. };
  2683. await table.Save<ChangeRecord>(changeRecord);
  2684. }
  2685. break;
  2686. case "going":
  2687. //pending訊息紀錄刪除
  2688. string pkey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "pending");
  2689. await table.DeleteSingle<ChangeRecord>(pkey, jointEventSchedule.id);
  2690. //發送finish訊息
  2691. var messageEnd = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "finish" }.ToJsonString());
  2692. messageEnd.ApplicationProperties.Add("name", "JointEventSchedule");
  2693. string PartitionKeyEnd = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "finish");
  2694. List<ChangeRecord> recordsEnd = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKeyEnd } });
  2695. if (recordsEnd.Count > 0)
  2696. {
  2697. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
  2698. try {
  2699. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordsEnd[0].sequenceNumber);
  2700. }
  2701. catch (ServiceBusException e) { }
  2702. recordsEnd[0].sequenceNumber = end;
  2703. await table.SaveOrUpdate<ChangeRecord>(recordsEnd[0]);
  2704. }
  2705. else
  2706. {
  2707. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
  2708. ChangeRecord changeRecord = new ChangeRecord
  2709. {
  2710. RowKey = jointEventSchedule.id,
  2711. PartitionKey = PartitionKeyEnd,
  2712. sequenceNumber = end,
  2713. msgId = messageEnd.MessageId
  2714. };
  2715. await table.Save<ChangeRecord>(changeRecord);
  2716. }
  2717. //寄發Email
  2718. if(jointEventSchedule.type.Equals("exam"))
  2719. {
  2720. string type = string.Empty;
  2721. string tablePartitionKey = string.Empty;
  2722. string tableRowKey = string.Empty;
  2723. long emitTime = 0;
  2724. //熱身賽
  2725. if (jointEventSchedule.examType.Equals("regular"))
  2726. {
  2727. //熱身賽開始
  2728. type = "regularExamStart";
  2729. emitTime = jointEventSchedule.startTime;
  2730. var messageRegularSt = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2731. messageRegularSt.ApplicationProperties.Add("name", "JointMessage");
  2732. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2733. tableRowKey = $"{jointEventSchedule.id}";
  2734. List<ChangeRecord> recordRegularSt = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2735. if (recordRegularSt.Count > 0)
  2736. {
  2737. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2738. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordRegularSt[0].sequenceNumber);
  2739. recordRegularSt[0].sequenceNumber = sr;
  2740. await table.SaveOrUpdate<ChangeRecord>(recordRegularSt[0]);
  2741. }
  2742. else
  2743. {
  2744. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2745. ChangeRecord changeRecord = new ChangeRecord
  2746. {
  2747. RowKey = tableRowKey,
  2748. PartitionKey = tablePartitionKey,
  2749. sequenceNumber = sr,
  2750. msgId = messageRegularSt.MessageId
  2751. };
  2752. await table.Save<ChangeRecord>(changeRecord);
  2753. }
  2754. //熱身賽即將結束
  2755. type = "regularExamEndSoon";
  2756. DateTimeOffset dateTimeEnd = DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime);
  2757. dateTimeEnd = dateTimeEnd.AddDays(-1);
  2758. DateTimeOffset emitTimeOffset = new DateTimeOffset(dateTimeEnd.Year, dateTimeEnd.Month, dateTimeEnd.Day, 0, 0, 0, DateTimeOffset.UtcNow.Offset);
  2759. emitTime = emitTimeOffset.ToUnixTimeMilliseconds();
  2760. var messageRegularSo = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2761. messageRegularSo.ApplicationProperties.Add("name", "JointMessage");
  2762. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2763. tableRowKey = $"{jointEventSchedule.id}";
  2764. List<ChangeRecord> recordRegularSo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2765. if (recordRegularSo.Count > 0)
  2766. {
  2767. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2768. try
  2769. {
  2770. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordRegularSo[0].sequenceNumber);
  2771. }
  2772. catch (ServiceBusException e) { }
  2773. recordRegularSo[0].sequenceNumber = sr;
  2774. await table.SaveOrUpdate<ChangeRecord>(recordRegularSo[0]);
  2775. }
  2776. else
  2777. {
  2778. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2779. ChangeRecord changeRecord = new ChangeRecord
  2780. {
  2781. RowKey = tableRowKey,
  2782. PartitionKey = tablePartitionKey,
  2783. sequenceNumber = sr,
  2784. msgId = messageRegularSt.MessageId
  2785. };
  2786. await table.Save<ChangeRecord>(changeRecord);
  2787. }
  2788. }
  2789. //決賽
  2790. else if(jointEventSchedule.examType.Equals("custom"))
  2791. {
  2792. //決賽開始
  2793. type = "customExamStart";
  2794. emitTime = jointEventSchedule.startTime;
  2795. var messageCustomSt = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2796. messageCustomSt.ApplicationProperties.Add("name", "JointMessage");
  2797. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2798. tableRowKey = $"{jointEventSchedule.id}";
  2799. List<ChangeRecord> recordCustomSt = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2800. if (recordCustomSt.Count > 0)
  2801. {
  2802. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2803. try
  2804. {
  2805. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordCustomSt[0].sequenceNumber);
  2806. }
  2807. catch (ServiceBusException e) { }
  2808. recordCustomSt[0].sequenceNumber = sr;
  2809. await table.SaveOrUpdate<ChangeRecord>(recordCustomSt[0]);
  2810. }
  2811. else
  2812. {
  2813. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2814. ChangeRecord changeRecord = new ChangeRecord
  2815. {
  2816. RowKey = tableRowKey,
  2817. PartitionKey = tablePartitionKey,
  2818. sequenceNumber = sr,
  2819. msgId = messageCustomSt.MessageId
  2820. };
  2821. await table.Save<ChangeRecord>(changeRecord);
  2822. }
  2823. //決賽即將結束
  2824. type = "customExamEndSoon";
  2825. DateTimeOffset dateTimeEnd = DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime);
  2826. dateTimeEnd = dateTimeEnd.AddDays(-1);
  2827. DateTimeOffset emitTimeOffset = new DateTimeOffset(dateTimeEnd.Year, dateTimeEnd.Month, dateTimeEnd.Day, 0, 0, 0, DateTimeOffset.UtcNow.Offset);
  2828. emitTime = emitTimeOffset.ToUnixTimeMilliseconds();
  2829. var messageCustomSo = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2830. messageCustomSo.ApplicationProperties.Add("name", "JointMessage");
  2831. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2832. tableRowKey = $"{jointEventSchedule.id}";
  2833. List<ChangeRecord> recordCustomSo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2834. if (recordCustomSo.Count > 0)
  2835. {
  2836. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2837. try
  2838. {
  2839. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordCustomSo[0].sequenceNumber);
  2840. }
  2841. catch (ServiceBusException e) { }
  2842. recordCustomSo[0].sequenceNumber = sr;
  2843. await table.SaveOrUpdate<ChangeRecord>(recordCustomSo[0]);
  2844. }
  2845. else
  2846. {
  2847. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2848. ChangeRecord changeRecord = new ChangeRecord
  2849. {
  2850. RowKey = tableRowKey,
  2851. PartitionKey = tablePartitionKey,
  2852. sequenceNumber = sr,
  2853. msgId = messageCustomSo.MessageId
  2854. };
  2855. await table.Save<ChangeRecord>(changeRecord);
  2856. }
  2857. }
  2858. }
  2859. break;
  2860. case "finish":
  2861. //熱身賽結束,生成決賽名單
  2862. if (jointEventSchedule.type.Equals("exam") && jointEventSchedule.examType.Equals("regular"))
  2863. {
  2864. List<string> jointGroupIds = jointEvent.groups.Select(g => g.id).ToList();
  2865. if (jointGroupIds.Count > 0)
  2866. {
  2867. string scope = "private";
  2868. int classCnt = 0;
  2869. foreach (string jointGroupId in jointGroupIds)
  2870. {
  2871. object addResult = await JointService.CreatePassJointCourseBySchedule(client, jointEvent.id, jointGroupId, jointEventSchedule.id, scope, true, classCnt);
  2872. classCnt = Int32.Parse(addResult.GetType().GetProperty("classCnt").GetValue(addResult).ToString());
  2873. }
  2874. }
  2875. }
  2876. break;
  2877. }
  2878. }
  2879. }
  2880. }
  2881. catch (CosmosException e)
  2882. {
  2883. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2884. }
  2885. catch (Exception ex)
  2886. {
  2887. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2888. }
  2889. finally
  2890. {
  2891. //自身訊息紀錄刪除
  2892. string PartitionKey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", $"{progress}"); //主key: JointEvent-{jointEventId}-schedule-{progress} RowKey: {jointScheduleId}
  2893. await table.DeleteSingle<ChangeRecord>(PartitionKey, $"{jointScheduleId}");
  2894. // Complete the message
  2895. await messageActions.CompleteMessageAsync(message);
  2896. }
  2897. }
  2898. /// <summary>
  2899. /// 統測活動訊息寄送
  2900. /// </summary>
  2901. /// <param name="message"></param>
  2902. /// <param name="messageActions"></param>
  2903. /// <returns></returns>
  2904. [Function("JointEventSendMessage")]
  2905. public async Task JointEventSendMessageFunc(
  2906. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointmessage", Connection = "Azure:ServiceBus:ConnectionString")]
  2907. ServiceBusReceivedMessage message,
  2908. ServiceBusMessageActions messageActions,
  2909. ExecutionContext context)
  2910. {
  2911. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2912. _logger.LogInformation("Message Body: {body}", message.Body);
  2913. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2914. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2915. jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
  2916. jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
  2917. jsonMsg.TryGetProperty("type", out JsonElement type);
  2918. string location = Environment.GetEnvironmentVariable("Option:Location");
  2919. var client = _azureCosmos.GetCosmosClient();
  2920. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2921. string lang = (location.Contains("China")) ? "zh-cn" : "zh-tw";
  2922. long time = (jsonMsg.TryGetProperty("time", out JsonElement _time)) ? _time.GetInt64() : new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
  2923. try
  2924. {
  2925. StringBuilder sqlStr = new StringBuilder($"SELECT DISTINCT c.creatorId, c.creatorName, c.creatorEmail FROM c WHERE c.jointEventId = '{jointEventId}' ");
  2926. string tid = string.Empty;
  2927. switch (type.ToString())
  2928. {
  2929. //熱身賽開始
  2930. case "regularExamStart":
  2931. sqlStr.Append($" AND c.type = 'regular' ");
  2932. tid = (location.Contains("China")) ? "" : "d-ba5d29036f81460c841fadaac7d35b6b"; //熱身賽開始
  2933. break;
  2934. //熱身賽即將結束
  2935. case "regularExamEndSoon":
  2936. sqlStr.Append($" AND c.type = 'regular' ");
  2937. tid = (location.Contains("China")) ? "" : "d-359ec5e40e244aceb4d04f42e52af29d"; //熱身賽即將結束
  2938. break;
  2939. //決賽開始
  2940. case "customExamStart":
  2941. sqlStr.Append($" AND c.type = 'custom' ");
  2942. break;
  2943. //決賽即將結束
  2944. case "customExamEndSoon":
  2945. sqlStr.Append($" AND c.type = 'custom' ");
  2946. break;
  2947. }
  2948. //取得收信者
  2949. List<dynamic> mailUsers = new List<dynamic>();
  2950. await foreach (var jc in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql(queryText: sqlStr.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointCourse") }))
  2951. {
  2952. using var json = await JsonDocument.ParseAsync(jc.Content);
  2953. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2954. {
  2955. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2956. {
  2957. EmailUser user = new EmailUser();
  2958. user.tmid = (obj.TryGetProperty("creatorId", out JsonElement _creatorId)) ? _creatorId.GetString() : string.Empty;
  2959. user.name = (obj.TryGetProperty("creatorName", out JsonElement _creatorName)) ? _creatorName.GetString() : string.Empty;
  2960. user.email = (obj.TryGetProperty("creatorEmail", out JsonElement _creatorEmail)) ? _creatorEmail.GetString() : string.Empty;
  2961. if (!string.IsNullOrWhiteSpace(user.tmid) && !string.IsNullOrWhiteSpace(user.email))
  2962. {
  2963. mailUsers.Add(user);
  2964. }
  2965. }
  2966. }
  2967. }
  2968. //寄發Email
  2969. if (mailUsers.Count > 0)
  2970. {
  2971. if(location.Contains("-Test")) await _dingDing.SendBotMsg($"寄送活動Email type:{type.ToString()} 寄送人數:{mailUsers.Count}人", GroupNames.研發C組);
  2972. //熱身賽開始 Mail發送
  2973. foreach (dynamic user in mailUsers)
  2974. {
  2975. if (!string.IsNullOrWhiteSpace(tid)) //※無模板ID不發
  2976. {
  2977. await _coreAPIHttpService.SendMail(new Dictionary<string, object> { { "to", user.email }, { "tid", tid }, { "vars", new { name = user.name } } }, location, _configuration);
  2978. }
  2979. }
  2980. }
  2981. }
  2982. catch (Exception ex)
  2983. {
  2984. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")} 統測活動Email寄送錯誤:\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2985. }
  2986. finally
  2987. {
  2988. //自身訊息紀錄刪除
  2989. string tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2990. string tableRowKey = $"{jointScheduleId}";
  2991. await table.DeleteSingle<ChangeRecord>(tablePartitionKey, tableRowKey);
  2992. // Complete the message
  2993. await messageActions.CompleteMessageAsync(message);
  2994. }
  2995. }
  2996. private async Task RefreshBlob(string name, string u)
  2997. {
  2998. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2999. var client = _azureStorage.GetBlobContainerClient(name);
  3000. var size = await client.GetBlobsSize(u);
  3001. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  3002. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  3003. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  3004. double blobsize = 0;
  3005. if (scores != default && scores != null)
  3006. {
  3007. foreach (var score in scores)
  3008. {
  3009. blobsize = blobsize + score.Score;
  3010. }
  3011. }
  3012. if (blobsize > 0)
  3013. {
  3014. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  3015. }
  3016. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  3017. long dis = (end - statr) / 1000;
  3018. long timeout = 60 * 5;
  3019. if (dis > timeout)
  3020. {
  3021. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
  3022. }
  3023. //await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
  3024. }
  3025. private class EmailUser
  3026. {
  3027. public string tmid { get; set; }
  3028. public string name { get; set; }
  3029. public string email { get; set; }
  3030. }
  3031. }
  3032. }