IESServiceBusTrigger.cs 210 KB

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