ActiveTaskTopic.cs 165 KB

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