IESServiceBusTrigger.cs 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736
  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. try
  1412. {
  1413. BlobDownloadResult timeLineBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1414. TimeLineData timeLineData = timeLineBlobDownload.Content.ToObjectFromJson<TimeLineData>();
  1415. lessonRecord.hitaClientCmpCount = timeLineData.events.Where(z => !string.IsNullOrWhiteSpace(z.WrkCmpSrcType) && z.WrkCmpSrcType.Equals("HitaClientCmp")).Count();
  1416. //lessonRecord.collateTaskCount = lessonRecord.hitaClientCmpCount;
  1417. List<TimeLineEvent> timeLineEvents = timeLineData.events.FindAll(z => !string.IsNullOrWhiteSpace(z.Event) && z.Event.Equals("PickupResult"));
  1418. if (timeLineEvents.IsNotEmpty())
  1419. {
  1420. foreach (var timeLineEvent in timeLineEvents)
  1421. {
  1422. var memberIds = timeLineEvent.PickupMemberId.ToObject<List<int>>();
  1423. PickupMemberIds.AddRange(memberIds);
  1424. }
  1425. }
  1426. }
  1427. catch (Exception ex)
  1428. {
  1429. if (!ex.Message.Contains("The specified blob does not exist"))
  1430. {
  1431. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},TimeLine.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1432. }
  1433. }
  1434. //读取Task.json
  1435. List<TaskData> taskDatas = new List<TaskData>();
  1436. try
  1437. {
  1438. BlobDownloadResult taskBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/Task.json").DownloadContentAsync();
  1439. taskDatas = taskBlobDownload.Content.ToObjectFromJson<List<TaskData>>();
  1440. }
  1441. catch (Exception ex)
  1442. {
  1443. if (!ex.Message.Contains("The specified blob does not exist"))
  1444. {
  1445. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},Task.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1446. }
  1447. }
  1448. //读取IRS.json
  1449. List<IRSData> iRSDatas = new List<IRSData>();
  1450. try
  1451. {
  1452. BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/IRS.json").DownloadContentAsync();
  1453. iRSDatas = irsBlobDownload.Content.ToObjectFromJson<List<IRSData>>();
  1454. }
  1455. catch (Exception ex)
  1456. {
  1457. if (!ex.Message.Contains("The specified blob does not exist"))
  1458. {
  1459. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1460. }
  1461. }
  1462. //如果有更新 则去读取/{_lessonId}/IES/base.json
  1463. try
  1464. {
  1465. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  1466. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  1467. //attendState
  1468. string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall", "0");
  1469. LessonBase lessonBase = null;
  1470. try
  1471. {
  1472. lessonBase = basejson.ToObject<LessonBase>();
  1473. }
  1474. catch (Exception ex)
  1475. {
  1476. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},base.json转换异常,{ex.Message}{ex.StackTrace}{basejson},{lessonRecord.id}", GroupNames.成都开发測試群組);
  1477. //lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1478. }
  1479. //await _dingDing.SendBotMsg($"课例记录文件base.json:{lessonBase.ToJsonString()}", GroupNames.成都开发測試群組);
  1480. if (lessonBase != null && lessonBase.summary != null)
  1481. {
  1482. //lessonRecord.name = lessonBase.summary.activityName;
  1483. lessonRecord.attendCount = lessonBase.summary.attendCount;
  1484. lessonRecord.clientCount = lessonBase.summary.clientCount;
  1485. lessonRecord.attendRate = lessonBase.summary.attendRate;
  1486. lessonRecord.groupCount = lessonBase.summary.groupCount;
  1487. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  1488. lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount + lessonRecord.hitaClientCmpCount;
  1489. lessonRecord.collateCount = lessonBase.summary.collateCount;
  1490. lessonRecord.pushCount = lessonBase.summary.pushCount;
  1491. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  1492. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  1493. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  1494. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  1495. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  1496. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  1497. lessonRecord.examCount = lessonBase.summary.examCount;
  1498. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  1499. lessonRecord.learningCategory = lessonBase.summary.learningCategory;
  1500. if (lessonRecord.learningCategory == null)
  1501. {
  1502. lessonRecord.learningCategory = new LearningCategory();
  1503. }
  1504. if (lessonRecord.hitaClientCmpCount > 0)
  1505. {
  1506. lessonRecord.learningCategory.cooperation = 1;
  1507. }
  1508. if (!string.IsNullOrWhiteSpace(lessonRecord.school))
  1509. {
  1510. lessonBase.student.ForEach(x =>
  1511. {
  1512. if (string.IsNullOrWhiteSpace(x.school))
  1513. {
  1514. x.school = lessonRecord.school;
  1515. }
  1516. });
  1517. }
  1518. //计算TP灯
  1519. {
  1520. int T = -1;
  1521. int P = -1;
  1522. if (lessonRecord.clientInteractionAverge <= 0)
  1523. {
  1524. T = 0;
  1525. }
  1526. else if (lessonRecord.clientInteractionAverge > 0 && lessonRecord.clientInteractionAverge < 2)
  1527. // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
  1528. {
  1529. T = 1;
  1530. }
  1531. else
  1532. {
  1533. T = 2;
  1534. }
  1535. //if (lessonRecord.examCount > 0)
  1536. //{
  1537. // //有评测次数大于0则P是直接绿灯
  1538. // P = 2;
  1539. //}
  1540. //else {
  1541. //}
  1542. int a = lessonRecord.hitaClientCmpCount;
  1543. int b = lessonRecord.pushCount;
  1544. int c = lessonRecord.examCount;
  1545. switch (true)
  1546. {
  1547. case bool when T == 0:
  1548. P = 0;
  1549. break;
  1550. case bool when T == 1 || T == 2:
  1551. if (a == 0 && b == 0 && c == 0)
  1552. {
  1553. P = 0;
  1554. }
  1555. else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
  1556. {
  1557. P = 2;
  1558. }
  1559. else
  1560. {
  1561. P = 1;
  1562. }
  1563. break;
  1564. }
  1565. lessonRecord.tLevel = T;
  1566. lessonRecord.pLevel = P;
  1567. }
  1568. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1569. //{
  1570. // clientSummaryList = lessonBase.report.clientSummaryList,
  1571. // students = lessonBase.student,
  1572. // name = lessonRecord.name,
  1573. // school = lessonRecord.school,
  1574. // id = lessonRecord.id,
  1575. // scope = lessonRecord.scope,
  1576. // tmdid = lessonRecord.tmdid,
  1577. // code = "LessonStudentRecord",
  1578. // pk = "LessonStudentRecord",
  1579. // courseId =lessonRecord.courseId,
  1580. // groupIds= lessonRecord.groupIds,
  1581. // periodId = lessonRecord.periodId,
  1582. // subjectId = lessonRecord.subjectId,
  1583. //};
  1584. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1585. }
  1586. //有上传 base.josn.
  1587. lessonRecord.upload = 1;
  1588. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1589. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, _coreAPIHttpService, _dingDing, _azureRedis);
  1590. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1591. Bloblog bloblog = new Bloblog
  1592. {
  1593. id = lessonRecord.id,
  1594. code = $"Bloblog-{blobname}",
  1595. name = lessonRecord.name,
  1596. pk = "Bloblog",
  1597. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1598. type = "records",
  1599. url = $"records/{_lessonId}",
  1600. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1601. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1602. size = size.HasValue ? size.Value : 0,
  1603. };
  1604. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1605. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1606. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1607. msgs.Add(update);
  1608. DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase, _azureRedis, PickupMemberIds, taskDatas, iRSDatas);
  1609. }
  1610. catch (Exception ex)
  1611. {
  1612. if (!ex.Message.Contains("The specified blob does not exist"))
  1613. {
  1614. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1615. }
  1616. }
  1617. await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
  1618. break;
  1619. //更新 时间线
  1620. case "up-TimeLine":
  1621. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1622. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1623. msgs.Add(update);
  1624. break;
  1625. //更新 课堂总览信息
  1626. case "up-ActivityInfo":
  1627. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1628. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1629. msgs.Add(update);
  1630. break;
  1631. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1632. isReplace = true;
  1633. msgs.Add(update);
  1634. break;
  1635. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1636. try
  1637. {
  1638. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1639. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1640. foreach (var record in records)
  1641. {
  1642. try
  1643. {
  1644. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1645. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1646. }
  1647. catch (Exception)
  1648. {
  1649. continue;
  1650. }
  1651. }
  1652. }
  1653. catch (Exception)
  1654. {
  1655. break;
  1656. }
  1657. isReplace = true;
  1658. msgs.Add(update);
  1659. break;
  1660. case "delete":
  1661. try
  1662. {
  1663. if (lessonRecord.expire > 0)
  1664. {
  1665. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1666. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1667. foreach (var record in records)
  1668. {
  1669. try
  1670. {
  1671. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1672. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1673. }
  1674. catch (Exception)
  1675. {
  1676. continue;
  1677. }
  1678. }
  1679. }
  1680. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1681. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1682. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1683. msgs.Add(update);
  1684. }
  1685. catch (CosmosException)
  1686. {
  1687. msgs.Add(update);
  1688. }
  1689. lessonRecord = null;
  1690. isReplace = false;
  1691. break;
  1692. case "create":
  1693. oldlessonRecord = null;
  1694. //处理课堂选用的课程信息
  1695. lessonRecord.show = teacher.lessonShow;
  1696. lessonRecord.upload = 0;
  1697. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1698. {
  1699. CourseBase course = null;
  1700. try
  1701. {
  1702. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase-{lessonRecord.school}"));
  1703. if (cresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1704. {
  1705. using var cJson = await JsonDocument.ParseAsync(cresponse.Content);
  1706. course = cJson.ToObject<CourseBase>();
  1707. }
  1708. else
  1709. {
  1710. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase"));
  1711. if (sresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1712. {
  1713. using var cJson = await JsonDocument.ParseAsync(sresponse.Content);
  1714. course = cJson.ToObject<CourseBase>();
  1715. }
  1716. else
  1717. {
  1718. course = null;
  1719. }
  1720. }
  1721. }
  1722. catch (Exception ex)
  1723. {
  1724. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1725. }
  1726. /*catch (CosmosException ex) when (ex.Status != 404)
  1727. {
  1728. try
  1729. {
  1730. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1731. }
  1732. catch (CosmosException e) when (e.Status != 404)
  1733. {
  1734. course = null;
  1735. }
  1736. }*/
  1737. if (course != null)
  1738. {
  1739. lessonRecord.periodId = course.period?.id;
  1740. lessonRecord.subjectId = course.subject?.id;
  1741. }
  1742. }
  1743. //处理课堂选用的名单
  1744. if (lessonRecord.groupIds.IsNotEmpty())
  1745. {
  1746. List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1747. if (!string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1748. {
  1749. HashSet<string> grades = new HashSet<string>();
  1750. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1751. HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
  1752. groups.ForEach(y =>
  1753. {
  1754. if (y.type.Equals("teach") || y.type.Equals("class"))
  1755. {
  1756. gd.Add(y.year);
  1757. }
  1758. });
  1759. var gpdata = SchoolService.GetGrades(schoolObj, lessonRecord.periodId, gd);
  1760. lessonRecord.grade = gpdata.grades.ToList();
  1761. }
  1762. }
  1763. try
  1764. {
  1765. if (scope.Equals("school"))
  1766. {
  1767. School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  1768. {
  1769. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  1770. { client = "hiteach", count = 1, id = schoolBase.id, key = "lesson-create", name = schoolBase.name, scope = "school", target = schoolBase.id });
  1771. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  1772. { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
  1773. }
  1774. var space = await BlobService.GetSurplusSpace(school, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
  1775. SchoolSetting setting = null;
  1776. ResponseMessage schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
  1777. if (schoolSetting.StatusCode == System.Net.HttpStatusCode.OK)
  1778. {
  1779. setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
  1780. if (setting.lessonSetting != null)
  1781. {
  1782. //两种状态都不属于,则默认未开启。
  1783. if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
  1784. {
  1785. setting.lessonSetting.openAutoClean = 0;
  1786. setting.lessonSetting.expireDays = Constant.school_lesson_expire;
  1787. }
  1788. else
  1789. {
  1790. //属于 要么开启1,要么关闭0
  1791. }
  1792. }
  1793. else
  1794. {
  1795. setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
  1796. }
  1797. }
  1798. else
  1799. {
  1800. setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
  1801. }
  1802. int school_lesson_expire = 0;
  1803. bool save = true;
  1804. if (space.surplus > 0)
  1805. {
  1806. save = true;
  1807. }
  1808. else
  1809. {
  1810. save = false;
  1811. school_lesson_expire = Constant.school_lesson_expire;
  1812. }
  1813. if (!save && school_lesson_expire > 0)
  1814. {
  1815. // 1-时间戳,7-时间戳
  1816. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1817. //暂定7天
  1818. var now = DateTimeOffset.UtcNow;
  1819. //剩余3天的通知
  1820. //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
  1821. //result.Add(3, day3);
  1822. //剩余1天的通知
  1823. var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
  1824. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1825. //到期通知
  1826. //不到五点上传的课例,七天之后直接删除。
  1827. int addSecond = 0;
  1828. if (now.Hour > 5)
  1829. {
  1830. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1831. addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
  1832. //再加 00到05小时内的 随机秒数
  1833. Random rand = new Random();
  1834. int randInt = rand.Next(0, 18000);
  1835. addSecond += randInt;
  1836. }
  1837. else
  1838. {
  1839. addSecond = school_lesson_expire * 24 * 60 * 60;
  1840. }
  1841. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1842. result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  1843. // result.Add(school_lesson_expire, lessonRecord.expire);
  1844. string biz = "expire";
  1845. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  1846. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  1847. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-school_lessonRecord", Constant.NotifyType_IES5_Course,
  1848. new Dictionary<string, object> { { "tmdid", teacher.id }, { "tmdname", teacher.name }, { "schoolName", schoolBase.name },
  1849. { "schoolId", $"{school}" },{ "lessonId",lessonRecord.id }, { "expireTime", expireTime },{ "lessonName",lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  1850. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1851. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1852. if (records.Count <= 0)
  1853. {
  1854. foreach (var item in result)
  1855. {
  1856. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  1857. //课堂的id ,
  1858. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1859. var servicebus_message = new ServiceBusMessage(new
  1860. {
  1861. id = lessonRecord.id,
  1862. progress = item.Key,
  1863. code = lessonRecord.code,
  1864. scope = lessonRecord.scope,
  1865. school = lessonRecord.school,
  1866. opt = "delete",
  1867. expire = lessonRecord.expire,
  1868. tmdid = tmdid,
  1869. tmdname = teacher.name,
  1870. name = lessonRecord.name,
  1871. startTime = lessonRecord.startTime,
  1872. tag = item.Value.tag
  1873. }.ToJsonString());
  1874. servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1875. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1876. ChangeRecord changeRecord = new ChangeRecord
  1877. {
  1878. RowKey = lessonRecord.id,
  1879. PartitionKey = PartitionKey,
  1880. sequenceNumber = start,
  1881. msgId = servicebus_message.MessageId
  1882. };
  1883. await table.Save<ChangeRecord>(changeRecord);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. //个人课例保存规则
  1889. if (scope.Equals("private"))
  1890. {
  1891. int lessonLimit = teacher.lessonLimit;
  1892. var space = await BlobService.GetSurplusSpace(tmdid, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
  1893. //20230208调整之前 if (blobTotal * 1073741824 - blobsize > 2147483648) //剩余空间大于2G
  1894. //剩余空间不足,则开启自动清理机制
  1895. if (space.surplus > 0)
  1896. {
  1897. //大于0则表示空间充足
  1898. lessonLimit = -1;
  1899. }
  1900. else
  1901. {
  1902. //20230208调整增加逻辑,之前lessonLimit用于处理默认保存50条,现在用于处理标记是否空间不足,不足则标记清理。
  1903. if ($"{Environment.GetEnvironmentVariable("Option:Location")}".Contains("Test", StringComparison.OrdinalIgnoreCase))
  1904. {
  1905. lessonLimit = 0;
  1906. }
  1907. else
  1908. {
  1909. lessonLimit = -1;
  1910. }
  1911. }
  1912. if (lessonLimit != -1)
  1913. {
  1914. #region 20230208 调整之后
  1915. {
  1916. // 1-时间戳,7-时间戳
  1917. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1918. //暂定7天
  1919. var now = DateTimeOffset.UtcNow;
  1920. //剩余3天的通知
  1921. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1922. //result.Add(3, day3);
  1923. //剩余1天的通知
  1924. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  1925. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1926. //到期通知
  1927. //不到五点上传的课例,七天之后直接删除。
  1928. int addSecond = 0;
  1929. if (now.Hour > 5)
  1930. {
  1931. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1932. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  1933. //再加 00到05小时内的 随机秒数
  1934. Random rand = new Random();
  1935. int randInt = rand.Next(0, 18000);
  1936. addSecond += randInt;
  1937. }
  1938. else
  1939. {
  1940. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  1941. }
  1942. //将当前课例标记为 自动清理
  1943. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1944. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  1945. string biz = "expire";
  1946. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  1947. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  1948. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecord.id }, { "lessonName", lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  1949. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1950. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1951. if (records.Count <= 0)
  1952. {
  1953. foreach (var item in result)
  1954. {
  1955. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  1956. //课堂的id ,
  1957. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1958. var servicebus_message = new ServiceBusMessage(new
  1959. {
  1960. id = lessonRecord.id,
  1961. progress = item.Key,
  1962. code = lessonRecord.code,
  1963. scope = lessonRecord.scope,
  1964. school = lessonRecord.school,
  1965. opt = "delete",
  1966. expire = lessonRecord.expire,
  1967. tmdid = tmdid,
  1968. tmdname = teacher.name,
  1969. name = lessonRecord.name,
  1970. startTime = lessonRecord.startTime,
  1971. tag = item.Value.tag
  1972. }.ToJsonString());
  1973. servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1974. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1975. ChangeRecord changeRecord = new ChangeRecord
  1976. {
  1977. RowKey = lessonRecord.id,
  1978. PartitionKey = PartitionKey,
  1979. sequenceNumber = start,
  1980. msgId = servicebus_message.MessageId
  1981. };
  1982. await table.Save<ChangeRecord>(changeRecord);
  1983. }
  1984. }
  1985. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1986. }
  1987. #endregion 20230208 调整之后
  1988. #region 20230208 调整之前
  1989. /** 20230208 调整之前
  1990. HashSet<string> ids = new HashSet<string>();
  1991. //未定义的 以及过期时间小于等于0 的 课例
  1992. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  1993. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  1994. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1995. {
  1996. ids.Add(item);
  1997. }
  1998. // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
  1999. //包含收藏的本人的个人课例
  2000. //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  2001. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  2002. // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  2003. //{
  2004. // ids.Add(item);
  2005. //}
  2006. //教师个人预设的,可以通过设置的方式增加
  2007. int limit = teacher.lessonLimit;
  2008. if (teacher.lessonLimit == 0)
  2009. {
  2010. //未设置的的采用系统设置的默认值50
  2011. limit = Constant.private_lesson_limit;
  2012. }
  2013. if (ids.Count >= limit)
  2014. {
  2015. LessonRecord lessonRecordExpire = null;
  2016. //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
  2017. //220712 讨论,将desc去掉,获取最旧的那一笔数据。删除最旧的
  2018. string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
  2019. $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' and c.status<>404 order by c.startTime ";
  2020. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<LessonRecord>(
  2021. queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
  2022. {
  2023. lessonRecordExpire = item; break;
  2024. }
  2025. if (lessonRecordExpire != null)
  2026. {
  2027. // 1-时间戳,7-时间戳
  2028. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  2029. //暂定7天
  2030. var now = DateTimeOffset.UtcNow;
  2031. //剩余3天的通知
  2032. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  2033. //result.Add(3, day3);
  2034. //剩余1天的通知
  2035. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  2036. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  2037. //到期通知
  2038. //不到五点上传的课例,七天之后直接删除。
  2039. int addSecond = 0;
  2040. if (now.Hour > 5)
  2041. {
  2042. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  2043. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  2044. //再加 00到05小时内的 随机秒数
  2045. Random rand = new Random();
  2046. int randInt = rand.Next(0, 18000);
  2047. addSecond += randInt;
  2048. }
  2049. else
  2050. {
  2051. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  2052. }
  2053. lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  2054. //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
  2055. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
  2056. string biz = "expire";
  2057. string expireTime= DateTimeOffset.FromUnixTimeMilliseconds(lessonRecordExpire.expire).ToString("yyyy-MM-dd HH:mm:ss");
  2058. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2059. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecordExpire.id }, { "lessonName", lessonRecordExpire. name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2060. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2061. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
  2062. if (records.Count <= 0)
  2063. {
  2064. foreach (var item in result)
  2065. {
  2066. string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
  2067. //课堂的id ,
  2068. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  2069. var message = new ServiceBusMessage(new
  2070. {
  2071. id = lessonRecordExpire.id,
  2072. progress = item.Key,
  2073. code = lessonRecordExpire.code,
  2074. scope = lessonRecordExpire.scope,
  2075. school = lessonRecordExpire.school,
  2076. opt = "delete",
  2077. expire = lessonRecordExpire.expire,
  2078. tmdid = tmdid,
  2079. tmdname = teacher.name,
  2080. name = lessonRecordExpire.name,
  2081. startTime = lessonRecordExpire.startTime,
  2082. tag = item.Value.tag
  2083. }.ToJsonString());
  2084. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  2085. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  2086. ChangeRecord changeRecord = new ChangeRecord
  2087. {
  2088. RowKey = lessonRecordExpire.id,
  2089. PartitionKey = PartitionKey,
  2090. sequenceNumber = start,
  2091. msgId = message.MessageId
  2092. };
  2093. await table.Save<ChangeRecord>(changeRecord);
  2094. }
  2095. }
  2096. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
  2097. }
  2098. }**/
  2099. #endregion 20230208 调整之前
  2100. }
  2101. else
  2102. {
  2103. //=-1 则表示不限制上传数量
  2104. }
  2105. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
  2106. { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
  2107. }
  2108. }
  2109. catch (Exception e)
  2110. {
  2111. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2112. }
  2113. msgs.Add(update);
  2114. await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 1, 0);//BI统计增/减量
  2115. break;
  2116. default:
  2117. break;
  2118. }
  2119. }
  2120. //如果被删除则不能再被更新
  2121. if (isReplace)
  2122. {
  2123. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  2124. }
  2125. //计算课堂更新前后的差值
  2126. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  2127. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  2128. }
  2129. });
  2130. }
  2131. catch (CosmosException e)
  2132. {
  2133. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2134. }
  2135. catch (Exception ex)
  2136. {
  2137. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  2138. }
  2139. finally
  2140. {
  2141. // Complete the message
  2142. await messageActions.CompleteMessageAsync(message);
  2143. }
  2144. }
  2145. /// <summary>
  2146. /// UseDevelopmentStorage=true
  2147. /// </summary>
  2148. /// <param name="message"></param>
  2149. /// <param name="messageActions"></param>
  2150. /// <returns></returns>
  2151. [Function("LessonRecordExpire")]
  2152. public async Task LessonRecordExpireFunc(
  2153. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%","lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")]
  2154. ServiceBusReceivedMessage message,
  2155. ServiceBusMessageActions messageActions)
  2156. {
  2157. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2158. _logger.LogInformation("Message Body: {body}", message.Body);
  2159. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2160. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2161. try
  2162. {
  2163. jsonMsg.TryGetProperty("id", out JsonElement id);
  2164. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  2165. jsonMsg.TryGetProperty("code", out JsonElement _code);
  2166. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  2167. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  2168. jsonMsg.TryGetProperty("name", out JsonElement name);
  2169. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  2170. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  2171. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  2172. jsonMsg.TryGetProperty("school", out JsonElement _school);
  2173. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  2174. var client = _azureCosmos.GetCosmosClient();
  2175. //处理到期删除
  2176. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  2177. {
  2178. string lessonId = $"{id}";
  2179. string tbname;
  2180. string school = $"{_school}";
  2181. string code = "";
  2182. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  2183. {
  2184. code = $"LessonRecord-{school}";
  2185. tbname = "School";
  2186. }
  2187. else if ($"{scope}".Equals("private"))
  2188. {
  2189. code = $"LessonRecord";
  2190. tbname = "Teacher";
  2191. }
  2192. else
  2193. {
  2194. return;
  2195. }
  2196. ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  2197. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  2198. {
  2199. LessonRecord lessonRecord;
  2200. var doc = JsonDocument.Parse(response.Content);
  2201. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  2202. lessonRecord.status = 404;
  2203. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  2204. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  2205. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  2206. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  2207. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  2208. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  2209. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  2210. }
  2211. }
  2212. string biz = "expire";
  2213. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  2214. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
  2215. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  2216. new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid", tmdid }, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName", name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  2217. }
  2218. catch (Exception ex)
  2219. {
  2220. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2221. }
  2222. finally
  2223. {
  2224. // Complete the message
  2225. await messageActions.CompleteMessageAsync(message);
  2226. }
  2227. }
  2228. /// <summary>
  2229. /// UseDevelopmentStorage=true
  2230. /// </summary>
  2231. /// <param name="message"></param>
  2232. /// <param name="messageActions"></param>
  2233. /// <returns></returns>
  2234. [Function("Imei")]
  2235. public async Task ImeiFunc(
  2236. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")]
  2237. ServiceBusReceivedMessage message,
  2238. ServiceBusMessageActions messageActions)
  2239. {
  2240. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2241. _logger.LogInformation("Message Body: {body}", message.Body);
  2242. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2243. var json = JsonDocument.Parse(message.Body);
  2244. try
  2245. {
  2246. //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
  2247. if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
  2248. json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
  2249. json.RootElement.TryGetProperty("school", out JsonElement school) &&
  2250. json.RootElement.TryGetProperty("stus", out JsonElement stus))
  2251. {
  2252. json.RootElement.TryGetProperty("imeiType", out JsonElement imeiType);
  2253. var db = _azureCosmos.GetCosmosClient();
  2254. foreach (var stu in stus.EnumerateArray())
  2255. {
  2256. await foreach (var item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIteratorSql(
  2257. queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}' and c.school='{school}' ",
  2258. requestOptions: new() { PartitionKey = new($"Imei") }))
  2259. {
  2260. using var root = await JsonDocument.ParseAsync(item.Content);
  2261. if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2262. {
  2263. var doc = root.RootElement.GetProperty("Documents").EnumerateArray().First();
  2264. var imei = doc.ToObject<Imei>();
  2265. imei.channel = channel.GetString();
  2266. imei.userid = userid.GetString();
  2267. if (!string.IsNullOrWhiteSpace($"{imeiType}"))
  2268. {
  2269. imei.imeiType = $"{imeiType}";
  2270. }
  2271. else
  2272. {
  2273. if (imei.id.Length == 11)
  2274. {
  2275. imei.imeiType = "139zhxy";
  2276. }
  2277. else if (imei.id.Length == 15)
  2278. {
  2279. imei.imeiType = "tianbo";
  2280. }
  2281. }
  2282. await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id);
  2283. }
  2284. }
  2285. }
  2286. }
  2287. }
  2288. catch (Exception ex)
  2289. {
  2290. await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF error\n{ex.Message}\n{ex.StackTrace}{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2291. }
  2292. finally
  2293. {
  2294. // Complete the message
  2295. await messageActions.CompleteMessageAsync(message);
  2296. }
  2297. }
  2298. /// <summary>
  2299. /// UseDevelopmentStorage=true
  2300. /// </summary>
  2301. /// <param name="message"></param>
  2302. /// <param name="messageActions"></param>
  2303. /// <returns></returns>
  2304. [Function("BlobRoot")]
  2305. public async Task BlobRoot(
  2306. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")]
  2307. ServiceBusReceivedMessage message,
  2308. ServiceBusMessageActions messageActions)
  2309. {
  2310. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2311. _logger.LogInformation("Message Body: {body}", message.Body);
  2312. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2313. try
  2314. {
  2315. _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
  2316. {
  2317. var jsonMsg = JsonDocument.Parse(message.Body).RootElement.ToObject<BlobRefreshMessage>();
  2318. if (!string.IsNullOrWhiteSpace($"{jsonMsg.root}") && !string.IsNullOrWhiteSpace($"{jsonMsg.name}"))
  2319. {
  2320. string lockKey = $"Blob:Lock:{jsonMsg.name}:{jsonMsg.root}";
  2321. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  2322. if (exist)
  2323. {
  2324. string[] uls = System.Web.HttpUtility.UrlDecode($"{jsonMsg.root}", Encoding.UTF8).Split("/");
  2325. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  2326. string name = $"{jsonMsg.name}";
  2327. await RefreshBlob(name, u);
  2328. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  2329. }
  2330. }
  2331. });
  2332. }
  2333. catch { }
  2334. finally
  2335. {
  2336. // Complete the message
  2337. await messageActions.CompleteMessageAsync(message);
  2338. }
  2339. }
  2340. /// <summary>
  2341. /// 統測評量開始結束
  2342. /// </summary>
  2343. /// <param name="message"></param>
  2344. /// <param name="messageActions"></param>
  2345. /// <returns></returns>
  2346. [Function("JointExam")]
  2347. public async Task JointExamFunc(
  2348. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointexam", Connection = "Azure:ServiceBus:ConnectionString")]
  2349. ServiceBusReceivedMessage message,
  2350. ServiceBusMessageActions messageActions)
  2351. {
  2352. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2353. _logger.LogInformation("Message Body: {body}", message.Body);
  2354. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2355. var json = JsonDocument.Parse(message.Body);
  2356. try
  2357. {
  2358. json.RootElement.TryGetProperty("id", out JsonElement id);
  2359. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  2360. json.RootElement.TryGetProperty("code", out JsonElement code);
  2361. var client = _azureCosmos.GetCosmosClient();
  2362. JointExam jointExam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<JointExam>(id.ToString(), new PartitionKey($"{code}"));
  2363. jointExam.progress = progress.ToString();
  2364. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(jointExam, id.ToString(), new PartitionKey($"{code}"));
  2365. }
  2366. catch (CosmosException e)
  2367. {
  2368. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2369. }
  2370. catch (Exception ex)
  2371. {
  2372. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2373. }
  2374. finally
  2375. { // Complete the message
  2376. await messageActions.CompleteMessageAsync(message);
  2377. }
  2378. }
  2379. /// <summary>
  2380. /// 統測活動行程進行狀況更新
  2381. /// </summary>
  2382. /// <param name="message"></param>
  2383. /// <param name="messageActions"></param>
  2384. /// <returns></returns>
  2385. [Function("JointEventSchedule")]
  2386. public async Task JointEventFunc(
  2387. [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointevent-schedule", Connection = "Azure:ServiceBus:ConnectionString")]
  2388. ServiceBusReceivedMessage message,
  2389. ServiceBusMessageActions messageActions,
  2390. ExecutionContext context)
  2391. {
  2392. _logger.LogInformation("Message ID: {id}", message.MessageId);
  2393. _logger.LogInformation("Message Body: {body}", message.Body);
  2394. _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
  2395. var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
  2396. try
  2397. {
  2398. //多國語字典
  2399. //string rootPath = _environment.ContentRootPath;
  2400. //List<string> langList = new List<string>() { "en-us", "zh-cn", "zh-tw" };
  2401. //Dictionary<string, JObject> langDic = new Dictionary<string, JObject>();
  2402. //foreach (string langCode in langList)
  2403. //{
  2404. // string path = Path.Combine(rootPath, $"Lang/{langCode}.json");
  2405. // if (File.Exists(path))
  2406. // {
  2407. // string jsonContent = await File.ReadAllTextAsync(path);
  2408. // JObject jsonObject = JObject.Parse(jsonContent);
  2409. // langDic.Add(langCode, jsonObject);
  2410. // }
  2411. //}
  2412. jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
  2413. jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
  2414. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  2415. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  2416. string PartitionKey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", $"{progress}"); //主key: JointEvent-{jointEventId}-schedule-{progress} RowKey: {jointScheduleId}
  2417. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKey } });
  2418. bool updFlg = false;
  2419. string code = "JointEvent";
  2420. var client = _azureCosmos.GetCosmosClient();
  2421. JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<JointEvent>(jointEventId.ToString(), new PartitionKey($"{code}"));
  2422. if (jointEvent != null)
  2423. {
  2424. JointEvent.JointEventSchedule jointEventSchedule = jointEvent.schedule.Where(s => s.id.Equals($"{jointScheduleId}")).FirstOrDefault();
  2425. if (jointEventSchedule != null)
  2426. {
  2427. //資料處理
  2428. if (!jointEventSchedule.progress.Equals($"{progress}"))
  2429. {
  2430. jointEventSchedule.progress = $"{progress}";
  2431. updFlg = true;
  2432. }
  2433. if (updFlg)
  2434. {
  2435. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(jointEvent, jointEvent.id);
  2436. }
  2437. //訊息處理
  2438. switch (jointEventSchedule.progress)
  2439. {
  2440. case "pending":
  2441. var msg = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "going" }.ToJsonString());
  2442. msg.ApplicationProperties.Add("name", "JointEventSchedule");
  2443. if (records.Count > 0)
  2444. {
  2445. try
  2446. {
  2447. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  2448. }
  2449. catch (Exception)
  2450. {
  2451. }
  2452. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
  2453. records[0].sequenceNumber = start;
  2454. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  2455. }
  2456. else
  2457. {
  2458. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
  2459. ChangeRecord changeRecord = new ChangeRecord
  2460. {
  2461. RowKey = jointEventSchedule.id,
  2462. PartitionKey = PartitionKey,
  2463. sequenceNumber = start,
  2464. msgId = message.MessageId
  2465. };
  2466. await table.Save<ChangeRecord>(changeRecord);
  2467. }
  2468. break;
  2469. case "going":
  2470. //刪除pending訊息
  2471. string pkey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "pending");
  2472. await table.DeleteSingle<ChangeRecord>(pkey, jointEventSchedule.id);
  2473. //發送finish訊息
  2474. var messageEnd = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "finish" }.ToJsonString());
  2475. messageEnd.ApplicationProperties.Add("name", "JointEventSchedule");
  2476. if (records.Count > 0)
  2477. {
  2478. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
  2479. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  2480. records[0].sequenceNumber = end;
  2481. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  2482. }
  2483. else
  2484. {
  2485. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
  2486. ChangeRecord changeRecord = new ChangeRecord
  2487. {
  2488. RowKey = jointEventSchedule.id,
  2489. PartitionKey = PartitionKey,
  2490. sequenceNumber = end,
  2491. msgId = messageEnd.MessageId
  2492. };
  2493. await table.Save<ChangeRecord>(changeRecord);
  2494. }
  2495. //寄發Email
  2496. ///取得收信者Email ※ jointCourse.creatorEmail
  2497. //List<dynamic> users = new List<dynamic>();
  2498. //if (jointEventSchedule.type.Equals("exam"))
  2499. //{
  2500. // //一般競賽 ※決賽 名單架構確定後再取
  2501. // if (jointEventSchedule.examType.Equals("regular"))
  2502. // {
  2503. // await foreach (var jc in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql(queryText: $"SELECT DISTINCT c.creatorId, c.creatorName, c.creatorEmail FROM c WHERE c.jointEventId = '{jointEvent.id}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointCourse") }))
  2504. // {
  2505. // using var json = await JsonDocument.ParseAsync(jc.Content);
  2506. // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2507. // {
  2508. // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2509. // {
  2510. // EmailUser user = new EmailUser();
  2511. // user.tmid = (obj.TryGetProperty("creatorId", out JsonElement _creatorId)) ? _creatorId.GetString() : string.Empty;
  2512. // user.name = (obj.TryGetProperty("creatorName", out JsonElement _creatorName)) ? _creatorName.GetString() : string.Empty;
  2513. // user.email = (obj.TryGetProperty("creatorEmail", out JsonElement _creatorEmail)) ? _creatorEmail.GetString() : string.Empty;
  2514. // if (!string.IsNullOrWhiteSpace(user.tmid) && !string.IsNullOrWhiteSpace(user.email))
  2515. // {
  2516. // users.Add(user);
  2517. // }
  2518. // }
  2519. // }
  2520. // }
  2521. // }
  2522. //}
  2523. //if (users.Count > 0)
  2524. //{
  2525. // //取得模板ID ※國際站就用繁體,大陸站就用簡體 [待定]
  2526. // string location = Environment.GetEnvironmentVariable("Option:Location");
  2527. // //string tid = (location.Contains("China")) ? "" : "d-833d40ac6397414b852b91e2fa45850a";
  2528. // string tid = string.Empty;
  2529. // string lang = (location.Contains("China")) ? "zh-cn" : "zh-tw";
  2530. // //取得通知內文
  2531. // string mailTitle = string.Empty;
  2532. // string mailBody = string.Empty;
  2533. // JObject jsonObject = langDic[lang];
  2534. // if (jsonObject.TryGetValue("joint-schedule-start", out JToken msgToken))
  2535. // {
  2536. // JArray msgArray = (JArray)msgToken;
  2537. // mailTitle = msgArray[0].ToString();
  2538. // mailBody = $"{msgArray[1].ToString()}";
  2539. // }
  2540. // foreach (dynamic user in users)
  2541. // {
  2542. // if (!string.IsNullOrWhiteSpace(tid)) //※大陸站無模板,暫時不發
  2543. // {
  2544. // mailBody = mailBody.Replace("{tmdname}", user.name).Replace("{event}", jointEventSchedule.name);
  2545. // await _coreAPIHttpService.SendMail(new Dictionary<string, object> { { "to", user.email }, { "tid", tid }, { "vars", new { name = user.name } } }, location, _configuration);
  2546. // }
  2547. // }
  2548. //}
  2549. break;
  2550. case "finish":
  2551. string pk = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "going");
  2552. await table.DeleteSingle<ChangeRecord>(pk, jointEventSchedule.id);
  2553. //寄發Email [待模板ID]
  2554. //熱身賽行程結束、決賽名單計算
  2555. if(jointEventSchedule.type.Equals("exam") && jointEventSchedule.examType.Equals("regular"))
  2556. {
  2557. string scope = "private"; //先寫死為個人
  2558. List<string> jointGroupIds = jointEvent.groups.Select(g => g.id).ToList();
  2559. if (jointGroupIds.Count > 0)
  2560. {
  2561. foreach (string jointGroupId in jointGroupIds)
  2562. {
  2563. List<JointEventGroupDb> addResult = await JointService.CreatePassJointCourseBySchedule(client, $"{jointEventId}", jointGroupId, jointEventSchedule.id, scope);
  2564. }
  2565. }
  2566. }
  2567. break;
  2568. }
  2569. }
  2570. }
  2571. }
  2572. catch (CosmosException e)
  2573. {
  2574. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2575. }
  2576. catch (Exception ex)
  2577. {
  2578. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2579. }
  2580. finally
  2581. { // Complete the message
  2582. await messageActions.CompleteMessageAsync(message);
  2583. }
  2584. }
  2585. private async Task RefreshBlob(string name, string u)
  2586. {
  2587. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2588. var client = _azureStorage.GetBlobContainerClient(name);
  2589. var size = await client.GetBlobsSize(u);
  2590. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  2591. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  2592. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  2593. double blobsize = 0;
  2594. if (scores != default && scores != null)
  2595. {
  2596. foreach (var score in scores)
  2597. {
  2598. blobsize = blobsize + score.Score;
  2599. }
  2600. }
  2601. if (blobsize > 0)
  2602. {
  2603. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  2604. }
  2605. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2606. long dis = (end - statr) / 1000;
  2607. long timeout = 60 * 5;
  2608. if (dis > timeout)
  2609. {
  2610. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
  2611. }
  2612. //await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
  2613. }
  2614. private class EmailUser
  2615. {
  2616. public string tmid { get; set; }
  2617. public string name { get; set; }
  2618. public string email { get; set; }
  2619. }
  2620. }
  2621. }