IESServiceBusTrigger.cs 213 KB

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