IESServiceBusTrigger.cs 208 KB

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