IESServiceBusTrigger.cs 204 KB

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