IESServiceBusTrigger.cs 175 KB

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