IESServiceBusTrigger.cs 215 KB

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