IESServiceBusTrigger.cs 207 KB

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