IESServiceBusTrigger.cs 215 KB

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