123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102 |
- using System;
- using System.Threading.Tasks;
- using Azure.Messaging.ServiceBus;
- using DinkToPdf.Contracts;
- using Microsoft.Azure.Functions.Worker;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Logging;
- using TEAMModelOS.Function.DI;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK;
- using TEAMModelOS.Models;
- using Microsoft.Extensions.Options;
- using static Microsoft.Azure.Amqp.Serialization.SerializableType;
- using System.Text.Json;
- using TEAMModelOS.SDK.Models;
- using Microsoft.Azure.Cosmos;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using StackExchange.Redis;
- using static TEAMModelOS.SDK.StatisticsService;
- using Azure;
- using TEAMModelOS.SDK.Models.Dtos;
- using TEAMModelOS.SDK.Models.Service.BI;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Services;
- using Azure.Storage.Blobs.Models;
- using static TEAMModelOS.SDK.Models.Service.LessonService;
- using System.Text;
- using Microsoft.Azure.Cosmos.Linq;
- using System.Net.Http.Json;
- using System.Threading;
- using System.Text.Json.Nodes;
- using System.Web;
- using Azure.Storage.Blobs;
- using static TEAMModelOS.SDK.CoreAPIHttpService;
- using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
- using System.Net;
- using Newtonsoft.Json;
- using System.Security.Policy;
- using System.Net.Http.Headers;
- using Microsoft.AspNetCore.Hosting;
- using Newtonsoft.Json.Linq;
- using HTEX.Lib.ETL.Lesson;
- using System.Globalization;
- using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
- using static TEAMModelOS.SDK.Models.Service.SystemService;
- namespace TEAMModelOS.Function
- {
- public class IESServiceBusTrigger
- {
- private readonly ILogger<IESServiceBusTrigger> _logger;
- private readonly int psize = 20;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly Option _option;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IConfiguration _configuration;
- // private readonly IConverter _converter;
- private readonly SnowflakeId _snowflakeId;
- private readonly HttpTrigger _httpTrigger;
- private readonly BackgroundWorkerQueue _backgroundWorkerQueue;
- private readonly IHttpClientFactory _httpClient;
- private readonly IWebHostEnvironment _environment;
- public IESServiceBusTrigger(ILogger<IESServiceBusTrigger> logger, HttpTrigger httpTrigger, SnowflakeId snowflakeId, CoreAPIHttpService coreAPIHttpService,
- AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis,
- AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option,
- IConfiguration configuration, BackgroundWorkerQueue backgroundWorkerQueue, IHttpClientFactory httpClient, IWebHostEnvironment hostingEnvironment)
- {
- _logger = logger;
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _serviceBus = serviceBus;
- _option = option?.Value;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _snowflakeId = snowflakeId;
- _httpTrigger = httpTrigger;
- _backgroundWorkerQueue = backgroundWorkerQueue;
- _httpClient=httpClient;
- _environment = hostingEnvironment;
- }
- [Function("GenPdf")]
- public async Task GenPdfFunc([ServiceBusTrigger("%Azure:ServiceBus:GenPdfQueue%", Connection = "Azure:ServiceBus:ConnectionString", IsBatched = false)] ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- //https://github.com/aafgani/AzFuncWithServiceBus/blob/a0da42f59b5fc45655b73b85bae932e84520db70/ServiceBusTriggerFunction/host.json
- // messageHandlerOptions 设置
- // https://dotblogs.com.tw/yc421206/2013/04/25/102300 // C# 原子操作。Interlocked
- // ConcurrentQueue http://t.zoukankan.com/hohoa-p-12622459.html
- // await messageActions.RenewMessageLockAsync(message);
- long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- Console.WriteLine($"開始:{time}");
- string apiUri = "http://52.130.252.100:13000";
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var json = JsonDocument.Parse(message.Body).RootElement;
- try
- {
- switch (true)
- {
- case bool when json.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("OfflineRecord"):
- //处理教师线下研修报告的生成。
- //await GenOfflineRecordPdf(element, msg);
- break;
- case bool when json.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("ArtStudentPdf"):
- json.TryGetProperty("studentIds", out JsonElement _studentIds);
- json.TryGetProperty("artId", out JsonElement _artId);
- json.TryGetProperty("schoolCode", out JsonElement _schoolId);
- json.TryGetProperty("headLang", out JsonElement headLang);
- List<string> studentIds = _studentIds.ToObject<List<string>>();
- var data = await GenPDFService.GenArtStudentPdf(_azureRedis, _azureCosmos, _coreAPIHttpService, _dingDing, _azureStorage,_configuration, studentIds,$"{_artId}",$"{_schoolId}",$"{headLang}");
- await GenPDFService. PushScreenTask(_azureRedis, _configuration, $"{_artId}",data. art,data. studentPdfs,_httpClient,_dingDing);
- break;
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- // [Function("GenPDF")]
- public async Task Run(
- [ServiceBusTrigger("dep-genpdf", Connection = "Azure:ServiceBus:ConnectionString" , IsBatched =false) ]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
-
- // await messageActions.RenewMessageLockAsync(message);
- long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- Console.WriteLine($"開始:{time}");
- string apiUri = "http://52.130.252.100:13000";
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var json = JsonDocument.Parse(message.Body);
- try
- {
- // Complete the message
-
- PDFGenQueue genQueueData = json.RootElement.ToObject<PDFGenQueue>();
- RedisValue redisValue= await _azureRedis.GetRedisClient(8).HashGetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id);
- PDFGenRedis genRedis = null ;
- if (redisValue!=default)
- {
- genRedis = redisValue.ToString().ToObject<PDFGenRedis>();
- //计算等待了多久的时间才开始生成。
- var wait = now- genRedis.join;
- genRedis.wait = wait;
- genRedis.status= 1;
- await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
- var client = _httpClient.CreateClient();
- ///再加5秒
- client.Timeout= TimeSpan.FromMilliseconds(genQueueData.timeout+ genQueueData.delay+5000);
- try
- {
- string urlpdf =$"{apiUri}/api/pdf";
- string jsonElement= new {
- pageUrl = genQueueData.pageUrl,
- timeout = genQueueData.timeout,
- delay = genQueueData.delay,
- checkPageCompleteJs = genQueueData.checkPageCompleteJs
- }.ToJsonString();
- var request = new HttpRequestMessage
- {
- Method = new HttpMethod("POST"),
- RequestUri = new Uri(urlpdf),
- Content = new StringContent(jsonElement)
- };
- var mediaTypeHeader = new MediaTypeHeaderValue("application/json")
- {
- CharSet = "UTF-8"
- };
- request.Content.Headers.ContentType = mediaTypeHeader;
- HttpResponseMessage responseMessage = await client.SendAsync(request);
- if (responseMessage.IsSuccessStatusCode)
- {
- string content = await responseMessage.Content.ReadAsStringAsync();
- JsonNode jsonNode = content.ToObject<JsonNode>();
- var code = jsonNode["code"];
- var file = jsonNode["data"]?["file"];
- if (code!=null && $"{code}".Equals("0") && file!= null && !string.IsNullOrWhiteSpace($"{file}"))
- {
- try
- {
- Stream stream = await client.GetStreamAsync($"{apiUri}/{file}");
- Uri uri = new Uri(genQueueData.pageUrl);
- var query = HttpUtility.ParseQueryString(uri.Query);
- string? url = query["url"];
- if (!string.IsNullOrWhiteSpace(url))
- {
- url= HttpUtility.UrlDecode(url);
- uri = new Uri(url);
- string host = uri.Host;
- var blobServiceClient = _azureStorage.GetBlobServiceClient();
- if (blobServiceClient.Uri.Host.Equals(host))
- {
- // 获取容器名,它是路径的第一个部分
- string containerName = uri.Segments[1].TrimEnd('/');
- // 获取文件的完整同级目录,这是文件路径中除了文件名和扩展名之外的部分
- // 由于文件名是路径的最后一个部分,我们可以通过连接除了最后一个部分之外的所有部分来获取目录路径
- string directoryPath = string.Join("", uri.Segments, 2, uri.Segments.Length - 3);
- string? fileName = Path.GetFileNameWithoutExtension(uri.AbsolutePath);
- string blobPath = $"{directoryPath}{fileName}.pdf";
- var blockBlob = _azureStorage.GetBlobContainerClient(containerName).GetBlobClient(blobPath);
- string content_type = "application/octet-stream";
- ContentTypeDict.dict.TryGetValue(".pdf", out string? contenttype);
- if (!string.IsNullOrEmpty(contenttype))
- {
- content_type = contenttype;
- }
- await blockBlob.UploadAsync(stream, true);
- blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
- genRedis.blob= blockBlob.Name;
- genRedis.status=2;
- }
- else
- {
- genRedis.status=6;
- }
- }
- else
- {
- genRedis.status=6;
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- genRedis.status=6;
- }
- }
- else
- {
- if (code!= null && $"{code}".Equals("99999"))
- {
- genRedis.status= 4;
- }
- else {
- genRedis.status= 3;
- }
- }
- }
- else {
- genRedis.status= 3;
- }
- }
- catch (TaskCanceledException ex)
- {
- if (ex.CancellationToken.IsCancellationRequested)
- {
- // Console.WriteLine("请求被取消。");
- genRedis.status= 5;
- }
- else
- {
- //Console.WriteLine("请求超时。");
- genRedis.status= 4;
- }
- }
- catch (Exception ex)
- {
- genRedis.status=3;
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- else
- {
- genRedis= new PDFGenRedis { id =genQueueData.id, status= 5, cost=0, join=now, wait=0,name= genQueueData .name };
- //被取消的
- }
- long nowNew = DateTimeOffset.Now.ToUnixTimeMilliseconds();
- genRedis.cost=nowNew-now;
- await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
- //如果全部 生成,需要发送通知
-
- HashEntry[] datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"PDFGen:{genQueueData.sessionId}");
- List<PDFGenRedis> dbgenRedis = new List<PDFGenRedis>();
- List<string> notifyUsers = new List<string>();
- string taskName = string.Empty;
- string taskType = string.Empty;
- if (datas!= null && datas.Length > 0)
- {
- foreach (var item in datas)
- {
- if (!$"{item.Name}".Contains("notifyUsers"))
- {
- dbgenRedis.Add(item.Value.ToString().ToObject<PDFGenRedis>());
- }
- else
- {
- var jsonData = item.Value.ToString().ToObject<JsonElement>();
- notifyUsers= jsonData.GetProperty("notifyUsers").ToObject<List<string>>();
- taskType = jsonData.GetProperty("taskType").ToString();
- taskName = jsonData.GetProperty("taskName").ToString();
- }
- }
- }
- if (notifyUsers.IsNotEmpty())
- {
- string lang = Environment.GetEnvironmentVariable("Option:Location")!.Contains("China") ? "zh-cn" : "en-us";
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", notifyUsers.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- 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; });
-
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- string location = "China";
- if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("China"))
- {
- location = "China";
- }
- else if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("Global"))
- {
- location = "Global";
- }
- var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
- var client = _httpClient.CreateClient();
- if (client.DefaultRequestHeaders.Contains("Authorization"))
- {
- client.DefaultRequestHeaders.Remove("Authorization");
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- else
- {
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- //检查dbgenRedis的状态是否全部已经不是0和1
- var unfinished = dbgenRedis.FindAll(x => (x.status==0||x.status==1));
- if (unfinished==null || unfinished.Count==0)
- {
- // 数据大于60一个班,发送报告的总耗时等概要信息, 小于60的发送 生成报告的细则消息,小于五个的,可以列出报告的链接.
- long joinTime = dbgenRedis.Min(x => x.join);
- long totalTime = (now-joinTime)/1000;
- long costTime = dbgenRedis.Sum(x => x.cost)/1000;
- long avgTime = costTime / dbgenRedis.Count;
- long maxTime = dbgenRedis.Max(x => x.cost)/1000;
- long minTime = dbgenRedis.Min(x => x.cost)/1000;
- long statusOk = dbgenRedis.Where(x => x.status==2).Count();
- long statusFailed = dbgenRedis.Where(x => x.status!=2).Count();
- string key = "pdf-gen-notify-higher60";
- if (dbgenRedis.Count>60)
- {
- key = "pdf-gen-notify-higher60";
- }
- else
- {
- key ="pdf-gen-notify-below60";
- }
-
- foreach (var teacher in idNameCodes)
- {
- string path = Path.Combine("", $"Lang/{teacher.code}.json");
- var sampleJson = File.ReadAllText(path);
- JsonElement jsonElement = sampleJson.ToObject<JsonElement>();
- JsonElement msgsJson = jsonElement.GetProperty(key);
- List<string> msgs = msgsJson.ToObject<List<string>>();
- string msg1 = msgs[1].Replace("{tmdname}", teacher.name).Replace("{taskName}", taskName).Replace("{totalTime}",$"{totalTime}")
- .Replace("{avgTime}",$"{avgTime}").Replace("{maxTime}",$"{maxTime}").Replace("{minTime}",$"{minTime}").Replace("{statusOk}",$"{statusOk}").Replace("{statusFailed}",$"{statusFailed}");
- StringBuilder sb = new StringBuilder($"{msg1}");
- if (dbgenRedis.Count<=60)
- {
- string status = string.Empty;
- dbgenRedis.ForEach(x => {
- switch (x.status)
- {
- case 0:
- status= teacher.code.Equals("zh-cn") ? "未执行" : teacher.code.Equals("zh-tw") ? "未執行" : "unexecuted";
- break;
- case 1:
- status= teacher.code.Equals("zh-cn") ? "执行中" : teacher.code.Equals("zh-tw") ? "執行中" : "executing";
- break;
- case 2:
- status= teacher.code.Equals("zh-cn") ? "成功" : teacher.code.Equals("zh-tw") ? "成功" : "success";
- break;
- case 3:
- status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
- break;
- case 4:
- status= teacher.code.Equals("zh-cn") ? "超时" : teacher.code.Equals("zh-tw") ? "超時" : "timeout";
- break;
- case 5:
- status= teacher.code.Equals("zh-cn") ? "取消" : teacher.code.Equals("zh-tw") ? "取消" : "canceled";
- break;
- case 6:
- status= teacher.code.Equals("zh-cn") ? "存放异常" : teacher.code.Equals("zh-tw") ? "存放異常" : "SaveError";
- break;
- default:
- status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
- break;
- }
- 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}");
- sb.Append(msg2);
- });
- }
- NotifyData notifyData = new NotifyData
- {
- hubName = "hita5",
- sender = "IES",
- tags = new List<string> { $"{teacher.id}_{Constant.NotifyType_IES5_Course}"},
- title = msgs[0],
- eventId = $"{key}_{_snowflakeId.NextId()}",
- eventName =msgs[0],
- data = "{\"value\":{}}",
- body=sb.ToString(),
- };
- string result = "";
- try
- {
- HttpResponseMessage responseMessage =await client.PostAsJsonAsync($"{url}/service/PushNotify", notifyData);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string content = await responseMessage.Content.ReadAsStringAsync();
- result = content;
- }
- else
- {
- result = $"{responseMessage.StatusCode},推送返回的状态码。";
- }
- }
- catch (Exception exm)
- {
- _= _dingDing.SendBotMsg($"{location}站点发送消息异常,{exm.Message}\n{exm.StackTrace}:\n{url}/service/PushNotify \nheader: {token.AccessToken} \nresult:{result}\n params:{notifyData.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- }
-
- }
- }
- Console.WriteLine($"結束:{time}");
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Exam")]
- public async Task ExamFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var json = JsonDocument.Parse(message.Body);
- try
- {
- json.RootElement.TryGetProperty("id", out JsonElement id);
- json.RootElement.TryGetProperty("progress", out JsonElement progress);
- json.RootElement.TryGetProperty("code", out JsonElement code);
- //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
- exam.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Vote")]
- public async Task VoteFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
- vote.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Correct")]
- public async Task CorrectFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
- correct.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Survey")]
- public async Task SurveyFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
- var client = _azureCosmos.GetCosmosClient();
- Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
- survey.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Homework")]
- public async Task HomeworkFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
- homework.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Study")]
- public async Task StudyFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- string activityId = string.Empty;
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
- study.progress = progress.ToString();
- activityId = id.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Art")]
- public async Task ArtFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "art", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- string activityId = string.Empty;
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- ArtEvaluation art = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ArtEvaluation>(id.ToString(), new PartitionKey($"{code}"));
- art.progress = progress.ToString();
- activityId = id.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(art, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Art()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Art()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("ExamLite")]
- public async Task ExamLiteFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
- lite.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("TeacherTrainChange")]
- public async Task TeacherTrainChangeFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var data = JsonDocument.Parse(message.Body).RootElement.ToObject<TeacherTrainChangeMsg>();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- List<TeacherTrain> trains = new List<TeacherTrain>();
- //redis锁
- bool lockKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Train:Statistics:Lock:{data.areaId}");
- if (!lockKey)
- {
- await _azureRedis.GetRedisClient(8).SetAddAsync($"Train:Statistics:Lock:{data.areaId}", new RedisValue(data.areaId));
- DateTime minutes = DateTime.UtcNow.AddMinutes(15); //15分钟
- await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Train:Statistics:Lock:{data.areaId}", minutes);
- Area area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{data.areaId}", new PartitionKey("Base-Area"));
- AreaSetting setting = null;
- if (area != null)
- {
- try
- {
- setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- setting = null;
- }
- }
- if (setting == null)
- {
- setting = new AreaSetting
- {
- allTime = 50,
- classTime = 5,
- submitTime = 15,
- onlineTime = 20,
- offlineTime = 10,
- lessonMinutes = 45,
- };
- }
- foreach (var school in data.schools)
- {
- List<Study> studies = new List<Study>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common")
- .GetItemQueryIteratorSql<Study>(queryText: $"select value(c) from c where c.owner<>'area' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{school.school}") }))
- {
- studies.Add(item);
- }
- if (school.teachers.Any())
- {
- string trainSql = $"select value(c) from c where c.id in ({string.Join(",", school.teachers.Select(x => $"'{x}'"))}) ";
- await foreach (var item in client.GetContainer("TEAMModelOS", Constant.Teacher)
- .GetItemQueryIteratorSql<TeacherTrain>(queryText: trainSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{school.school}") }))
- {
- trains.Add(item);
- }
- }
- await StatisticsService.GetStatisticsTeacher(trains, setting, area, client, studies);
- }
- area.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- await client.GetContainer(Constant.TEAMModelOS, "Normal").ReplaceItemAsync<Area>(area, $"{data.areaId}", new PartitionKey("Base-Area"));
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-TeacherTrainChange\n{ex.Message}\n{ex.StackTrace}\n\n{message.Body}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
- /// </summary>
- /// <data msg>
- /// CourseChange
- ///// </data>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("GroupChange")]
- public async Task GroupChangeFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var client = _azureCosmos.GetCosmosClient();
- var jsonMsg = JsonDocument.Parse(message.Body);
- GroupChange groupChange = jsonMsg.RootElement.ToObject<GroupChange>();
- try
- {
- _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
- {
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.醍摩豆服務運維群組);
- //await _dingDing.SendBotMsg($"名单变化{msg}", GroupNames.成都开发測試群組);
- int add = groupChange.tmdjoin.Count - groupChange.tmdleave.Count + groupChange.stujoin.Count - groupChange.stuleave.Count;
- if (groupChange.scope.Equals("private") && (groupChange.type.Equals("student") || groupChange.type.Equals("class") || groupChange.type.Equals("teach")))
- {
- 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 });
- }
- if (groupChange.scope.Equals("school") && (groupChange.type.Equals("student") || groupChange.type.Equals("class") || groupChange.type.Equals("teach")))
- {
- 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 });
- }
- //名单变动修改学生课程关联信息
- //await StuListService.FixStuCourse(client, stuListChange);
- //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
- //名单变动修改学生问卷关联信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
- //名单变动修改学生投票关联信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
- //名单变动修改学生评测关联信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
- //名单变动修改学生研修关联信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Study");
- //名单变动修改学生简易评测关联信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
- //名单变动修改学生作业活动信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
- //名单变动修改学生艺术评价活动信息
- //await IESActivityService.FixActivity(client, _dingDing, groupChange, "Art");
- //TODO学习活动
- //await FixActivity(client, stuListChange, "Learn");
- if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
- {
- //课程名单变动修改学生课程关联信息
- // await IESActivityService.FixStuCourse(client, _dingDing, groupChange);
- //名单变动修改课例关联信息
- //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
- }
- if (groupChange.type.Equals("class") || groupChange.type.Equals("teach") || groupChange.type.Equals("student"))
- {
- await _httpTrigger.RequestHttpTrigger(new { data = groupChange }, Environment.GetEnvironmentVariable("Option:Location"), "webhook/group-member-change");
- if (groupChange.stujoin.Count > 0)
- await BIStats.SetTypeAddStats(client, _dingDing, groupChange.school, "Student", groupChange.stujoin.Count);//BI统计增/减量
- if (groupChange.stuleave.Count > 0)
- await BIStats.SetTypeAddStats(client, _dingDing, groupChange.school, "Student", -groupChange.stuleave.Count);//BI统计增/减量
- }
- 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))
- {
- var data = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { groupChange.listid }, groupChange.school);
- if (data.groups.IsNotEmpty())
- {
- School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(groupChange.school, new PartitionKey("Base"));
- var period = school.period.Find(z => z.id.Equals(data.groups.First().periodId));
- if (period != null)
- {
- var dataSemester = SchoolService.GetSemester(period, DateTimeOffset.Now.ToUnixTimeMilliseconds());
- string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{data.groups.First().id}";
- string code = $"GroupListSemester-{groupChange.school}";
- GroupListSemester groupListSemester = data.groups.First().ToJsonString().ToObject<GroupListSemester>();
- groupListSemester.id = id;
- groupListSemester.code = code;
- groupListSemester.pk = "GroupListSemester";
- groupListSemester.semesterId = dataSemester.currSemester.id;
- groupListSemester.groupListId = data.groups.First().id;
- groupListSemester.studyYear = dataSemester.studyYear;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- }
- }
- }
- });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("ItemCondDel")]
- public async Task ItemCondDelFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%/$DeadLetterQueue", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- await _dingDing.SendBotMsg($"{message.Body}", GroupNames.成都开发測試群組);
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("ItemCond")]
- public async Task ItemCondFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- List<ItemCondDto> itemCondDtos = jsonMsg.RootElement.ToObject<List<ItemCondDto>>();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- foreach (var itemCondDto in itemCondDtos)
- {
- if (itemCondDto.scope.Equals("school"))
- {
- ItemCond itemCond = null;
- List<ItemInfo> items = new List<ItemInfo>();
- School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{itemCondDto.key}", new PartitionKey("Base"));
- var period = school.period.Find(z => z.id.Equals(itemCondDto.filed));
- string subjectIn = string.Empty;
- if (period != null && period.subjects.IsNotEmpty())
- {
- subjectIn = $" and c.subjectId in({string.Join(",", period.subjects.Select(x => $"'{x.id}'"))})";
- }
- 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} ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
- {
- items.Add(item);
- }
- itemCond = new ItemCond()
- {
- id = $"{itemCondDto.filed}",
- code = $"ItemCond-{itemCondDto.key}",
- pk = "ItemCond",
- ttl = -1,
- count = items.Count,
- grades = new List<GradeCount>(),
- subjects = new List<SubjectItemCount>()
- };
- items.ForEach(z =>
- {
- if (!string.IsNullOrEmpty(z.type))
- {
- ItemService.CountItemCond(z, null, itemCond);
- }
- });
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
- }
- else
- {
- ItemCond itemCond = null;
- List<ItemInfo> items = new List<ItemInfo>();
- var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
- {
- items.Add(item);
- }
- itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
- items.ForEach(z =>
- {
- if (!string.IsNullOrEmpty(z.type))
- {
- ItemService.CountItemCond(z, null, itemCond);
- }
- });
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
- }
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Product")]
- public async Task ProductFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body);
- try
- {
- jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
- jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
- jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
- jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
- var client = _azureCosmos.GetCosmosClient();
- string strQuery = string.Empty;
- //取得所有學校產品
- ////序號
- List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
- SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
- if (serialProd == null)
- {
- SchoolProductSumData serialProdAdd = new SchoolProductSumData();
- serialProdAdd.prodCode = serialInfo.prodCode;
- serialProdAdd.ids.Add(serialInfo.id);
- serialProdAdd.avaliable = serialProdAdd.ids.Count;
- serialsProductSumOrg.Add(serialProdAdd);
- }
- else
- {
- if (!serialProd.ids.Contains(serialInfo.id))
- {
- serialProd.ids.Add(serialInfo.id);
- }
- serialProd.avaliable = serialProd.ids.Count;
- }
- }
- }
- }
- ////服務
- List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
- //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
- long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
- string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
- SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
- if (serviceProd == null)
- {
- SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
- serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
- serviceProdAdd.avaliable = 0;
- serviceProdAdd.ids.Add(servicePeriodInfo.id);
- serviceProdAdd.avaliable += servicePeriodInfo.number;
- serviceProdAdd.startDate = servicePeriodInfo.startDate;
- serviceProdAdd.endDate = servicePeriodInfo.endDate;
- servicesProductSumOrg.Add(serviceProdAdd);
- }
- else
- {
- serviceProd.ids = new List<string>();
- serviceProd.ids.Add(servicePeriodInfo.id);
- serviceProd.startDate = servicePeriodInfo.startDate;
- serviceProd.endDate = servicePeriodInfo.endDate;
- }
- }
- }
- }
- ////服務產品特別對應項
- School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
- bool updSchool = false; //是否變更學校基本資料
- int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
- int schoolDefaultSize = 1; //學校空間初始值:1
- if (!string.IsNullOrWhiteSpace(school.id))
- {
- if (servicesProductSumOrg.Count > 0)
- {
- foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
- {
- //更新學校空間
- if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
- {
- school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
- updSchool = true;
- chgSchSizeCnt++;
- }
- }
- }
- if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
- {
- school.size = schoolDefaultSize;
- //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
- updSchool = false;
- }
- }
- //變更學校基本資料
- if (updSchool)
- {
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
- }
- ////硬體
- List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
- SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
- if (hardProd == null)
- {
- SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
- hardProdAdd.prodCode = hardInfo.prodCode;
- hardProdAdd.model = hardInfo.model;
- hardProdAdd.ids.Add(hardInfo.id);
- hardProdAdd.avaliable = hardProdAdd.ids.Count;
- hardsProductSumOrg.Add(hardProdAdd);
- }
- else
- {
- if (!hardProd.ids.Contains(hardInfo.id))
- {
- hardProd.ids.Add(hardInfo.id);
- }
- hardProd.avaliable = hardProd.ids.Count;
- }
- }
- }
- }
- //更新學校產品一覽表
- SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
- prodSum.serial = serialsProductSumOrg;
- prodSum.service = servicesProductSumOrg;
- prodSum.hard = hardsProductSumOrg;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// 更新开课数据事件
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("LessonRecordEvent")]
- public async Task LessonRecordFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- JsonElement data = JsonDocument.Parse(message.Body).RootElement;
- string scope = "";
- string tmdid = "";
- string lessonId;
- string school;
- string tbname;
- string code = string.Empty;
- string blobname;
- List<LessonUpdate> updates = new List<LessonUpdate>();
- try
- {
- _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
- {
- //更新课堂记录
- if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
- {
- if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
- if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
- if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
- data.TryGetProperty("school", out JsonElement _school);
- school = $"{_school}";
- scope = $"{_scope}";
- tmdid = $"{_tmdid}";
- lessonId = $"{_lessonId}";
- updates = _grant_types.ToObject<List<LessonUpdate>>();
- }//创建课堂记录
- else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
- && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
- && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
- {
- data.TryGetProperty("school", out JsonElement _school);
- school = $"{_school}";
- scope = $"{_scope}";
- tmdid = $"{_tmdid}";
- lessonId = $"{_id}";
- updates.Add(new LessonUpdate { grant_type = "create" });
- }//删除课堂记录
- else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
- && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
- && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
- && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
- {
- data.TryGetProperty("school", out JsonElement _dschool);
- school = $"{_dschool}";
- if ($"{_opt}".Equals("delete"))
- {
- scope = $"{_dscope}";
- tmdid = $"{_dtmdid}";
- lessonId = $"{_delete_id}";
- updates.Add(new LessonUpdate { grant_type = "delete" });
- }
- else { return; }
- }
- else
- {
- return;
- }
- //if (!string.IsNullOrWhiteSpace(school) && school.Equals("habook"))
- //{
- // await _dingDing.SendBotMsg($"研发学校课堂记录事件触发:\n{msg}", GroupNames.成都开发測試群組);
- //}
- var client = _azureCosmos.GetCosmosClient();
- if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
- {
- blobname = $"{school}";
- code = $"LessonRecord-{school}";
- tbname = "School";
- }
- else if ($"{scope}".Equals("private"))
- {
- blobname = $"{tmdid}";
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return;
- }
- LessonDis lessonDis = new LessonDis();
- List<LessonUpdate> msgs = new List<LessonUpdate>();
- LessonRecord oldlessonRecord = null;
- LessonRecord lessonRecord = null;
- ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- var doc = JsonDocument.Parse(response.Content);
- lessonRecord = doc.RootElement.ToObject<LessonRecord>();
- oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
- }
- else
- {
- lessonRecord = null;
- }
- bool isReplace = true;
- if (updates.IsNotEmpty())
- {
- Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
- foreach (LessonUpdate update in updates)
- {
- switch (update.grant_type)
- {
- //更新课堂时长
- case "up-duration":
- double.TryParse($"{update.data}", out double duration);
- lessonRecord.duration = duration;
- msgs.Add(update);
- try
- {
- BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
- var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
- if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
- {
- var durationFile = double.Parse($"{_duration}");
- if (duration < durationFile)
- {
- lessonRecord.duration = durationFile;
- }
- }
- if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
- {
- lessonRecord.hasVideo = 1;
- }
- }
- catch (Exception ex)
- {
- // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
- }
- isReplace = true;
- break;
- //更新T分
- case "up-tScore":
- var tScore = int.Parse($"{update.data}");
- lessonRecord.tScore = tScore;
- msgs.Add(update);
- break;
- //更新课P分
- case "up-pScore":
- var pScore = int.Parse($"{update.data}");
- lessonRecord.pScore = pScore;
- msgs.Add(update);
- break;
- //更新 学生人数
- case "up-mCount":
- var mCount = int.Parse($"{update.data}");
- lessonRecord.mCount = mCount;
- msgs.Add(update);
- break;
- //更新 议课次数
- case "up-techCount":
- var techCount = int.Parse($"{update.data}");
- lessonRecord.mCount = techCount;
- msgs.Add(update);
- break;
- //更新 基础统计信息
- case "up-base":
- //读取TimeLine.json
- List<int> PickupMemberIds = new List<int>();
- TimeLineData timeLineData = new TimeLineData();
- try
- {
- BlobDownloadResult timeLineBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
- timeLineData = timeLineBlobDownload.Content.ToObjectFromJson<TimeLineData>();
- lessonRecord.hitaClientCmpCount = timeLineData.events.Where(z => !string.IsNullOrWhiteSpace(z.WrkCmpSrcType) && z.WrkCmpSrcType.Equals("HitaClientCmp")).Count();
- //lessonRecord.collateTaskCount = lessonRecord.hitaClientCmpCount;
- List<TimeLineEvent> timeLineEvents = timeLineData.events.FindAll(z => !string.IsNullOrWhiteSpace(z.Event) && z.Event.Equals("PickupResult"));
- if (timeLineEvents.IsNotEmpty())
- {
- foreach (var timeLineEvent in timeLineEvents)
- {
- var memberIds = timeLineEvent.PickupMemberId.ToObject<List<int>>();
- PickupMemberIds.AddRange(memberIds);
- }
- }
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},TimeLine.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取Task.json
- ///Event 过滤类型 : 'WrkSpaceLoad', 'WrkCmp' 文件:Task.json 根据clientWorks 中的seatID 匹配base.json 中的 student
- List<TaskData> taskDatas = new List<TaskData>();
- try
- {
- BlobDownloadResult taskBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/Task.json").DownloadContentAsync();
- taskDatas = taskBlobDownload.Content.ToObjectFromJson<List<TaskData>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},Task.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取互评信息
- //Event 过滤类型 'RatingStart'
- //smartRateSummary.mutualSummary.mutualType 互评【All(每人多件评分) Two(随机分配互评) Self(自评)】 smartRateSummary.meteor_VoteSummary 投票
- //读取IRS.json
- List<SmartRatingData> smartRatingDatas = new List<SmartRatingData>();
- try
- {
- BlobDownloadResult smartRatingBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/IRS.json").DownloadContentAsync();
- smartRatingDatas = smartRatingBlobDownload.Content.ToObjectFromJson<List<SmartRatingData>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取互动信息
- //Event 过滤类型 'PopQuesLoad', 'ReAtmpAnsStrt', 'BuzrAns','BuzrLoad'
- //TimeLine.json 中找到对应类型,根据Pgid 去 IRS.json 中找到对应数据,从clientAnswers 的下标对应 base.json 中的 student 找到对应学生信息 clientAnswers.length > 1 则表示有二次作答
- //读取IRS.json
- List<IRSData> irsDatas = new List<IRSData>();
- try
- {
- BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/IRS.json").DownloadContentAsync();
- irsDatas = irsBlobDownload.Content.ToObjectFromJson<List<IRSData>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取协作信息
- ///Event 过滤类型 'CoworkLoad'
- //TimeLine.json 中找到对应类型,根据Pgid 去 Cowork.json 中找到对应数据
- List<CoworkData> coworkDatas = new List<CoworkData>();
- try
- {
- BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/Cowork.json").DownloadContentAsync();
- coworkDatas = irsBlobDownload.Content.ToObjectFromJson<List<CoworkData>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //苏格拉底文件信息
- //Sokrates/SokratesRecords.json
- List<TimeLineEvent> sokratesDatas = new List<TimeLineEvent>();
- try
- {
- BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/Sokrates/SokratesRecords.json").DownloadContentAsync();
- sokratesDatas = irsBlobDownload.Content.ToObjectFromJson<List<TimeLineEvent>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取base.json信息
- //如果有更新 则去读取/{_lessonId}/IES/base.json
- List<LocalStudent> studentLessonDatas = new List<LocalStudent>();
- LessonBase lessonBase = null;
- try
- {
- // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
- BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
- //attendState
- string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall", "0");
-
- try
- {
- lessonBase = basejson.ToObject<LessonBase>();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},base.json转换异常,{ex.Message}{ex.StackTrace}{basejson},{lessonRecord.id}", GroupNames.成都开发測試群組);
- //lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
- }
- //await _dingDing.SendBotMsg($"课例记录文件base.json:{lessonBase.ToJsonString()}", GroupNames.成都开发測試群組);
- if (lessonBase != null && lessonBase.summary != null)
- {
- var baseData =LessonETLService. GetBaseData(lessonBase!);
- studentLessonDatas= baseData.studentLessonDatas;
- //lessonRecord.name = lessonBase.summary.activityName;
- lessonRecord.attendCount = lessonBase.summary.attendCount;
- lessonRecord.clientCount = lessonBase.summary.clientCount;
- lessonRecord.attendRate = lessonBase.summary.attendRate;
- lessonRecord.groupCount = lessonBase.summary.groupCount;
- lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
- lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount + lessonRecord.hitaClientCmpCount;
- lessonRecord.collateCount = lessonBase.summary.collateCount;
- lessonRecord.pushCount = lessonBase.summary.pushCount;
- lessonRecord.totalPoint = lessonBase.summary.totalPoint;
- lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
- lessonRecord.interactionCount = lessonBase.summary.interactionCount;
- lessonRecord.examPointRate = lessonBase.summary.examPointRate;
- lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
- lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
- lessonRecord.examCount = lessonBase.summary.examCount;
- lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
- lessonRecord.learningCategory = lessonBase.summary.learningCategory;
- if (lessonRecord.learningCategory == null)
- {
- lessonRecord.learningCategory = new LearningCategory();
- }
- if (lessonRecord.hitaClientCmpCount > 0)
- {
- lessonRecord.learningCategory.cooperation = 1;
- }
- if (!string.IsNullOrWhiteSpace(lessonRecord.school))
- {
- lessonBase.student.ForEach(x =>
- {
- if (string.IsNullOrWhiteSpace(x.school))
- {
- x.school = lessonRecord.school;
- }
- });
- }
- //计算TP灯
- {
- int T = -1;
- int P = -1;
- if (lessonRecord.clientInteractionAverge <= 0)
- {
- T = 0;
- }
- else if (lessonRecord.clientInteractionAverge > 0 && lessonRecord.clientInteractionAverge < 2)
- // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
- {
- T = 1;
- }
- else
- {
- T = 2;
- }
- //if (lessonRecord.examCount > 0)
- //{
- // //有评测次数大于0则P是直接绿灯
- // P = 2;
- //}
- //else {
- //}
- int a = lessonRecord.hitaClientCmpCount;
- int b = lessonRecord.pushCount;
- int c = lessonRecord.examCount;
- switch (true)
- {
- case bool when T == 0:
- P = 0;
- break;
- case bool when T == 1 || T == 2:
- if (a == 0 && b == 0 && c == 0)
- {
- P = 0;
- }
- else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
- {
- P = 2;
- }
- else
- {
- P = 1;
- }
- break;
- }
- lessonRecord.tLevel = T;
- lessonRecord.pLevel = P;
- }
- //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
- //{
- // clientSummaryList = lessonBase.report.clientSummaryList,
- // students = lessonBase.student,
- // name = lessonRecord.name,
- // school = lessonRecord.school,
- // id = lessonRecord.id,
- // scope = lessonRecord.scope,
- // tmdid = lessonRecord.tmdid,
- // code = "LessonStudentRecord",
- // pk = "LessonStudentRecord",
- // courseId =lessonRecord.courseId,
- // groupIds= lessonRecord.groupIds,
- // periodId = lessonRecord.periodId,
- // subjectId = lessonRecord.subjectId,
- //};
- //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
- }
- //有上传 base.josn.
- lessonRecord.upload = 1;
- // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
- LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, _coreAPIHttpService, _dingDing, _azureRedis);
- long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
- Bloblog bloblog = new Bloblog
- {
- id = lessonRecord.id,
- code = $"Bloblog-{blobname}",
- name = lessonRecord.name,
- pk = "Bloblog",
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- type = "records",
- url = $"records/{_lessonId}",
- subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
- periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
- size = size.HasValue ? size.Value : 0,
- };
- await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
- msgs.Add(update);
- List<ExamData> examDatas = new List<ExamData>();
- if (lessonBase!=null && lessonBase.student!=null)
- {
- string owner = lessonRecord.scope.Equals("school") ? lessonRecord.school : lessonRecord.tmdid;
- examDatas = await LessonETLService.GetExamInfo(lessonRecord, timeLineData, _azureStorage, owner);
- sokratesDatas= sokratesDatas.IsNotEmpty() ? sokratesDatas : timeLineData!=null ? timeLineData.events : new List<TimeLineEvent>();
- }
- LessonLocal lessonLocal = new LessonLocal()
- {
- lessonBase=lessonBase,
- timeLineData= timeLineData,
- lessonRecord= lessonRecord,
- taskDatas= taskDatas,
- smartRatingDatas= smartRatingDatas,
- irsDatas= irsDatas,
- coworkDatas= coworkDatas,
- examDatas=examDatas,
- sokratesDatas= sokratesDatas,
- studentLessonDatas=studentLessonDatas
- };
- try {
- if (lessonRecord.duration>0)
- {
- var location = Environment.GetEnvironmentVariable("Option:Location");
- if (location.Equals("China", StringComparison.OrdinalIgnoreCase))
- {
- List<School> schools = new List<School>();
- List<StudentSemesterRecord> studentSemesterRecords = new List<StudentSemesterRecord>();
- List<OverallEducation> overallEducations = new List<OverallEducation>();
- List<Student> studentsBase = new List<Student>();
- List<StudentSemesterRecord> students = new List<StudentSemesterRecord>();
- LessonDataAnalysisModel lessonDataAnalysis = null;
- bool exists = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient($"/lesson/analysis/analysis-model.json").ExistsAsync();
- if (exists)
- {
- BlobDownloadResult blobDownload = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient($"/lesson/analysis/analysis-model.json").DownloadContentAsync();
- lessonDataAnalysis = blobDownload.Content.ToObjectFromJson<LessonDataAnalysisModel>();
- string studentSql = $"select value c from c where c.id in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))})";
- var studentResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(studentSql, $"Base-{school}");
- if (studentResults.list.IsNotEmpty())
- {
- studentsBase.AddRange(studentResults.list);
- }
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
- schools.Add(schoolBase);
- string? periodId = !string.IsNullOrWhiteSpace(lessonLocal.lessonRecord.periodId) ? lessonLocal.lessonRecord.periodId : schoolBase.period.FirstOrDefault()?.id;
- var period = schoolBase.period.Find(x => x.id.Equals(periodId));
- var semester = SchoolService.GetSemester(period, lessonLocal.lessonRecord.startTime);
- string code = $"StudentSemesterRecord-{schoolBase.id}";
- string studentSemesterRecordSql = $"select value c from c where c.stuid in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))}) and c.semesterId='{semester.currSemester.id}' and c.studyYear={semester.studyYear}";
- var studentSemesterRecordResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<StudentSemesterRecord>(studentSemesterRecordSql, code);
- if (studentSemesterRecordResults.list.IsNotEmpty())
- {
- studentSemesterRecords.AddRange(studentSemesterRecordResults.list);
- }
- string overallEducationSql = $"select value c from c where c.studentId in ({string.Join(",", lessonLocal.studentLessonDatas.Select(x => $"'{x.id}'"))}) and c.semesterId='{semester.currSemester.id}' and c.year={semester.studyYear}";
- var overallEducationResults = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<OverallEducation>(overallEducationSql, $"OverallEducation-{schoolBase.id}");
- if (overallEducationResults.list.IsNotEmpty())
- {
- overallEducations.AddRange(overallEducationResults.list);
- }
- LessonETLService.DoStudentLessonDataV2(Constant.objectiveTypes, lessonLocal, location, studentSemesterRecords, overallEducations, lessonDataAnalysis, studentsBase, schools);
- await Parallel.ForEachAsync(studentSemesterRecords, async (studentSemester, cancellationToken) =>
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(studentSemester, new PartitionKey(studentSemester.code));
- });
- await Parallel.ForEachAsync(overallEducations, async (overallEducation, cancellationToken) =>
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(overallEducation, partitionKey: new PartitionKey(overallEducation.code));
- string key = $"OverallEducation:{overallEducation.schoolCode}:{overallEducation.periodId}:{overallEducation.year}:{overallEducation.semesterId}:{overallEducation?.classId}";
- await _azureRedis.GetRedisClient(8).HashSetAsync(key, overallEducation.studentId, overallEducation.ToJsonString());
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 *24, 0, 0));
- });
- }
- }
- // 使用当前文化设置的日历
- CultureInfo cultureInfo = CultureInfo.CurrentCulture;
- Calendar calendar = cultureInfo.Calendar;
- //表示如果一年的第一个星期至少有4天在同一年,则该星期被视为第一周,DayOfWeek.Monday和DayOfWeek.Sunday分别表示一周的第一天是星期一或星期日。
- var week = calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
- string key = $"LessonWeekly:{lessonRecord.scope}:{DateTime.Now.Year}-{week}";
- _azureRedis.GetRedisClient(8).HashSet(key, $"{lessonRecord.tmdid}:{lessonRecord.id}",
- new LessonWeek
- {
- week=week,
- id = lessonRecord.id,
- cid=lessonRecord.courseId,
- sid= lessonRecord.subjectId,
- school=lessonRecord.school,
- gid= lessonRecord.groupIds?.FirstOrDefault(),
- //pid= lessonRecord.periodId,
- scope= lessonRecord.scope,
- }.ToJsonString()
- );
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, TimeSpan.FromDays(10));
- }
-
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}处理学生课中数据发生异常,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- // DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase, _azureRedis, PickupMemberIds, taskDatas, irsDatas);
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
- break;
- //更新 时间线
- case "up-TimeLine":
- //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
- //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
- msgs.Add(update);
- break;
- //更新 课堂总览信息
- case "up-ActivityInfo":
- //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
- //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
- msgs.Add(update);
- break;
- case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
- isReplace = true;
- msgs.Add(update);
- break;
- case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
- try
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- foreach (var record in records)
- {
- try
- {
- await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- catch (Exception)
- {
- break;
- }
- isReplace = true;
- msgs.Add(update);
- break;
- case "delete":
- try
- {
- if (lessonRecord.expire > 0)
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- foreach (var record in records)
- {
- try
- {
- await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
- await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
- msgs.Add(update);
- }
- catch (CosmosException)
- {
- msgs.Add(update);
- }
- lessonRecord = null;
- isReplace = false;
- break;
- case "create":
- oldlessonRecord = null;
- //处理课堂选用的课程信息
- lessonRecord.show = teacher.lessonShow;
- lessonRecord.upload = 0;
- if (!string.IsNullOrEmpty(lessonRecord.courseId))
- {
- CourseBase course = null;
- try
- {
- var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase-{lessonRecord.school}"));
- if (cresponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cresponse.Content);
- course = cJson.ToObject<CourseBase>();
- }
- else
- {
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase"));
- if (sresponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(sresponse.Content);
- course = cJson.ToObject<CourseBase>();
- }
- else
- {
- course = null;
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- /*catch (CosmosException ex) when (ex.Status != 404)
- {
- try
- {
- course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
- }
- catch (CosmosException e) when (e.Status != 404)
- {
- course = null;
- }
- }*/
- if (course != null)
- {
- lessonRecord.periodId = course.period?.id;
- lessonRecord.subjectId = course.subject?.id;
- }
- }
- //处理课堂选用的名单
- if (lessonRecord.groupIds.IsNotEmpty())
- {
- List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
- if (!string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
- {
- HashSet<string> grades = new HashSet<string>();
- School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
- HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
- groups.ForEach(y =>
- {
- if (y.type.Equals("teach") || y.type.Equals("class"))
- {
- gd.Add(y.year);
- }
- });
- var gpdata = SchoolService.GetGrades(schoolObj, lessonRecord.periodId, gd);
- lessonRecord.grade = gpdata.grades.ToList();
- }
- }
- try
- {
- if (scope.Equals("school"))
- {
- School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
- {
- await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
- { client = "hiteach", count = 1, id = schoolBase.id, key = "lesson-create", name = schoolBase.name, scope = "school", target = schoolBase.id });
- await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
- { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
- }
- var space = await BlobService.GetSurplusSpace(school, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
- SchoolSetting setting = null;
- ResponseMessage schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
- if (schoolSetting.StatusCode == System.Net.HttpStatusCode.OK)
- {
- setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
- if (setting.lessonSetting != null)
- {
- //两种状态都不属于,则默认未开启。
- if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
- {
- setting.lessonSetting.openAutoClean = 0;
- setting.lessonSetting.expireDays = Constant.school_lesson_expire;
- }
- else
- {
- //属于 要么开启1,要么关闭0
- }
- }
- else
- {
- setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
- }
- }
- else
- {
- setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
- }
- int school_lesson_expire = 0;
- bool save = true;
- if (space.surplus > 0)
- {
- save = true;
- }
- else
- {
- save = false;
- school_lesson_expire = Constant.school_lesson_expire;
- }
- if (!save && school_lesson_expire > 0)
- {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = school_lesson_expire * 24 * 60 * 60;
- }
- lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
- // result.Add(school_lesson_expire, lessonRecord.expire);
- string biz = "expire";
- string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
- Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-school_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdid", teacher.id }, { "tmdname", teacher.name }, { "schoolName", schoolBase.name },
- { "schoolId", $"{school}" },{ "lessonId",lessonRecord.id }, { "expireTime", expireTime },{ "lessonName",lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var servicebus_message = new ServiceBusMessage(new
- {
- id = lessonRecord.id,
- progress = item.Key,
- code = lessonRecord.code,
- scope = lessonRecord.scope,
- school = lessonRecord.school,
- opt = "delete",
- expire = lessonRecord.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecord.name,
- startTime = lessonRecord.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecord.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = servicebus_message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- }
- }
- //个人课例保存规则
- if (scope.Equals("private"))
- {
- int lessonLimit = teacher.lessonLimit;
- var space = await BlobService.GetSurplusSpace(tmdid, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
- //20230208调整之前 if (blobTotal * 1073741824 - blobsize > 2147483648) //剩余空间大于2G
- //剩余空间不足,则开启自动清理机制
- if (space.surplus > 0)
- {
- //大于0则表示空间充足
- lessonLimit = -1;
- }
- else
- {
- //20230208调整增加逻辑,之前lessonLimit用于处理默认保存50条,现在用于处理标记是否空间不足,不足则标记清理。
- if ($"{Environment.GetEnvironmentVariable("Option:Location")}".Contains("Test", StringComparison.OrdinalIgnoreCase))
- {
- lessonLimit = 0;
- }
- else
- {
- lessonLimit = -1;
- }
- }
- if (lessonLimit != -1)
- {
- #region 20230208 调整之后
- {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
- }
- //将当前课例标记为 自动清理
- lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
- string biz = "expire";
- string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecord.id }, { "lessonName", lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var servicebus_message = new ServiceBusMessage(new
- {
- id = lessonRecord.id,
- progress = item.Key,
- code = lessonRecord.code,
- scope = lessonRecord.scope,
- school = lessonRecord.school,
- opt = "delete",
- expire = lessonRecord.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecord.name,
- startTime = lessonRecord.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- servicebus_message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), servicebus_message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecord.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = servicebus_message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
- }
- #endregion 20230208 调整之后
- #region 20230208 调整之前
- /** 20230208 调整之前
- HashSet<string> ids = new HashSet<string>();
- //未定义的 以及过期时间小于等于0 的 课例
- string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
- queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
- {
- ids.Add(item);
- }
- // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
- //包含收藏的本人的个人课例
- //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
- //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
- // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
- //{
- // ids.Add(item);
- //}
- //教师个人预设的,可以通过设置的方式增加
- int limit = teacher.lessonLimit;
- if (teacher.lessonLimit == 0)
- {
- //未设置的的采用系统设置的默认值50
- limit = Constant.private_lesson_limit;
- }
- if (ids.Count >= limit)
- {
- LessonRecord lessonRecordExpire = null;
- //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
- //220712 讨论,将desc去掉,获取最旧的那一笔数据。删除最旧的
- string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
- $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' and c.status<>404 order by c.startTime ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<LessonRecord>(
- queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
- {
- lessonRecordExpire = item; break;
- }
- if (lessonRecordExpire != null)
- {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
- }
- lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
- result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
- string biz = "expire";
- string expireTime= DateTimeOffset.FromUnixTimeMilliseconds(lessonRecordExpire.expire).ToString("yyyy-MM-dd HH:mm:ss");
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecordExpire.id }, { "lessonName", lessonRecordExpire. name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var message = new ServiceBusMessage(new
- {
- id = lessonRecordExpire.id,
- progress = item.Key,
- code = lessonRecordExpire.code,
- scope = lessonRecordExpire.scope,
- school = lessonRecordExpire.school,
- opt = "delete",
- expire = lessonRecordExpire.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecordExpire.name,
- startTime = lessonRecordExpire.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecordExpire.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
- }
- }**/
- #endregion 20230208 调整之前
- }
- else
- {
- //=-1 则表示不限制上传数量
- }
- await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate
- { client = "hiteach", count = 1, id = lessonRecord.tmdid, key = "lesson-create", name = "课例", scope = "teacher", target = lessonRecord.tmdid });
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- msgs.Add(update);
- await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 1, 0);//BI统计增/减量
- break;
- default:
- break;
- }
- }
- //如果被删除则不能再被更新
- if (isReplace)
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
- }
- //计算课堂更新前后的差值
- lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
- await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
- }
- });
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错IESServiceBusTrigger\n{ex.Message}{ex.StackTrace}{data}{code}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("LessonRecordExpire")]
- public async Task LessonRecordExpireFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%","lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
- try
- {
- jsonMsg.TryGetProperty("id", out JsonElement id);
- jsonMsg.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.TryGetProperty("code", out JsonElement _code);
- jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
- jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
- jsonMsg.TryGetProperty("name", out JsonElement name);
- jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
- jsonMsg.TryGetProperty("expire", out JsonElement expire);
- jsonMsg.TryGetProperty("scope", out JsonElement scope);
- jsonMsg.TryGetProperty("school", out JsonElement _school);
- jsonMsg.TryGetProperty("tag", out JsonElement _tag);
- var client = _azureCosmos.GetCosmosClient();
- //处理到期删除
- if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
- {
- string lessonId = $"{id}";
- string tbname;
- string school = $"{_school}";
- string code = "";
- if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
- {
- code = $"LessonRecord-{school}";
- tbname = "School";
- }
- else if ($"{scope}".Equals("private"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return;
- }
- ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- LessonRecord lessonRecord;
- var doc = JsonDocument.Parse(response.Content);
- lessonRecord = doc.RootElement.ToObject<LessonRecord>();
- lessonRecord.status = 404;
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
- $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- }
- string biz = "expire";
- Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
- string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid", tmdid }, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName", name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("Imei")]
- public async Task ImeiFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var json = JsonDocument.Parse(message.Body);
- try
- {
- //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
- if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
- json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
- json.RootElement.TryGetProperty("school", out JsonElement school) &&
- json.RootElement.TryGetProperty("stus", out JsonElement stus))
- {
- json.RootElement.TryGetProperty("imeiType", out JsonElement imeiType);
- var db = _azureCosmos.GetCosmosClient();
- foreach (var stu in stus.EnumerateArray())
- {
- await foreach (var item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIteratorSql(
- queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}' and c.school='{school}' ",
- requestOptions: new() { PartitionKey = new($"Imei") }))
- {
- using var root = await JsonDocument.ParseAsync(item.Content);
- if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var doc = root.RootElement.GetProperty("Documents").EnumerateArray().First();
- var imei = doc.ToObject<Imei>();
- imei.channel = channel.GetString();
- imei.userid = userid.GetString();
- if (!string.IsNullOrWhiteSpace($"{imeiType}"))
- {
- imei.imeiType = $"{imeiType}";
- }
- else
- {
- if (imei.id.Length == 11)
- {
- imei.imeiType = "139zhxy";
- }
- else if (imei.id.Length == 15)
- {
- imei.imeiType = "tianbo";
- }
- }
- await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id);
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF error\n{ex.Message}\n{ex.StackTrace}{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// UseDevelopmentStorage=true
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("BlobRoot")]
- public async Task BlobRoot(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- try
- {
- _backgroundWorkerQueue.QueueBackgroundWorkItem(async task =>
- {
- var jsonMsg = JsonDocument.Parse(message.Body).RootElement.ToObject<BlobRefreshMessage>();
- if (!string.IsNullOrWhiteSpace($"{jsonMsg.root}") && !string.IsNullOrWhiteSpace($"{jsonMsg.name}"))
- {
- string lockKey = $"Blob:Lock:{jsonMsg.name}:{jsonMsg.root}";
- bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
- if (exist)
- {
- string[] uls = System.Web.HttpUtility.UrlDecode($"{jsonMsg.root}", Encoding.UTF8).Split("/");
- string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
- string name = $"{jsonMsg.name}";
- await RefreshBlob(name, u);
- await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
- }
- }
- });
- }
- catch { }
- finally
- {
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// 統測評量開始結束
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("JointExam")]
- public async Task JointExamFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointexam", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var json = JsonDocument.Parse(message.Body);
- try
- {
- json.RootElement.TryGetProperty("id", out JsonElement id);
- json.RootElement.TryGetProperty("progress", out JsonElement progress);
- json.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- JointExam jointExam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<JointExam>(id.ToString(), new PartitionKey($"{code}"));
- jointExam.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(jointExam, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{json.RootElement.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- { // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// 統測活動行程進行狀況更新
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("JointEventSchedule")]
- public async Task JointEventFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointevent-schedule", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions,
- ExecutionContext context)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
- jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
- jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
- jsonMsg.TryGetProperty("progress", out JsonElement progress);
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- try
- {
- //多國語字典
- //string rootPath = _environment.ContentRootPath;
- //List<string> langList = new List<string>() { "en-us", "zh-cn", "zh-tw" };
- //Dictionary<string, JObject> langDic = new Dictionary<string, JObject>();
- //foreach (string langCode in langList)
- //{
- // string path = Path.Combine(rootPath, $"Lang/{langCode}.json");
- // if (File.Exists(path))
- // {
- // string jsonContent = await File.ReadAllTextAsync(path);
- // JObject jsonObject = JObject.Parse(jsonContent);
- // langDic.Add(langCode, jsonObject);
- // }
- //}
- bool updFlg = false;
- string code = "JointEvent";
- var client = _azureCosmos.GetCosmosClient();
- JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<JointEvent>(jointEventId.ToString(), new PartitionKey($"{code}"));
- if (jointEvent != null)
- {
- JointEvent.JointEventSchedule jointEventSchedule = jointEvent.schedule.Where(s => s.id.Equals($"{jointScheduleId}")).FirstOrDefault();
- if (jointEventSchedule != null)
- {
- //DB資料處理
- if (!jointEventSchedule.progress.Equals($"{progress}"))
- {
- jointEventSchedule.progress = $"{progress}";
- updFlg = true;
- }
- if (updFlg)
- {
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(jointEvent, jointEvent.id);
- }
- //訊息處理
- switch (jointEventSchedule.progress)
- {
- case "pending":
- //going訊息寄送
- var msg = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "going" }.ToJsonString());
- msg.ApplicationProperties.Add("name", "JointEventSchedule");
- string PartitionKeyGo = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "going");
- List<ChangeRecord> recordsGo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKeyGo } });
- if (recordsGo.Count > 0)
- {
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordsGo[0].sequenceNumber);
- }
- catch (ServiceBusException e) { }
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
- recordsGo[0].sequenceNumber = start;
- await table.SaveOrUpdate<ChangeRecord>(recordsGo[0]);
- }
- else
- {
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), msg, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.startTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = jointEventSchedule.id,
- PartitionKey = PartitionKeyGo,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- break;
- case "going":
- //pending訊息紀錄刪除
- string pkey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "pending");
- await table.DeleteSingle<ChangeRecord>(pkey, jointEventSchedule.id);
- //發送finish訊息
- var messageEnd = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointScheduleId}", progress = "finish" }.ToJsonString());
- messageEnd.ApplicationProperties.Add("name", "JointEventSchedule");
- string PartitionKeyEnd = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", "finish");
- List<ChangeRecord> recordsEnd = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", $"{jointScheduleId}" }, { "PartitionKey", PartitionKeyEnd } });
- if (recordsEnd.Count > 0)
- {
- long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
- try {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordsEnd[0].sequenceNumber);
- }
- catch (ServiceBusException e) { }
- recordsEnd[0].sequenceNumber = end;
- await table.SaveOrUpdate<ChangeRecord>(recordsEnd[0]);
- }
- else
- {
- long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = jointEventSchedule.id,
- PartitionKey = PartitionKeyEnd,
- sequenceNumber = end,
- msgId = messageEnd.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- //寄發Email
- if(jointEventSchedule.type.Equals("exam"))
- {
- string type = string.Empty;
- string tablePartitionKey = string.Empty;
- string tableRowKey = string.Empty;
- long emitTime = 0;
- //熱身賽
- if (jointEventSchedule.examType.Equals("regular"))
- {
- //熱身賽開始
- type = "regularExamStart";
- emitTime = jointEventSchedule.startTime;
- var messageRegularSt = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
- messageRegularSt.ApplicationProperties.Add("name", "JointMessage");
- tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
- tableRowKey = $"{jointEventSchedule.id}";
- List<ChangeRecord> recordRegularSt = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
- if (recordRegularSt.Count > 0)
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordRegularSt[0].sequenceNumber);
- recordRegularSt[0].sequenceNumber = sr;
- await table.SaveOrUpdate<ChangeRecord>(recordRegularSt[0]);
- }
- else
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = tableRowKey,
- PartitionKey = tablePartitionKey,
- sequenceNumber = sr,
- msgId = messageRegularSt.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- //熱身賽即將結束
- type = "regularExamEndSoon";
- DateTimeOffset dateTimeEnd = DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime);
- dateTimeEnd = dateTimeEnd.AddDays(-1);
- DateTimeOffset emitTimeOffset = new DateTimeOffset(dateTimeEnd.Year, dateTimeEnd.Month, dateTimeEnd.Day, 0, 0, 0, DateTimeOffset.UtcNow.Offset);
- emitTime = emitTimeOffset.ToUnixTimeMilliseconds();
- var messageRegularSo = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
- messageRegularSo.ApplicationProperties.Add("name", "JointMessage");
- tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
- tableRowKey = $"{jointEventSchedule.id}";
- List<ChangeRecord> recordRegularSo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
- if (recordRegularSo.Count > 0)
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordRegularSo[0].sequenceNumber);
- }
- catch (ServiceBusException e) { }
- recordRegularSo[0].sequenceNumber = sr;
- await table.SaveOrUpdate<ChangeRecord>(recordRegularSo[0]);
- }
- else
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageRegularSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = tableRowKey,
- PartitionKey = tablePartitionKey,
- sequenceNumber = sr,
- msgId = messageRegularSt.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- //決賽
- else if(jointEventSchedule.examType.Equals("custom"))
- {
- //決賽開始
- type = "customExamStart";
- emitTime = jointEventSchedule.startTime;
- var messageCustomSt = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
- messageCustomSt.ApplicationProperties.Add("name", "JointMessage");
- tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
- tableRowKey = $"{jointEventSchedule.id}";
- List<ChangeRecord> recordCustomSt = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
- if (recordCustomSt.Count > 0)
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordCustomSt[0].sequenceNumber);
- }
- catch (ServiceBusException e) { }
- recordCustomSt[0].sequenceNumber = sr;
- await table.SaveOrUpdate<ChangeRecord>(recordCustomSt[0]);
- }
- else
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSt, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = tableRowKey,
- PartitionKey = tablePartitionKey,
- sequenceNumber = sr,
- msgId = messageCustomSt.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- //決賽即將結束
- type = "customExamEndSoon";
- DateTimeOffset dateTimeEnd = DateTimeOffset.FromUnixTimeMilliseconds(jointEventSchedule.endTime);
- dateTimeEnd = dateTimeEnd.AddDays(-1);
- DateTimeOffset emitTimeOffset = new DateTimeOffset(dateTimeEnd.Year, dateTimeEnd.Month, dateTimeEnd.Day, 0, 0, 0, DateTimeOffset.UtcNow.Offset);
- emitTime = emitTimeOffset.ToUnixTimeMilliseconds();
- var messageCustomSo = new ServiceBusMessage(new { jointEventId = $"{jointEventId}", jointScheduleId = $"{jointEventSchedule.id}", type = type, time = emitTime }.ToJsonString());
- messageCustomSo.ApplicationProperties.Add("name", "JointMessage");
- tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
- tableRowKey = $"{jointEventSchedule.id}";
- List<ChangeRecord> recordCustomSo = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tableRowKey }, { "PartitionKey", tablePartitionKey } });
- if (recordCustomSo.Count > 0)
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), recordCustomSo[0].sequenceNumber);
- }
- catch (ServiceBusException e) { }
- recordCustomSo[0].sequenceNumber = sr;
- await table.SaveOrUpdate<ChangeRecord>(recordCustomSo[0]);
- }
- else
- {
- long sr = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCustomSo, DateTimeOffset.FromUnixTimeMilliseconds(emitTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = tableRowKey,
- PartitionKey = tablePartitionKey,
- sequenceNumber = sr,
- msgId = messageCustomSo.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- }
- break;
- case "finish":
- //熱身賽結束,生成決賽名單
- if (jointEventSchedule.type.Equals("exam") && jointEventSchedule.examType.Equals("regular"))
- {
- List<string> jointGroupIds = jointEvent.groups.Select(g => g.id).ToList();
- if (jointGroupIds.Count > 0)
- {
- string scope = "private";
- int classCnt = 0;
- foreach (string jointGroupId in jointGroupIds)
- {
- object addResult = await JointService.CreatePassJointCourseBySchedule(client, jointEvent.id, jointGroupId, jointEventSchedule.id, scope, true, classCnt);
- classCnt = Int32.Parse(addResult.GetType().GetProperty("classCnt").GetValue(addResult).ToString());
- }
- }
- }
- break;
- }
- }
- }
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,JointEventScheduleBus()\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- //自身訊息紀錄刪除
- string PartitionKey = string.Format("{0}{1}{2}{3}{4}{5}{6}", "JointEvent", "-", $"{jointEventId}", "-", "schedule", "-", $"{progress}"); //主key: JointEvent-{jointEventId}-schedule-{progress} RowKey: {jointScheduleId}
- await table.DeleteSingle<ChangeRecord>(PartitionKey, $"{jointScheduleId}");
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- /// <summary>
- /// 統測活動訊息寄送
- /// </summary>
- /// <param name="message"></param>
- /// <param name="messageActions"></param>
- /// <returns></returns>
- [Function("JointEventSendMessage")]
- public async Task JointEventSendMessageFunc(
- [ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "jointmessage", Connection = "Azure:ServiceBus:ConnectionString")]
- ServiceBusReceivedMessage message,
- ServiceBusMessageActions messageActions,
- ExecutionContext context)
- {
- _logger.LogInformation("Message ID: {id}", message.MessageId);
- _logger.LogInformation("Message Body: {body}", message.Body);
- _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
- var jsonMsg = JsonDocument.Parse(message.Body).RootElement;
- jsonMsg.TryGetProperty("jointEventId", out JsonElement jointEventId);
- jsonMsg.TryGetProperty("jointScheduleId", out JsonElement jointScheduleId);
- jsonMsg.TryGetProperty("type", out JsonElement type);
- string location = Environment.GetEnvironmentVariable("Option:Location");
- var client = _azureCosmos.GetCosmosClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- string lang = (location.Contains("China")) ? "zh-cn" : "zh-tw";
- long time = (jsonMsg.TryGetProperty("time", out JsonElement _time)) ? _time.GetInt64() : new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
- try
- {
- StringBuilder sqlStr = new StringBuilder($"SELECT DISTINCT c.creatorId, c.creatorName, c.creatorEmail FROM c WHERE c.jointEventId = '{jointEventId}' ");
- string tid = string.Empty;
- switch (type.ToString())
- {
- //熱身賽開始
- case "regularExamStart":
- sqlStr.Append($" AND c.type = 'regular' ");
- tid = (location.Contains("China")) ? "" : "d-ba5d29036f81460c841fadaac7d35b6b"; //熱身賽開始
- break;
- //熱身賽即將結束
- case "regularExamEndSoon":
- sqlStr.Append($" AND c.type = 'regular' ");
- tid = (location.Contains("China")) ? "" : "d-359ec5e40e244aceb4d04f42e52af29d"; //熱身賽即將結束
- break;
- //決賽開始
- case "customExamStart":
- sqlStr.Append($" AND c.type = 'custom' ");
- break;
- //決賽即將結束
- case "customExamEndSoon":
- sqlStr.Append($" AND c.type = 'custom' ");
- break;
- }
- //取得收信者
- List<dynamic> mailUsers = new List<dynamic>();
- await foreach (var jc in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql(queryText: sqlStr.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointCourse") }))
- {
- using var json = await JsonDocument.ParseAsync(jc.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- EmailUser user = new EmailUser();
- user.tmid = (obj.TryGetProperty("creatorId", out JsonElement _creatorId)) ? _creatorId.GetString() : string.Empty;
- user.name = (obj.TryGetProperty("creatorName", out JsonElement _creatorName)) ? _creatorName.GetString() : string.Empty;
- user.email = (obj.TryGetProperty("creatorEmail", out JsonElement _creatorEmail)) ? _creatorEmail.GetString() : string.Empty;
- if (!string.IsNullOrWhiteSpace(user.tmid) && !string.IsNullOrWhiteSpace(user.email))
- {
- mailUsers.Add(user);
- }
- }
- }
- }
- //寄發Email
- if (mailUsers.Count > 0)
- {
- if(location.Contains("-Test")) await _dingDing.SendBotMsg($"寄送活動Email type:{type.ToString()} 寄送人數:{mailUsers.Count}人", GroupNames.研發C組);
- //熱身賽開始 Mail發送
- foreach (dynamic user in mailUsers)
- {
- if (!string.IsNullOrWhiteSpace(tid)) //※無模板ID不發
- {
- await _coreAPIHttpService.SendMail(new Dictionary<string, object> { { "to", user.email }, { "tid", tid }, { "vars", new { name = user.name } } }, location, _configuration);
- }
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")} 統測活動Email寄送錯誤:\n{ex.Message}\n{ex.StackTrace}\n\n{jsonMsg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- //自身訊息紀錄刪除
- string tablePartitionKey = string.Format("{0}{1}{2}{3}{4}", "JointMessage", "-", $"{jointEventId}", "-", $"{type}"); //主key: JointMessage-{jointEventId}-{type} RowKey: {jointScheduleId}
- string tableRowKey = $"{jointScheduleId}";
- await table.DeleteSingle<ChangeRecord>(tablePartitionKey, tableRowKey);
- // Complete the message
- await messageActions.CompleteMessageAsync(message);
- }
- }
- private async Task RefreshBlob(string name, string u)
- {
- long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var client = _azureStorage.GetBlobContainerClient(name);
- var size = await client.GetBlobsSize(u);
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
- var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
- double blobsize = 0;
- if (scores != default && scores != null)
- {
- foreach (var score in scores)
- {
- blobsize = blobsize + score.Score;
- }
- }
- if (blobsize > 0)
- {
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
- }
- long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- long dis = (end - statr) / 1000;
- long timeout = 60 * 5;
- if (dis > timeout)
- {
- await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
- }
- //await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}\n文件夹大小:{blobsize}", GroupNames.醍摩豆服務運維群組);
- }
- private class EmailUser
- {
- public string tmid { get; set; }
- public string name { get; set; }
- public string email { get; set; }
- }
- }
- }
|