IESServiceBusTrigger.cs 212 KB

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