IESServiceBusTrigger.cs 175 KB

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