ActiveTaskTopic.cs 138 KB

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