IESServiceBusTrigger.cs 177 KB

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