IESServiceBusTrigger.cs 205 KB

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