IESServiceBusTrigger.cs 169 KB

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