IESServiceBusTrigger.cs 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138
  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.Common;
  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.learningCategory = lessonBase.summary.learningCategory;
  1578. if (lessonRecord.learningCategory == null)
  1579. {
  1580. lessonRecord.learningCategory = new LearningCategory();
  1581. }
  1582. if (lessonRecord.hitaClientCmpCount > 0)
  1583. {
  1584. lessonRecord.learningCategory.cooperation = 1;
  1585. }
  1586. if (!string.IsNullOrWhiteSpace(lessonRecord.school))
  1587. {
  1588. lessonBase.student.ForEach(x =>
  1589. {
  1590. if (string.IsNullOrWhiteSpace(x.school))
  1591. {
  1592. x.school = lessonRecord.school;
  1593. }
  1594. });
  1595. }
  1596. //计算TP灯
  1597. {
  1598. int T = -1;
  1599. int P = -1;
  1600. if (lessonRecord.clientInteractionAverge <= 0)
  1601. {
  1602. T = 0;
  1603. }
  1604. else if (lessonRecord.clientInteractionAverge > 0 && lessonRecord.clientInteractionAverge < 2)
  1605. // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
  1606. {
  1607. T = 1;
  1608. }
  1609. else
  1610. {
  1611. T = 2;
  1612. }
  1613. //if (lessonRecord.examCount > 0)
  1614. //{
  1615. // //有评测次数大于0则P是直接绿灯
  1616. // P = 2;
  1617. //}
  1618. //else {
  1619. //}
  1620. int a = lessonRecord.hitaClientCmpCount;
  1621. int b = lessonRecord.pushCount;
  1622. int c = lessonRecord.examCount;
  1623. switch (true)
  1624. {
  1625. case bool when T == 0:
  1626. P = 0;
  1627. break;
  1628. case bool when T == 1 || T == 2:
  1629. if (a == 0 && b == 0 && c == 0)
  1630. {
  1631. P = 0;
  1632. }
  1633. else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
  1634. {
  1635. P = 2;
  1636. }
  1637. else
  1638. {
  1639. P = 1;
  1640. }
  1641. break;
  1642. }
  1643. lessonRecord.tLevel = T;
  1644. lessonRecord.pLevel = P;
  1645. }
  1646. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1647. //{
  1648. // clientSummaryList = lessonBase.report.clientSummaryList,
  1649. // students = lessonBase.student,
  1650. // name = lessonRecord.name,
  1651. // school = lessonRecord.school,
  1652. // id = lessonRecord.id,
  1653. // scope = lessonRecord.scope,
  1654. // tmdid = lessonRecord.tmdid,
  1655. // code = "LessonStudentRecord",
  1656. // pk = "LessonStudentRecord",
  1657. // courseId =lessonRecord.courseId,
  1658. // groupIds= lessonRecord.groupIds,
  1659. // periodId = lessonRecord.periodId,
  1660. // subjectId = lessonRecord.subjectId,
  1661. //};
  1662. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1663. }
  1664. //有上传 base.josn.
  1665. lessonRecord.upload = 1;
  1666. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1667. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, _coreAPIHttpService, _dingDing, _azureRedis);
  1668. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1669. Bloblog bloblog = new Bloblog
  1670. {
  1671. id = lessonRecord.id,
  1672. code = $"Bloblog-{blobname}",
  1673. name = lessonRecord.name,
  1674. pk = "Bloblog",
  1675. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1676. type = "records",
  1677. url = $"records/{_lessonId}",
  1678. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1679. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1680. size = size.HasValue ? size.Value : 0,
  1681. };
  1682. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1683. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1684. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1685. msgs.Add(update);
  1686. List<ExamData> examDatas = new List<ExamData>();
  1687. if (lessonBase!=null && lessonBase.student!=null)
  1688. {
  1689. string owner = lessonRecord.scope.Equals("school") ? lessonRecord.school : lessonRecord.tmdid;
  1690. examDatas = await LessonETLService.GetExamInfo(lessonRecord, timeLineData, _azureStorage, owner);
  1691. sokratesDatas= sokratesDatas.IsNotEmpty() ? sokratesDatas : timeLineData!=null ? timeLineData.events : new List<TimeLineEvent>();
  1692. }
  1693. LessonLocal lessonLocal = new LessonLocal()
  1694. {
  1695. lessonBase=lessonBase,
  1696. timeLineData= timeLineData,
  1697. lessonRecord= lessonRecord,
  1698. taskDatas= taskDatas,
  1699. smartRatingDatas= smartRatingDatas,
  1700. irsDatas= irsDatas,
  1701. coworkDatas= coworkDatas,
  1702. examDatas=examDatas,
  1703. sokratesDatas= sokratesDatas,
  1704. studentLessonDatas=studentLessonDatas
  1705. };
  1706. try {
  1707. if (lessonRecord.duration>0 && lessonRecord.scope.Equals("school"))
  1708. {
  1709. var location = Environment.GetEnvironmentVariable("Option:Location");
  1710. var studatas = LessonETLService.GenStudentLessonData(lessonLocal, Constant.objectiveTypes );
  1711. string owner = lessonRecord.scope.Equals("school") ? lessonRecord.school : lessonRecord.tmdid;
  1712. if (location.Equals("China", StringComparison.OrdinalIgnoreCase))
  1713. {
  1714. List<School> schools = new List<School>();
  1715. List<StudentSemesterRecord> studentSemesterRecords = new List<StudentSemesterRecord>();
  1716. List<OverallEducation> overallEducations = new List<OverallEducation>();
  1717. List<Student> studentsBase = new List<Student>();
  1718. List<StudentSemesterRecord> students = new List<StudentSemesterRecord>();
  1719. LessonDataAnalysisModel lessonDataAnalysis = null;
  1720. bool exists = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient($"/lesson/analysis/analysis-model.json").ExistsAsync();
  1721. if (exists)
  1722. {
  1723. BlobDownloadResult blobDownload = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient($"/lesson/analysis/analysis-model.json").DownloadContentAsync();
  1724. lessonDataAnalysis = blobDownload.Content.ToObjectFromJson<LessonDataAnalysisModel>();
  1725. string studentSql = $"select value c from c where c.id in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))})";
  1726. var studentResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(studentSql, $"Base-{school}");
  1727. if (studentResults.list.IsNotEmpty())
  1728. {
  1729. studentsBase.AddRange(studentResults.list);
  1730. }
  1731. School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  1732. schools.Add(schoolBase);
  1733. string? periodId = !string.IsNullOrWhiteSpace(lessonLocal.lessonRecord.periodId) ? lessonLocal.lessonRecord.periodId : schoolBase.period.FirstOrDefault()?.id;
  1734. var period = schoolBase.period.Find(x => x.id.Equals(periodId));
  1735. var semester = SchoolService.GetSemester(period, lessonLocal.lessonRecord.startTime);
  1736. string code = $"StudentSemesterRecord-{schoolBase.id}";
  1737. 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}";
  1738. var studentSemesterRecordResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<StudentSemesterRecord>(studentSemesterRecordSql, code);
  1739. if (studentSemesterRecordResults.list.IsNotEmpty())
  1740. {
  1741. studentSemesterRecords.AddRange(studentSemesterRecordResults.list);
  1742. }
  1743. 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}";
  1744. var overallEducationResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<OverallEducation>(overallEducationSql, $"OverallEducation-{schoolBase.id}");
  1745. if (overallEducationResults.list.IsNotEmpty())
  1746. {
  1747. overallEducations.AddRange(overallEducationResults.list);
  1748. }
  1749. var studata = LessonETLService.DoStudentLessonDataV2(Constant.objectiveTypes, lessonLocal, location, studentSemesterRecords, overallEducations, lessonDataAnalysis, studentsBase, schools);
  1750. await Parallel.ForEachAsync(studentSemesterRecords, async (studentSemester, cancellationToken) =>
  1751. {
  1752. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(studentSemester, new PartitionKey(studentSemester.code));
  1753. });
  1754. await Parallel.ForEachAsync(overallEducations, async (overallEducation, cancellationToken) =>
  1755. {
  1756. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(overallEducation, partitionKey: new PartitionKey(overallEducation.code));
  1757. string key = $"OverallEducation:{overallEducation.schoolCode}:{overallEducation.periodId}:{overallEducation.year}:{overallEducation.semesterId}:{overallEducation?.classId}";
  1758. await _azureRedis.GetRedisClient(8).HashSetAsync(key, overallEducation.studentId, overallEducation.ToJsonString());
  1759. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 *24, 0, 0));
  1760. });
  1761. await _azureStorage.GetBlobContainerClient(owner).UploadFileByContainer(studata.studentLessonDatas.ToJsonString(), "records", $"{lessonRecord.id}/student-analysis.json");
  1762. XmlDocument xmlDocument = new XmlDocument();
  1763. var runtimePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  1764. xmlDocument.Load($"{runtimePath}\\summary.xml");
  1765. PropertyInfo[] properties = typeof(StudentLessonItem).GetProperties();
  1766. List<string> summaryes = new List<string>();
  1767. for (int i = 0; i < properties.Length; i++)
  1768. {
  1769. string summary = Regex.Replace(LessonETLService.GetPropertySummary(properties[i], xmlDocument), @"\s+", "");
  1770. summaryes.Add(summary);
  1771. }
  1772. await LessonETLService.ExportToExcelAzureBlob(studata.lessonItems, _azureStorage, owner, $"{lessonRecord.id}/student-analysis.xlsx", xmlDocument, summaryes, properties);
  1773. }
  1774. }
  1775. else {
  1776. await _azureStorage.GetBlobContainerClient(owner).UploadFileByContainer(studatas.studentLessonDatas.ToJsonString(), "records", $"{lessonRecord.id}/student-analysis.json");
  1777. }
  1778. // 使用当前文化设置的日历
  1779. CultureInfo cultureInfo = CultureInfo.CurrentCulture;
  1780. Calendar calendar = cultureInfo.Calendar;
  1781. //表示如果一年的第一个星期至少有4天在同一年,则该星期被视为第一周,DayOfWeek.Monday和DayOfWeek.Sunday分别表示一周的第一天是星期一或星期日。
  1782. var week = calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
  1783. string key = $"LessonWeekly:{lessonRecord.scope}:{DateTime.Now.Year}-{week}";
  1784. _azureRedis.GetRedisClient(8).HashSet(key, $"{lessonRecord.tmdid}:{lessonRecord.id}",
  1785. new LessonWeek
  1786. {
  1787. week=week,
  1788. id = lessonRecord.id,
  1789. cid=lessonRecord.courseId,
  1790. sid= lessonRecord.subjectId,
  1791. school=lessonRecord.school,
  1792. gid= lessonRecord.groupIds?.FirstOrDefault(),
  1793. //pid= lessonRecord.periodId,
  1794. scope= lessonRecord.scope,
  1795. }.ToJsonString()
  1796. );
  1797. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, TimeSpan.FromDays(10));
  1798. }
  1799. } catch (Exception ex) {
  1800. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}处理学生课中数据发生异常,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1801. }
  1802. // DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase, _azureRedis, PickupMemberIds, taskDatas, irsDatas);
  1803. }
  1804. catch (Exception ex)
  1805. {
  1806. if (!ex.Message.Contains("The specified blob does not exist"))
  1807. {
  1808. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1809. }
  1810. }
  1811. await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
  1812. break;
  1813. //更新 时间线
  1814. case "up-TimeLine":
  1815. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1816. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1817. msgs.Add(update);
  1818. break;
  1819. //更新 课堂总览信息
  1820. case "up-ActivityInfo":
  1821. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1822. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1823. msgs.Add(update);
  1824. break;
  1825. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1826. isReplace = true;
  1827. msgs.Add(update);
  1828. break;
  1829. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1830. try
  1831. {
  1832. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1833. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1834. foreach (var record in records)
  1835. {
  1836. try
  1837. {
  1838. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1839. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1840. }
  1841. catch (Exception)
  1842. {
  1843. continue;
  1844. }
  1845. }
  1846. }
  1847. catch (Exception)
  1848. {
  1849. break;
  1850. }
  1851. isReplace = true;
  1852. msgs.Add(update);
  1853. break;
  1854. case "delete":
  1855. try
  1856. {
  1857. if (lessonRecord.expire > 0)
  1858. {
  1859. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1860. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1861. foreach (var record in records)
  1862. {
  1863. try
  1864. {
  1865. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1866. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1867. }
  1868. catch (Exception)
  1869. {
  1870. continue;
  1871. }
  1872. }
  1873. }
  1874. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1875. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1876. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1877. msgs.Add(update);
  1878. }
  1879. catch (CosmosException)
  1880. {
  1881. msgs.Add(update);
  1882. }
  1883. lessonRecord = null;
  1884. isReplace = false;
  1885. break;
  1886. case "create":
  1887. oldlessonRecord = null;
  1888. //处理课堂选用的课程信息
  1889. lessonRecord.show = teacher.lessonShow;
  1890. lessonRecord.upload = 0;
  1891. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1892. {
  1893. CourseBase course = null;
  1894. try
  1895. {
  1896. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase-{lessonRecord.school}"));
  1897. if (cresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1898. {
  1899. using var cJson = await JsonDocument.ParseAsync(cresponse.Content);
  1900. course = cJson.ToObject<CourseBase>();
  1901. }
  1902. else
  1903. {
  1904. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase"));
  1905. if (sresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1906. {
  1907. using var cJson = await JsonDocument.ParseAsync(sresponse.Content);
  1908. course = cJson.ToObject<CourseBase>();
  1909. }
  1910. else
  1911. {
  1912. course = null;
  1913. }
  1914. }
  1915. }
  1916. catch (Exception ex)
  1917. {
  1918. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1919. }
  1920. /*catch (CosmosException ex) when (ex.Status != 404)
  1921. {
  1922. try
  1923. {
  1924. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1925. }
  1926. catch (CosmosException e) when (e.Status != 404)
  1927. {
  1928. course = null;
  1929. }
  1930. }*/
  1931. if (course != null)
  1932. {
  1933. lessonRecord.periodId = course.period?.id;
  1934. lessonRecord.subjectId = course.subject?.id;
  1935. }
  1936. }
  1937. //处理课堂选用的名单
  1938. if (lessonRecord.groupIds.IsNotEmpty())
  1939. {
  1940. List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1941. if (!string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1942. {
  1943. HashSet<string> grades = new HashSet<string>();
  1944. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1945. HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
  1946. groups.ForEach(y =>
  1947. {
  1948. if (y.type.Equals("teach") || y.type.Equals("class"))
  1949. {
  1950. gd.Add(y.year);
  1951. }
  1952. });
  1953. var gpdata = SchoolService.GetGrades(schoolObj, lessonRecord.periodId, gd);
  1954. lessonRecord.grade = gpdata.grades.ToList();
  1955. }
  1956. }
  1957. try
  1958. {
  1959. if (scope.Equals("school"))
  1960. {
  1961. School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  1962. {
  1963. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  1964. { client = "hiteach", count = 1, id = schoolBase.id, key = "lesson-create", name = schoolBase.name, scope = "school", target = schoolBase.id });
  1965. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  1966. { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
  1967. }
  1968. var space = await BlobService.GetSurplusSpace(school, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
  1969. SchoolSetting setting = null;
  1970. ResponseMessage schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
  1971. if (schoolSetting.StatusCode == System.Net.HttpStatusCode.OK)
  1972. {
  1973. setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
  1974. if (setting.lessonSetting != null)
  1975. {
  1976. //两种状态都不属于,则默认未开启。
  1977. if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
  1978. {
  1979. setting.lessonSetting.openAutoClean = 0;
  1980. setting.lessonSetting.expireDays = Constant.school_lesson_expire;
  1981. }
  1982. else
  1983. {
  1984. //属于 要么开启1,要么关闭0
  1985. }
  1986. }
  1987. else
  1988. {
  1989. setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
  1990. }
  1991. }
  1992. else
  1993. {
  1994. setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
  1995. }
  1996. int school_lesson_expire = 0;
  1997. bool save = true;
  1998. if (space.surplus > 0)
  1999. {
  2000. save = true;
  2001. }
  2002. else
  2003. {
  2004. save = false;
  2005. school_lesson_expire = Constant.school_lesson_expire;
  2006. }
  2007. if (!save && school_lesson_expire > 0)
  2008. {
  2009. // 1-时间戳,7-时间戳
  2010. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2011. //暂定7天
  2012. var now = DateTimeOffset.UtcNow;
  2013. //剩余3天的通知
  2014. //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
  2015. //result.Add(3, day3);
  2016. //剩余1天的通知
  2017. var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2018. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2019. //到期通知
  2020. //不到五点上传的课例,七天之后直接删除。
  2021. int addSecond = 0;
  2022. if (now.Hour > 5)
  2023. {
  2024. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2025. addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
  2026. //再加 00到05小时内的 随机秒数
  2027. Random rand = new Random();
  2028. int randInt = rand.Next(0, 18000);
  2029. addSecond += randInt;
  2030. }
  2031. else
  2032. {
  2033. addSecond = school_lesson_expire * 24 * 60 * 60;
  2034. }
  2035. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2036. result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  2037. // result.Add(school_lesson_expire, lessonRecord.expire);
  2038. string biz = "expire";
  2039. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2040. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  2041. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-school_lessonRecord", Constant.NotifyType_IES5_Course,
  2042. new Dictionary<string, object> { { "tmdid", teacher.id }, { "tmdname", teacher.name }, { "schoolName", schoolBase.name },
  2043. { "schoolId", $"{school}" },{ "lessonId",lessonRecord.id }, { "expireTime", expireTime },{ "lessonName",lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2044. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2045. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  2046. if (records.Count <= 0)
  2047. {
  2048. foreach (var item in result)
  2049. {
  2050. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  2051. //课堂的id ,
  2052. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2053. var servicebus_message = new ServiceBusMessage(new
  2054. {
  2055. id = lessonRecord.id,
  2056. progress = item.Key,
  2057. code = lessonRecord.code,
  2058. scope = lessonRecord.scope,
  2059. school = lessonRecord.school,
  2060. opt = "delete",
  2061. expire = lessonRecord.expire,
  2062. tmdid = tmdid,
  2063. tmdname = teacher.name,
  2064. name = lessonRecord.name,
  2065. startTime = lessonRecord.startTime,
  2066. tag = item.Value.tag
  2067. }.ToJsonString());
  2068. servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2069. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2070. ChangeRecord changeRecord = new ChangeRecord
  2071. {
  2072. RowKey = lessonRecord.id,
  2073. PartitionKey = PartitionKey,
  2074. sequenceNumber = start,
  2075. msgId = servicebus_message.MessageId
  2076. };
  2077. await table.Save<ChangeRecord>(changeRecord);
  2078. }
  2079. }
  2080. }
  2081. }
  2082. //个人课例保存规则
  2083. if (scope.Equals("private"))
  2084. {
  2085. int lessonLimit = teacher.lessonLimit;
  2086. var space = await BlobService.GetSurplusSpace(tmdid, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
  2087. //20230208调整之前 if (blobTotal * 1073741824 - blobsize > 2147483648) //剩余空间大于2G
  2088. //剩余空间不足,则开启自动清理机制
  2089. if (space.surplus > 0)
  2090. {
  2091. //大于0则表示空间充足
  2092. lessonLimit = -1;
  2093. }
  2094. else
  2095. {
  2096. //20230208调整增加逻辑,之前lessonLimit用于处理默认保存50条,现在用于处理标记是否空间不足,不足则标记清理。
  2097. if ($"{Environment.GetEnvironmentVariable("Option:Location")}".Contains("Test", StringComparison.OrdinalIgnoreCase))
  2098. {
  2099. lessonLimit = 0;
  2100. }
  2101. else
  2102. {
  2103. lessonLimit = -1;
  2104. }
  2105. }
  2106. if (lessonLimit != -1)
  2107. {
  2108. #region 20230208 调整之后
  2109. {
  2110. // 1-时间戳,7-时间戳
  2111. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2112. //暂定7天
  2113. var now = DateTimeOffset.UtcNow;
  2114. //剩余3天的通知
  2115. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  2116. //result.Add(3, day3);
  2117. //剩余1天的通知
  2118. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2119. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2120. //到期通知
  2121. //不到五点上传的课例,七天之后直接删除。
  2122. int addSecond = 0;
  2123. if (now.Hour > 5)
  2124. {
  2125. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2126. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  2127. //再加 00到05小时内的 随机秒数
  2128. Random rand = new Random();
  2129. int randInt = rand.Next(0, 18000);
  2130. addSecond += randInt;
  2131. }
  2132. else
  2133. {
  2134. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  2135. }
  2136. //将当前课例标记为 自动清理
  2137. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2138. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  2139. string biz = "expire";
  2140. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2141. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2142. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecord.id }, { "lessonName", lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2143. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2144. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  2145. if (records.Count <= 0)
  2146. {
  2147. foreach (var item in result)
  2148. {
  2149. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  2150. //课堂的id ,
  2151. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2152. var servicebus_message = new ServiceBusMessage(new
  2153. {
  2154. id = lessonRecord.id,
  2155. progress = item.Key,
  2156. code = lessonRecord.code,
  2157. scope = lessonRecord.scope,
  2158. school = lessonRecord.school,
  2159. opt = "delete",
  2160. expire = lessonRecord.expire,
  2161. tmdid = tmdid,
  2162. tmdname = teacher.name,
  2163. name = lessonRecord.name,
  2164. startTime = lessonRecord.startTime,
  2165. tag = item.Value.tag
  2166. }.ToJsonString());
  2167. servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2168. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2169. ChangeRecord changeRecord = new ChangeRecord
  2170. {
  2171. RowKey = lessonRecord.id,
  2172. PartitionKey = PartitionKey,
  2173. sequenceNumber = start,
  2174. msgId = servicebus_message.MessageId
  2175. };
  2176. await table.Save<ChangeRecord>(changeRecord);
  2177. }
  2178. }
  2179. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  2180. }
  2181. #endregion 20230208 调整之后
  2182. #region 20230208 调整之前
  2183. /** 20230208 调整之前
  2184. HashSet<string> ids = new HashSet<string>();
  2185. //未定义的 以及过期时间小于等于0 的 课例
  2186. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  2187. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  2188. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  2189. {
  2190. ids.Add(item);
  2191. }
  2192. // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
  2193. //包含收藏的本人的个人课例
  2194. //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  2195. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  2196. // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  2197. //{
  2198. // ids.Add(item);
  2199. //}
  2200. //教师个人预设的,可以通过设置的方式增加
  2201. int limit = teacher.lessonLimit;
  2202. if (teacher.lessonLimit == 0)
  2203. {
  2204. //未设置的的采用系统设置的默认值50
  2205. limit = Constant.private_lesson_limit;
  2206. }
  2207. if (ids.Count >= limit)
  2208. {
  2209. LessonRecord lessonRecordExpire = null;
  2210. //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
  2211. //220712 讨论,将desc去掉,获取最旧的那一笔数据。删除最旧的
  2212. string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
  2213. $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' and c.status<>404 order by c.startTime ";
  2214. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<LessonRecord>(
  2215. queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
  2216. {
  2217. lessonRecordExpire = item; break;
  2218. }
  2219. if (lessonRecordExpire != null)
  2220. {
  2221. // 1-时间戳,7-时间戳
  2222. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2223. //暂定7天
  2224. var now = DateTimeOffset.UtcNow;
  2225. //剩余3天的通知
  2226. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  2227. //result.Add(3, day3);
  2228. //剩余1天的通知
  2229. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2230. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2231. //到期通知
  2232. //不到五点上传的课例,七天之后直接删除。
  2233. int addSecond = 0;
  2234. if (now.Hour > 5)
  2235. {
  2236. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2237. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  2238. //再加 00到05小时内的 随机秒数
  2239. Random rand = new Random();
  2240. int randInt = rand.Next(0, 18000);
  2241. addSecond += randInt;
  2242. }
  2243. else
  2244. {
  2245. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  2246. }
  2247. lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2248. //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
  2249. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
  2250. string biz = "expire";
  2251. string expireTime= DateTimeOffset.FromUnixTimeMilliseconds(lessonRecordExpire.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2252. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2253. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecordExpire.id }, { "lessonName", lessonRecordExpire. name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2254. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2255. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
  2256. if (records.Count <= 0)
  2257. {
  2258. foreach (var item in result)
  2259. {
  2260. string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
  2261. //课堂的id ,
  2262. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2263. var message = new ServiceBusMessage(new
  2264. {
  2265. id = lessonRecordExpire.id,
  2266. progress = item.Key,
  2267. code = lessonRecordExpire.code,
  2268. scope = lessonRecordExpire.scope,
  2269. school = lessonRecordExpire.school,
  2270. opt = "delete",
  2271. expire = lessonRecordExpire.expire,
  2272. tmdid = tmdid,
  2273. tmdname = teacher.name,
  2274. name = lessonRecordExpire.name,
  2275. startTime = lessonRecordExpire.startTime,
  2276. tag = item.Value.tag
  2277. }.ToJsonString());
  2278. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2279. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2280. ChangeRecord changeRecord = new ChangeRecord
  2281. {
  2282. RowKey = lessonRecordExpire.id,
  2283. PartitionKey = PartitionKey,
  2284. sequenceNumber = start,
  2285. msgId = message.MessageId
  2286. };
  2287. await table.Save<ChangeRecord>(changeRecord);
  2288. }
  2289. }
  2290. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
  2291. }
  2292. }**/
  2293. #endregion 20230208 调整之前
  2294. }
  2295. else
  2296. {
  2297. //=-1 则表示不限制上传数量
  2298. }
  2299. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  2300. { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
  2301. }
  2302. }
  2303. catch (Exception e)
  2304. {
  2305. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2306. }
  2307. msgs.Add(update);
  2308. await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 1, 0);//BI统计增/减量
  2309. break;
  2310. default:
  2311. break;
  2312. }
  2313. }
  2314. //如果被删除则不能再被更新
  2315. if (isReplace)
  2316. {
  2317. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  2318. }
  2319. //计算课堂更新前后的差值
  2320. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  2321. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  2322. }
  2323. });
  2324. }
  2325. catch (CosmosException e)
  2326. {
  2327. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2328. }
  2329. catch (Exception ex)
  2330. {
  2331. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错IESServiceBusTrigger\n{ex.Message}{ex.StackTrace}{data}{code}", GroupNames.醍摩豆服務運維群組);
  2332. }
  2333. finally
  2334. {
  2335. // Complete the message
  2336. await messageActions.CompleteMessageAsync(message);
  2337. }
  2338. }
  2339. /// <summary>
  2340. /// UseDevelopmentStorage=true
  2341. /// </summary>
  2342. /// <param name="message"></param>
  2343. /// <param name="messageActions"></param>
  2344. /// <returns></returns>
  2345. [Function("LessonRecordExpire")]
  2346. public async Task LessonRecordExpireFunc(
  2347. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%","lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")]
  2348. ServiceBusReceivedMessage message,
  2349. ServiceBusMessageActions messageActions)
  2350. {
  2351. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2352. _logger.LogInformation("Message Body: {body}", message.Body);
  2353. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2354. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2355. try
  2356. {
  2357. jsonMsg.TryGetProperty("id", out JsonElement id);
  2358. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  2359. jsonMsg.TryGetProperty("code", out JsonElement _code);
  2360. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  2361. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  2362. jsonMsg.TryGetProperty("name", out JsonElement name);
  2363. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  2364. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  2365. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  2366. jsonMsg.TryGetProperty("school", out JsonElement _school);
  2367. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  2368. var client = _azureCosmos.GetCosmosClient();
  2369. //处理到期删除
  2370. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  2371. {
  2372. string lessonId = $"{id}";
  2373. string tbname;
  2374. string school = $"{_school}";
  2375. string code = "";
  2376. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  2377. {
  2378. code = $"LessonRecord-{school}";
  2379. tbname = "School";
  2380. }
  2381. else if ($"{scope}".Equals("private"))
  2382. {
  2383. code = $"LessonRecord";
  2384. tbname = "Teacher";
  2385. }
  2386. else
  2387. {
  2388. return;
  2389. }
  2390. ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  2391. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  2392. {
  2393. LessonRecord lessonRecord;
  2394. var doc = JsonDocument.Parse(response.Content);
  2395. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  2396. lessonRecord.status = 404;
  2397. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  2398. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  2399. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  2400. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  2401. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  2402. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  2403. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  2404. }
  2405. }
  2406. string biz = "expire";
  2407. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  2408. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
  2409. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2410. new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid", tmdid }, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName", name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2411. }
  2412. catch (Exception ex)
  2413. {
  2414. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2415. }
  2416. finally
  2417. {
  2418. // Complete the message
  2419. await messageActions.CompleteMessageAsync(message);
  2420. }
  2421. }
  2422. /// <summary>
  2423. /// UseDevelopmentStorage=true
  2424. /// </summary>
  2425. /// <param name="message"></param>
  2426. /// <param name="messageActions"></param>
  2427. /// <returns></returns>
  2428. [Function("Imei")]
  2429. public async Task ImeiFunc(
  2430. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")]
  2431. ServiceBusReceivedMessage message,
  2432. ServiceBusMessageActions messageActions)
  2433. {
  2434. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2435. _logger.LogInformation("Message Body: {body}", message.Body);
  2436. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2437. var json = JsonDocument.Parse(message.Body);
  2438. try
  2439. {
  2440. //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
  2441. if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
  2442. json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
  2443. json.RootElement.TryGetProperty("school", out JsonElement school) &&
  2444. json.RootElement.TryGetProperty("stus", out JsonElement stus))
  2445. {
  2446. json.RootElement.TryGetProperty("imeiType", out JsonElement imeiType);
  2447. var db = _azureCosmos.GetCosmosClient();
  2448. foreach (var stu in stus.EnumerateArray())
  2449. {
  2450. await foreach (var item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIteratorSql(
  2451. queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}' and c.school='{school}' ",
  2452. requestOptions: new() { PartitionKey = new($"Imei") }))
  2453. {
  2454. using var root = await JsonDocument.ParseAsync(item.Content);
  2455. if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2456. {
  2457. var doc = root.RootElement.GetProperty("Documents").EnumerateArray().First();
  2458. var imei = doc.ToObject<Imei>();
  2459. imei.channel = channel.GetString();
  2460. imei.userid = userid.GetString();
  2461. if (!string.IsNullOrWhiteSpace($"{imeiType}"))
  2462. {
  2463. imei.imeiType = $"{imeiType}";
  2464. }
  2465. else
  2466. {
  2467. if (imei.id.Length == 11)
  2468. {
  2469. imei.imeiType = "139zhxy";
  2470. }
  2471. else if (imei.id.Length == 15)
  2472. {
  2473. imei.imeiType = "tianbo";
  2474. }
  2475. }
  2476. await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id);
  2477. }
  2478. }
  2479. }
  2480. }
  2481. }
  2482. catch (Exception ex)
  2483. {
  2484. await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF error\n{ex.Message}\n{ex.StackTrace}{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2485. }
  2486. finally
  2487. {
  2488. // Complete the message
  2489. await messageActions.CompleteMessageAsync(message);
  2490. }
  2491. }
  2492. /// <summary>
  2493. /// UseDevelopmentStorage=true
  2494. /// </summary>
  2495. /// <param name="message"></param>
  2496. /// <param name="messageActions"></param>
  2497. /// <returns></returns>
  2498. [Function("BlobRoot")]
  2499. public async Task BlobRoot(
  2500. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")]
  2501. ServiceBusReceivedMessage message,
  2502. ServiceBusMessageActions messageActions)
  2503. {
  2504. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2505. _logger.LogInformation("Message Body: {body}", message.Body);
  2506. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2507. try
  2508. {
  2509. _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
  2510. {
  2511. var jsonMsg = JsonDocument.Parse(message.Body).RootElement.ToObject<BlobRefreshMessage>();
  2512. if (!string.IsNullOrWhiteSpace($"{jsonMsg.root}") && !string.IsNullOrWhiteSpace($"{jsonMsg.name}"))
  2513. {
  2514. string lockKey = $"Blob:Lock:{jsonMsg.name}:{jsonMsg.root}";
  2515. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  2516. if (exist)
  2517. {
  2518. string[] uls = System.Web.HttpUtility.UrlDecode($"{jsonMsg.root}", Encoding.UTF8).Split("/");
  2519. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  2520. string name = $"{jsonMsg.name}";
  2521. await RefreshBlob(name, u);
  2522. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  2523. }
  2524. }
  2525. });
  2526. }
  2527. catch { }
  2528. finally
  2529. {
  2530. // Complete the message
  2531. await messageActions.CompleteMessageAsync(message);
  2532. }
  2533. }
  2534. /// <summary>
  2535. /// 統測評量開始結束
  2536. /// </summary>
  2537. /// <param name="message"></param>
  2538. /// <param name="messageActions"></param>
  2539. /// <returns></returns>
  2540. [Function("JointExam")]
  2541. public async Task JointExamFunc(
  2542. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointexam", Connection = "Azure:ServiceBus:ConnectionString")]
  2543. ServiceBusReceivedMessage message,
  2544. ServiceBusMessageActions messageActions)
  2545. {
  2546. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2547. _logger.LogInformation("Message Body: {body}", message.Body);
  2548. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2549. var json = JsonDocument.Parse(message.Body);
  2550. try
  2551. {
  2552. json.RootElement.TryGetProperty("id", out JsonElement id);
  2553. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  2554. json.RootElement.TryGetProperty("code", out JsonElement code);
  2555. var client = _azureCosmos.GetCosmosClient();
  2556. JointExam jointExam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<JointExam>(id.ToString(), new PartitionKey($"{code}"));
  2557. jointExam.progress = progress.ToString();
  2558. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(jointExam, id.ToString(), new PartitionKey($"{code}"));
  2559. }
  2560. catch (CosmosException e)
  2561. {
  2562. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2563. }
  2564. catch (Exception ex)
  2565. {
  2566. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2567. }
  2568. finally
  2569. { // Complete the message
  2570. await messageActions.CompleteMessageAsync(message);
  2571. }
  2572. }
  2573. /// <summary>
  2574. /// 統測活動行程進行狀況更新
  2575. /// </summary>
  2576. /// <param name="message"></param>
  2577. /// <param name="messageActions"></param>
  2578. /// <returns></returns>
  2579. [Function("JointEventSchedule")]
  2580. public async Task JointEventFunc(
  2581. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointevent-schedule", Connection = "Azure:ServiceBus:ConnectionString")]
  2582. ServiceBusReceivedMessage message,
  2583. ServiceBusMessageActions messageActions,
  2584. ExecutionContext context)
  2585. {
  2586. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2587. _logger.LogInformation("Message Body: {body}", message.Body);
  2588. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2589. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2590. jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
  2591. jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
  2592. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  2593. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2594. try
  2595. {
  2596. //多國語字典
  2597. //string rootPath = _environment.ContentRootPath;
  2598. //List<string> langList = new List<string>() { "en-us", "zh-cn", "zh-tw" };
  2599. //Dictionary<string, JObject> langDic = new Dictionary<string, JObject>();
  2600. //foreach (string langCode in langList)
  2601. //{
  2602. // string path = Path.Combine(rootPath, $"Lang/{langCode}.json");
  2603. // if (File.Exists(path))
  2604. // {
  2605. // string jsonContent = await File.ReadAllTextAsync(path);
  2606. // JObject jsonObject = JObject.Parse(jsonContent);
  2607. // langDic.Add(langCode, jsonObject);
  2608. // }
  2609. //}
  2610. bool updFlg = false;
  2611. string code = "JointEvent";
  2612. var client = _azureCosmos.GetCosmosClient();
  2613. JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<JointEvent>(jointEventId.ToString(), new PartitionKey($"{code}"));
  2614. if (jointEvent != null)
  2615. {
  2616. JointEvent.JointEventSchedule jointEventSchedule = jointEvent.schedule.Where(s => s.id.Equals($"{jointScheduleId}")).FirstOrDefault();
  2617. if (jointEventSchedule != null)
  2618. {
  2619. //DB資料處理
  2620. if (!jointEventSchedule.progress.Equals($"{progress}"))
  2621. {
  2622. jointEventSchedule.progress = $"{progress}";
  2623. updFlg = true;
  2624. }
  2625. if (updFlg)
  2626. {
  2627. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(jointEvent, jointEvent.id);
  2628. }
  2629. //訊息處理
  2630. switch (jointEventSchedule.progress)
  2631. {
  2632. case "pending":
  2633. //going訊息寄送
  2634. var msg = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "going" }.ToJsonString());
  2635. msg.ApplicationProperties.Add("name", "JointEventSchedule");
  2636. string PartitionKeyGo = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "going");
  2637. List<ChangeRecord> recordsGo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKeyGo } });
  2638. if (recordsGo.Count > 0)
  2639. {
  2640. try
  2641. {
  2642. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordsGo[0].sequenceNumber);
  2643. }
  2644. catch (ServiceBusException e) { }
  2645. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
  2646. recordsGo[0].sequenceNumber = start;
  2647. await table.SaveOrUpdate<ChangeRecord>(recordsGo[0]);
  2648. }
  2649. else
  2650. {
  2651. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
  2652. ChangeRecord changeRecord = new ChangeRecord
  2653. {
  2654. RowKey = jointEventSchedule.id,
  2655. PartitionKey = PartitionKeyGo,
  2656. sequenceNumber = start,
  2657. msgId = message.MessageId
  2658. };
  2659. await table.Save<ChangeRecord>(changeRecord);
  2660. }
  2661. break;
  2662. case "going":
  2663. //pending訊息紀錄刪除
  2664. string pkey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "pending");
  2665. await table.DeleteSingle<ChangeRecord>(pkey, jointEventSchedule.id);
  2666. //發送finish訊息
  2667. var messageEnd = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "finish" }.ToJsonString());
  2668. messageEnd.ApplicationProperties.Add("name", "JointEventSchedule");
  2669. string PartitionKeyEnd = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "finish");
  2670. List<ChangeRecord> recordsEnd = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKeyEnd } });
  2671. if (recordsEnd.Count > 0)
  2672. {
  2673. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
  2674. try {
  2675. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordsEnd[0].sequenceNumber);
  2676. }
  2677. catch (ServiceBusException e) { }
  2678. recordsEnd[0].sequenceNumber = end;
  2679. await table.SaveOrUpdate<ChangeRecord>(recordsEnd[0]);
  2680. }
  2681. else
  2682. {
  2683. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
  2684. ChangeRecord changeRecord = new ChangeRecord
  2685. {
  2686. RowKey = jointEventSchedule.id,
  2687. PartitionKey = PartitionKeyEnd,
  2688. sequenceNumber = end,
  2689. msgId = messageEnd.MessageId
  2690. };
  2691. await table.Save<ChangeRecord>(changeRecord);
  2692. }
  2693. //寄發Email
  2694. if(jointEventSchedule.type.Equals("exam"))
  2695. {
  2696. string type = string.Empty;
  2697. string tablePartitionKey = string.Empty;
  2698. string tableRowKey = string.Empty;
  2699. long emitTime = 0;
  2700. //熱身賽
  2701. if (jointEventSchedule.examType.Equals("regular"))
  2702. {
  2703. //熱身賽開始
  2704. type = "regularExamStart";
  2705. emitTime = jointEventSchedule.startTime;
  2706. var messageRegularSt = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2707. messageRegularSt.ApplicationProperties.Add("name", "JointMessage");
  2708. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2709. tableRowKey = $"{jointEventSchedule.id}";
  2710. List<ChangeRecord> recordRegularSt = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2711. if (recordRegularSt.Count > 0)
  2712. {
  2713. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2714. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordRegularSt[0].sequenceNumber);
  2715. recordRegularSt[0].sequenceNumber = sr;
  2716. await table.SaveOrUpdate<ChangeRecord>(recordRegularSt[0]);
  2717. }
  2718. else
  2719. {
  2720. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2721. ChangeRecord changeRecord = new ChangeRecord
  2722. {
  2723. RowKey = tableRowKey,
  2724. PartitionKey = tablePartitionKey,
  2725. sequenceNumber = sr,
  2726. msgId = messageRegularSt.MessageId
  2727. };
  2728. await table.Save<ChangeRecord>(changeRecord);
  2729. }
  2730. //熱身賽即將結束
  2731. type = "regularExamEndSoon";
  2732. DateTimeOffset dateTimeEnd = DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime);
  2733. dateTimeEnd = dateTimeEnd.AddDays(-1);
  2734. DateTimeOffset emitTimeOffset = new DateTimeOffset(dateTimeEnd.Year, dateTimeEnd.Month, dateTimeEnd.Day, 0, 0, 0, DateTimeOffset.UtcNow.Offset);
  2735. emitTime = emitTimeOffset.ToUnixTimeMilliseconds();
  2736. var messageRegularSo = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2737. messageRegularSo.ApplicationProperties.Add("name", "JointMessage");
  2738. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2739. tableRowKey = $"{jointEventSchedule.id}";
  2740. List<ChangeRecord> recordRegularSo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2741. if (recordRegularSo.Count > 0)
  2742. {
  2743. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2744. try
  2745. {
  2746. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordRegularSo[0].sequenceNumber);
  2747. }
  2748. catch (ServiceBusException e) { }
  2749. recordRegularSo[0].sequenceNumber = sr;
  2750. await table.SaveOrUpdate<ChangeRecord>(recordRegularSo[0]);
  2751. }
  2752. else
  2753. {
  2754. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2755. ChangeRecord changeRecord = new ChangeRecord
  2756. {
  2757. RowKey = tableRowKey,
  2758. PartitionKey = tablePartitionKey,
  2759. sequenceNumber = sr,
  2760. msgId = messageRegularSt.MessageId
  2761. };
  2762. await table.Save<ChangeRecord>(changeRecord);
  2763. }
  2764. }
  2765. //決賽
  2766. else if(jointEventSchedule.examType.Equals("custom"))
  2767. {
  2768. //決賽開始
  2769. type = "customExamStart";
  2770. emitTime = jointEventSchedule.startTime;
  2771. var messageCustomSt = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2772. messageCustomSt.ApplicationProperties.Add("name", "JointMessage");
  2773. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2774. tableRowKey = $"{jointEventSchedule.id}";
  2775. List<ChangeRecord> recordCustomSt = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2776. if (recordCustomSt.Count > 0)
  2777. {
  2778. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2779. try
  2780. {
  2781. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordCustomSt[0].sequenceNumber);
  2782. }
  2783. catch (ServiceBusException e) { }
  2784. recordCustomSt[0].sequenceNumber = sr;
  2785. await table.SaveOrUpdate<ChangeRecord>(recordCustomSt[0]);
  2786. }
  2787. else
  2788. {
  2789. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2790. ChangeRecord changeRecord = new ChangeRecord
  2791. {
  2792. RowKey = tableRowKey,
  2793. PartitionKey = tablePartitionKey,
  2794. sequenceNumber = sr,
  2795. msgId = messageCustomSt.MessageId
  2796. };
  2797. await table.Save<ChangeRecord>(changeRecord);
  2798. }
  2799. //決賽即將結束
  2800. type = "customExamEndSoon";
  2801. DateTimeOffset dateTimeEnd = DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime);
  2802. dateTimeEnd = dateTimeEnd.AddDays(-1);
  2803. DateTimeOffset emitTimeOffset = new DateTimeOffset(dateTimeEnd.Year, dateTimeEnd.Month, dateTimeEnd.Day, 0, 0, 0, DateTimeOffset.UtcNow.Offset);
  2804. emitTime = emitTimeOffset.ToUnixTimeMilliseconds();
  2805. var messageCustomSo = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
  2806. messageCustomSo.ApplicationProperties.Add("name", "JointMessage");
  2807. tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2808. tableRowKey = $"{jointEventSchedule.id}";
  2809. List<ChangeRecord> recordCustomSo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
  2810. if (recordCustomSo.Count > 0)
  2811. {
  2812. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2813. try
  2814. {
  2815. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordCustomSo[0].sequenceNumber);
  2816. }
  2817. catch (ServiceBusException e) { }
  2818. recordCustomSo[0].sequenceNumber = sr;
  2819. await table.SaveOrUpdate<ChangeRecord>(recordCustomSo[0]);
  2820. }
  2821. else
  2822. {
  2823. long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
  2824. ChangeRecord changeRecord = new ChangeRecord
  2825. {
  2826. RowKey = tableRowKey,
  2827. PartitionKey = tablePartitionKey,
  2828. sequenceNumber = sr,
  2829. msgId = messageCustomSo.MessageId
  2830. };
  2831. await table.Save<ChangeRecord>(changeRecord);
  2832. }
  2833. }
  2834. }
  2835. break;
  2836. case "finish":
  2837. //熱身賽結束,生成決賽名單
  2838. if (jointEventSchedule.type.Equals("exam") && jointEventSchedule.examType.Equals("regular"))
  2839. {
  2840. List<string> jointGroupIds = jointEvent.groups.Select(g => g.id).ToList();
  2841. if (jointGroupIds.Count > 0)
  2842. {
  2843. string scope = "private";
  2844. int classCnt = 0;
  2845. foreach (string jointGroupId in jointGroupIds)
  2846. {
  2847. object addResult = await JointService.CreatePassJointCourseBySchedule(client, jointEvent.id, jointGroupId, jointEventSchedule.id, scope, true, classCnt);
  2848. classCnt = Int32.Parse(addResult.GetType().GetProperty("classCnt").GetValue(addResult).ToString());
  2849. }
  2850. }
  2851. }
  2852. break;
  2853. }
  2854. }
  2855. }
  2856. }
  2857. catch (CosmosException e)
  2858. {
  2859. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2860. }
  2861. catch (Exception ex)
  2862. {
  2863. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2864. }
  2865. finally
  2866. {
  2867. //自身訊息紀錄刪除
  2868. string PartitionKey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", $"{progress}"); //主key: JointEvent-{jointEventId}-schedule-{progress} RowKey: {jointScheduleId}
  2869. await table.DeleteSingle<ChangeRecord>(PartitionKey, $"{jointScheduleId}");
  2870. // Complete the message
  2871. await messageActions.CompleteMessageAsync(message);
  2872. }
  2873. }
  2874. /// <summary>
  2875. /// 統測活動訊息寄送
  2876. /// </summary>
  2877. /// <param name="message"></param>
  2878. /// <param name="messageActions"></param>
  2879. /// <returns></returns>
  2880. [Function("JointEventSendMessage")]
  2881. public async Task JointEventSendMessageFunc(
  2882. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointmessage", Connection = "Azure:ServiceBus:ConnectionString")]
  2883. ServiceBusReceivedMessage message,
  2884. ServiceBusMessageActions messageActions,
  2885. ExecutionContext context)
  2886. {
  2887. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2888. _logger.LogInformation("Message Body: {body}", message.Body);
  2889. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2890. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2891. jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
  2892. jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
  2893. jsonMsg.TryGetProperty("type", out JsonElement type);
  2894. string location = Environment.GetEnvironmentVariable("Option:Location");
  2895. var client = _azureCosmos.GetCosmosClient();
  2896. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2897. string lang = (location.Contains("China")) ? "zh-cn" : "zh-tw";
  2898. long time = (jsonMsg.TryGetProperty("time", out JsonElement _time)) ? _time.GetInt64() : new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
  2899. try
  2900. {
  2901. StringBuilder sqlStr = new StringBuilder($"SELECT DISTINCT c.creatorId, c.creatorName, c.creatorEmail FROM c WHERE c.jointEventId = '{jointEventId}' ");
  2902. string tid = string.Empty;
  2903. switch (type.ToString())
  2904. {
  2905. //熱身賽開始
  2906. case "regularExamStart":
  2907. sqlStr.Append($" AND c.type = 'regular' ");
  2908. tid = (location.Contains("China")) ? "" : "d-ba5d29036f81460c841fadaac7d35b6b"; //熱身賽開始
  2909. break;
  2910. //熱身賽即將結束
  2911. case "regularExamEndSoon":
  2912. sqlStr.Append($" AND c.type = 'regular' ");
  2913. tid = (location.Contains("China")) ? "" : "d-359ec5e40e244aceb4d04f42e52af29d"; //熱身賽即將結束
  2914. break;
  2915. //決賽開始
  2916. case "customExamStart":
  2917. sqlStr.Append($" AND c.type = 'custom' ");
  2918. break;
  2919. //決賽即將結束
  2920. case "customExamEndSoon":
  2921. sqlStr.Append($" AND c.type = 'custom' ");
  2922. break;
  2923. }
  2924. //取得收信者
  2925. List<dynamic> mailUsers = new List<dynamic>();
  2926. await foreach (var jc in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql(queryText: sqlStr.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointCourse") }))
  2927. {
  2928. using var json = await JsonDocument.ParseAsync(jc.Content);
  2929. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2930. {
  2931. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2932. {
  2933. EmailUser user = new EmailUser();
  2934. user.tmid = (obj.TryGetProperty("creatorId", out JsonElement _creatorId)) ? _creatorId.GetString() : string.Empty;
  2935. user.name = (obj.TryGetProperty("creatorName", out JsonElement _creatorName)) ? _creatorName.GetString() : string.Empty;
  2936. user.email = (obj.TryGetProperty("creatorEmail", out JsonElement _creatorEmail)) ? _creatorEmail.GetString() : string.Empty;
  2937. if (!string.IsNullOrWhiteSpace(user.tmid) && !string.IsNullOrWhiteSpace(user.email))
  2938. {
  2939. mailUsers.Add(user);
  2940. }
  2941. }
  2942. }
  2943. }
  2944. //寄發Email
  2945. if (mailUsers.Count > 0)
  2946. {
  2947. if(location.Contains("-Test")) await _dingDing.SendBotMsg($"寄送活動Email type:{type.ToString()} 寄送人數:{mailUsers.Count}人", GroupNames.研發C組);
  2948. //熱身賽開始 Mail發送
  2949. foreach (dynamic user in mailUsers)
  2950. {
  2951. if (!string.IsNullOrWhiteSpace(tid)) //※無模板ID不發
  2952. {
  2953. await _coreAPIHttpService.SendMail(new Dictionary<string, object> { { "to", user.email }, { "tid", tid }, { "vars", new { name = user.name } } }, location, _configuration);
  2954. }
  2955. }
  2956. }
  2957. }
  2958. catch (Exception ex)
  2959. {
  2960. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")} 統測活動Email寄送錯誤:\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2961. }
  2962. finally
  2963. {
  2964. //自身訊息紀錄刪除
  2965. string tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
  2966. string tableRowKey = $"{jointScheduleId}";
  2967. await table.DeleteSingle<ChangeRecord>(tablePartitionKey, tableRowKey);
  2968. // Complete the message
  2969. await messageActions.CompleteMessageAsync(message);
  2970. }
  2971. }
  2972. private async Task RefreshBlob(string name, string u)
  2973. {
  2974. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2975. var client = _azureStorage.GetBlobContainerClient(name);
  2976. var size = await client.GetBlobsSize(u);
  2977. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  2978. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  2979. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  2980. double blobsize = 0;
  2981. if (scores != default && scores != null)
  2982. {
  2983. foreach (var score in scores)
  2984. {
  2985. blobsize = blobsize + score.Score;
  2986. }
  2987. }
  2988. if (blobsize > 0)
  2989. {
  2990. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  2991. }
  2992. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2993. long dis = (end - statr) / 1000;
  2994. long timeout = 60 * 5;
  2995. if (dis > timeout)
  2996. {
  2997. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
  2998. }
  2999. //await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
  3000. }
  3001. private class EmailUser
  3002. {
  3003. public string tmid { get; set; }
  3004. public string name { get; set; }
  3005. public string email { get; set; }
  3006. }
  3007. }
  3008. }