IESServiceBusTrigger.cs 206 KB

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