ActiveTaskTopic.cs 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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. namespace TEAMModelOS.FunctionV4.ServiceBus
  29. {
  30. public class ActiveTaskTopic
  31. {
  32. private readonly AzureCosmosFactory _azureCosmos;
  33. private readonly DingDing _dingDing;
  34. private readonly AzureStorageFactory _azureStorage;
  35. private readonly AzureRedisFactory _azureRedis;
  36. private readonly AzureServiceBusFactory _serviceBus;
  37. private readonly Option _option;
  38. private readonly NotificationService _notificationService;
  39. private readonly CoreAPIHttpService _coreAPIHttpService;
  40. private readonly IConfiguration _configuration;
  41. public ActiveTaskTopic(CoreAPIHttpService coreAPIHttpService,AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
  42. {
  43. _azureCosmos = azureCosmos;
  44. _dingDing = dingDing;
  45. _azureStorage = azureStorage;
  46. _azureRedis = azureRedis;
  47. _serviceBus = serviceBus;
  48. _option = option?.Value;
  49. _notificationService = notificationService;
  50. _configuration = configuration;
  51. _coreAPIHttpService = coreAPIHttpService;
  52. }
  53. [Function("Exam")]
  54. public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  55. {
  56. try
  57. {
  58. var json = JsonDocument.Parse(msg);
  59. json.RootElement.TryGetProperty("id", out JsonElement id);
  60. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  61. json.RootElement.TryGetProperty("code", out JsonElement code);
  62. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  63. var client = _azureCosmos.GetCosmosClient();
  64. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  65. exam.progress = progress.ToString();
  66. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  67. }
  68. catch (CosmosException e)
  69. {
  70. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  71. }
  72. catch (Exception ex)
  73. {
  74. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  75. }
  76. }
  77. [Function("Vote")]
  78. public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  79. {
  80. try
  81. {
  82. var jsonMsg = JsonDocument.Parse(msg);
  83. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  84. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  85. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  86. var client = _azureCosmos.GetCosmosClient();
  87. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  88. vote.progress = progress.ToString();
  89. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  90. }
  91. catch (CosmosException e)
  92. {
  93. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  94. }
  95. catch (Exception ex)
  96. {
  97. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  98. }
  99. }
  100. [Function("Correct")]
  101. public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  102. {
  103. try
  104. {
  105. var jsonMsg = JsonDocument.Parse(msg);
  106. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  107. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  108. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  109. var client = _azureCosmos.GetCosmosClient();
  110. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  111. correct.progress = progress.ToString();
  112. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  113. }
  114. catch (CosmosException e)
  115. {
  116. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  117. }
  118. catch (Exception ex)
  119. {
  120. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  121. }
  122. }
  123. [Function("Survey")]
  124. public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  125. {
  126. try
  127. {
  128. var jsonMsg = JsonDocument.Parse(msg);
  129. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  130. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  131. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  132. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  133. var client = _azureCosmos.GetCosmosClient();
  134. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  135. survey.progress = progress.ToString();
  136. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  137. }
  138. catch (CosmosException e)
  139. {
  140. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  141. }
  142. catch (Exception ex)
  143. {
  144. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  145. }
  146. }
  147. [Function("Homework")]
  148. public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  149. {
  150. try
  151. {
  152. var jsonMsg = JsonDocument.Parse(msg);
  153. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  154. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  155. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  156. var client = _azureCosmos.GetCosmosClient();
  157. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  158. homework.progress = progress.ToString();
  159. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  160. }
  161. catch (CosmosException e)
  162. {
  163. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.StackTrace}{e.Message}{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  164. }
  165. catch (Exception ex)
  166. {
  167. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  168. }
  169. }
  170. [Function("Study")]
  171. public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  172. {
  173. string activityId = string.Empty;
  174. try
  175. {
  176. var jsonMsg = JsonDocument.Parse(msg);
  177. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  178. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  179. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  180. var client = _azureCosmos.GetCosmosClient();
  181. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  182. study.progress = progress.ToString();
  183. activityId = id.ToString();
  184. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  185. }
  186. catch (CosmosException e)
  187. {
  188. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  189. }
  190. catch (Exception ex)
  191. {
  192. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  193. }
  194. }
  195. [Function("ExamLite")]
  196. public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  197. {
  198. try
  199. {
  200. var jsonMsg = JsonDocument.Parse(msg);
  201. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  202. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  203. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  204. var client = _azureCosmos.GetCosmosClient();
  205. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  206. lite.progress = progress.ToString();
  207. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  208. }
  209. catch (CosmosException e)
  210. {
  211. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  212. }
  213. catch (Exception ex)
  214. {
  215. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  216. }
  217. }
  218. /// <summary>
  219. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  220. /// </summary>
  221. /// <param name="msg"></param>
  222. /// <returns></returns>
  223. [Function("BlobRoot")]
  224. public async Task BlobRootFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  225. {
  226. try
  227. {
  228. var jsonMsg = JsonDocument.Parse(msg);
  229. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  230. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  231. {
  232. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  233. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  234. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  235. string name = $"{_name}";
  236. string lockKey = $"Blob:Lock:{name}:{u}";
  237. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  238. if (!exist)
  239. { ///key不存在则正常进行计算
  240. bool condition = false;
  241. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  242. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  243. //准备处理Blob刷新时间
  244. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  245. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  246. await RefreshBlob(name, u);
  247. //将action 与Redis最新的时间进行比较,如果
  248. var rds = await CheckLockKey(lockKey, action);
  249. condition = rds.condition;
  250. exist = rds.exist;
  251. if (condition || !exist)
  252. {
  253. await RefreshBlob(name, u);
  254. }
  255. //使用 CancellationToken
  256. //while (condition || !exist)
  257. //{
  258. //}
  259. }
  260. else
  261. {
  262. ///key存在则,则刷新key对应的值
  263. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  264. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  265. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  266. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  267. }
  268. }
  269. }
  270. catch (Exception ex)
  271. {
  272. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  273. }
  274. }
  275. private async Task<(bool condition, bool exist)> CheckLockKey(string lockKey, long nowTime)
  276. {
  277. //Redis的最新时间
  278. long newestTime = 0;
  279. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  280. if (value != default && !value.IsNullOrEmpty)
  281. {
  282. JsonElement record = value.ToString().ToObject<JsonElement>();
  283. if (record.TryGetInt64(out newestTime))
  284. {
  285. }
  286. }
  287. //说明key已经不存在
  288. if (newestTime == 0)
  289. {
  290. return (false, true);
  291. }
  292. //说明key存在
  293. else
  294. {
  295. //说明Redis记录了最新的时间戳
  296. if (nowTime != newestTime)
  297. {
  298. return (true, false);
  299. }
  300. //时间相同,没有被再次记录最新的时间戳
  301. else
  302. {
  303. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  304. return (false, true);
  305. }
  306. }
  307. }
  308. private async Task RefreshBlob(string name, string u)
  309. {
  310. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  311. var client = _azureStorage.GetBlobContainerClient(name);
  312. var size = await client.GetBlobsSize(u);
  313. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  314. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  315. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  316. double blobsize = 0;
  317. if (scores != default && scores != null)
  318. {
  319. foreach (var score in scores)
  320. {
  321. blobsize = blobsize + score.Score;
  322. }
  323. }
  324. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  325. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  326. long dis = (end - statr) / 1000;
  327. long timeout = 60*5;
  328. if (dis > timeout)
  329. {
  330. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  331. }
  332. }
  333. /// <param name="msg"></param>
  334. /// <returns></returns>
  335. [Function("TeacherTrainChange")]
  336. public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  337. {
  338. }
  339. /// <param name="msg"></param>
  340. /// <returns></returns>
  341. //[Function("TeacherTrainChange")]
  342. public async Task TeacherTrainChangeFuncBak([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  343. {
  344. try
  345. {
  346. TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
  347. if (change.update == null || change.update.Count <= 0 || change.tmdids.IsEmpty())
  348. {
  349. return;
  350. }
  351. var client = _azureCosmos.GetCosmosClient();
  352. string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
  353. string selsql = $"select value(c) from c {insql} ";
  354. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  355. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
  356. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
  357. {
  358. teacherTrains.Add(item);
  359. }
  360. if (change.statistics != 1)
  361. {
  362. List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
  363. teacherTrains.ForEach(x =>
  364. {
  365. x.update.UnionWith(change.update);
  366. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
  367. });
  368. await task.TaskPage(5);
  369. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  370. if (unchange != null)
  371. {
  372. task.Clear();
  373. unchange.ToList().ForEach(x =>
  374. {
  375. TeacherTrain teacherTrain = new TeacherTrain
  376. {
  377. pk = "TeacherTrain",
  378. id = x,
  379. code = $"TeacherTrain-{change.school}",
  380. tmdid = x,
  381. school = change.school,
  382. update = new HashSet<string> { StatisticsService.TeacherAbility,
  383. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  384. };
  385. teacherTrain.update.UnionWith(change.update);
  386. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
  387. });
  388. await task.TaskPage(1);
  389. }
  390. }
  391. else
  392. {
  393. Area area = null;
  394. string sql = $"select value(c) from c where c.standard='{change.standard}'";
  395. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
  396. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  397. {
  398. area = item;
  399. }
  400. AreaSetting setting = null;
  401. if (area != null)
  402. {
  403. try
  404. {
  405. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  406. }
  407. catch (CosmosException)
  408. {
  409. try
  410. {
  411. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  412. }
  413. catch (CosmosException)
  414. {
  415. setting = null;
  416. }
  417. }
  418. }
  419. if (setting == null)
  420. {
  421. setting = new AreaSetting
  422. {
  423. allTime = 50,
  424. classTime = 5,
  425. submitTime = 15,
  426. onlineTime = 20,
  427. offlineTime = 10,
  428. lessonMinutes = 45,
  429. };
  430. }
  431. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  432. teacherTrains.ForEach(x =>
  433. {
  434. x.update.UnionWith(change.update);
  435. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  436. });
  437. await task.TaskPage(1);
  438. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  439. if (unchange != null)
  440. {
  441. task.Clear();
  442. unchange.ToList().ForEach(x =>
  443. {
  444. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  445. {
  446. pk = "TeacherTrain",
  447. id = x,
  448. code = $"TeacherTrain-{change.school}",
  449. tmdid = x,
  450. school = change.school,
  451. update = new HashSet<string> { StatisticsService.TeacherAbility,
  452. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  453. }, setting, area, client, null));
  454. });
  455. await task.TaskPage(1);
  456. }
  457. }
  458. }
  459. catch (CosmosException ex)
  460. {
  461. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}CosmosException{ex.Status}", GroupNames.醍摩豆服務運維群組);
  462. }
  463. catch (Exception ex)
  464. {
  465. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  466. }
  467. }
  468. /// <summary>
  469. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  470. /// </summary>
  471. /// <data msg>
  472. /// CourseChange
  473. ///// </data>
  474. /// <param name="msg"></param>
  475. /// <returns></returns>
  476. [Function("GroupChange")]
  477. public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  478. {
  479. var client = _azureCosmos.GetCosmosClient();
  480. try
  481. {
  482. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.醍摩豆服務運維群組);
  483. var jsonMsg = JsonDocument.Parse(msg);
  484. GroupChange groupChange = msg.ToObject<GroupChange>();
  485. //名单变动修改学生课程关联信息
  486. //await StuListService.FixStuCourse(client, stuListChange);
  487. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  488. //名单变动修改学生问卷关联信息
  489. await ActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
  490. //名单变动修改学生投票关联信息
  491. await ActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
  492. //名单变动修改学生评测关联信息
  493. await ActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
  494. //名单变动修改学生研修关联信息
  495. await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  496. //名单变动修改学生简易评测关联信息
  497. await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  498. //名单变动修改学生作业活动信息
  499. await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  500. //TODO学习活动
  501. //await FixActivity(client, stuListChange, "Learn");
  502. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  503. {
  504. //课程名单变动修改学生课程关联信息
  505. await ActivityService.FixStuCourse(client, _dingDing, groupChange);
  506. //名单变动修改课例关联信息
  507. //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
  508. }
  509. }
  510. catch (Exception ex)
  511. {
  512. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange-GroupChange\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  513. }
  514. }
  515. [Function("ItemCond")]
  516. public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  517. {
  518. try
  519. {
  520. var client = _azureCosmos.GetCosmosClient();
  521. var jsonMsg = JsonDocument.Parse(msg);
  522. List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
  523. foreach (var itemCondDto in itemCondDtos)
  524. {
  525. if (itemCondDto.scope.Equals("school"))
  526. {
  527. ItemCond itemCond = null;
  528. List<ItemInfo> items = new List<ItemInfo>();
  529. 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 ";
  530. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
  531. {
  532. items.Add(item);
  533. }
  534. itemCond = new ItemCond()
  535. {
  536. id = $"{itemCondDto.filed}",
  537. code = $"ItemCond-{itemCondDto.key}",
  538. pk = "ItemCond",
  539. ttl = -1,
  540. count = items.Count,
  541. grades = new List<GradeCount>(),
  542. subjects = new List<SubjectItemCount>()
  543. };
  544. items.ForEach(z =>
  545. {
  546. if (!string.IsNullOrEmpty(z.type))
  547. {
  548. ItemService.CountItemCond(z, null, itemCond);
  549. }
  550. });
  551. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
  552. }
  553. else
  554. {
  555. ItemCond itemCond = null;
  556. List<ItemInfo> items = new List<ItemInfo>();
  557. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
  558. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
  559. {
  560. items.Add(item);
  561. }
  562. itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
  563. items.ForEach(z =>
  564. {
  565. if (!string.IsNullOrEmpty(z.type))
  566. {
  567. ItemService.CountItemCond(z, null, itemCond);
  568. }
  569. });
  570. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
  571. }
  572. }
  573. }
  574. catch (CosmosException ex)
  575. {
  576. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  577. }
  578. catch (Exception ex)
  579. {
  580. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  581. }
  582. }
  583. //更新學校產品一覽表
  584. //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
  585. [Function("Product")]
  586. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  587. {
  588. try
  589. {
  590. var jsonMsg = JsonDocument.Parse(msg);
  591. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  592. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  593. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  594. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  595. var client = _azureCosmos.GetCosmosClient();
  596. string strQuery = string.Empty;
  597. //取得所有學校產品
  598. ////序號
  599. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  600. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  601. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  602. {
  603. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  604. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  605. {
  606. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  607. {
  608. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  609. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  610. if (serialProd == null)
  611. {
  612. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  613. serialProdAdd.prodCode = serialInfo.prodCode;
  614. serialProdAdd.ids.Add(serialInfo.id);
  615. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  616. serialsProductSumOrg.Add(serialProdAdd);
  617. }
  618. else
  619. {
  620. if (!serialProd.ids.Contains(serialInfo.id))
  621. {
  622. serialProd.ids.Add(serialInfo.id);
  623. }
  624. serialProd.avaliable = serialProd.ids.Count;
  625. }
  626. }
  627. }
  628. }
  629. ////服務
  630. List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
  631. //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
  632. long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  633. string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
  634. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  635. {
  636. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  637. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  638. {
  639. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  640. {
  641. SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
  642. SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
  643. if (serviceProd == null)
  644. {
  645. SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
  646. serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
  647. serviceProdAdd.avaliable = 0;
  648. serviceProdAdd.ids.Add(servicePeriodInfo.id);
  649. serviceProdAdd.avaliable += servicePeriodInfo.number;
  650. serviceProdAdd.startDate = servicePeriodInfo.startDate;
  651. serviceProdAdd.endDate = servicePeriodInfo.endDate;
  652. servicesProductSumOrg.Add(serviceProdAdd);
  653. }
  654. else
  655. {
  656. serviceProd.ids = new List<string>();
  657. serviceProd.ids.Add(servicePeriodInfo.id);
  658. serviceProd.startDate = servicePeriodInfo.startDate;
  659. serviceProd.endDate = servicePeriodInfo.endDate;
  660. }
  661. }
  662. }
  663. }
  664. ////服務產品特別對應項
  665. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  666. bool updSchool = false; //是否變更學校基本資料
  667. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  668. int schoolDefaultSize = 1; //學校空間初始值:1
  669. if (!string.IsNullOrWhiteSpace(school.id))
  670. {
  671. if (servicesProductSumOrg.Count > 0)
  672. {
  673. foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
  674. {
  675. //更新學校空間
  676. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  677. {
  678. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  679. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  680. updSchool = true;
  681. chgSchSizeCnt++;
  682. }
  683. }
  684. }
  685. if(chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  686. {
  687. school.size = schoolDefaultSize;
  688. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  689. updSchool = false;
  690. }
  691. }
  692. //變更學校基本資料
  693. if(updSchool)
  694. {
  695. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  696. }
  697. ////硬體
  698. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  699. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  700. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  701. {
  702. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  703. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  704. {
  705. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  706. {
  707. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  708. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  709. if (hardProd == null)
  710. {
  711. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  712. hardProdAdd.prodCode = hardInfo.prodCode;
  713. hardProdAdd.model = hardInfo.model;
  714. hardProdAdd.ids.Add(hardInfo.id);
  715. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  716. hardsProductSumOrg.Add(hardProdAdd);
  717. }
  718. else
  719. {
  720. if (!hardProd.ids.Contains(hardInfo.id))
  721. {
  722. hardProd.ids.Add(hardInfo.id);
  723. }
  724. hardProd.avaliable = hardProd.ids.Count;
  725. }
  726. }
  727. }
  728. }
  729. //更新學校產品一覽表
  730. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  731. prodSum.serial = serialsProductSumOrg;
  732. prodSum.service = servicesProductSumOrg;
  733. prodSum.hard = hardsProductSumOrg;
  734. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  735. }
  736. catch (CosmosException ex)
  737. {
  738. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  739. }
  740. catch (Exception ex)
  741. {
  742. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  743. }
  744. }
  745. /// <summary>
  746. /// 批量复制文件
  747. /// </summary>
  748. /// <param name="msg"></param>
  749. /// <returns></returns>
  750. [Function("CopyStandardFile")]
  751. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  752. {
  753. try
  754. {
  755. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
  756. var jsonMsg = JsonDocument.Parse(msg);
  757. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  758. //批量复制文件
  759. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  760. if (result == 200)
  761. {
  762. //发送消息实体
  763. Notification notification = new Notification
  764. {
  765. hubName = "hita",
  766. type = "msg",
  767. from = $"BI:{_option.Location}:private",
  768. to = bIBatchCopyFile.tmdIds,
  769. label = $"{bIBatchCopyFile.codeKey}_finish",
  770. body = new { location = $"{Environment.GetEnvironmentVariable("Option:Location")}", biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  771. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  772. };
  773. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  774. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  775. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  776. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  777. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  778. }
  779. }
  780. catch (Exception ex)
  781. {
  782. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  783. }
  784. }
  785. /// <summary>
  786. /// 更新开课数据事件
  787. /// </summary>
  788. /// <param name="msg"></param>
  789. /// <returns></returns>
  790. [Function("LessonRecordEvent")]
  791. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  792. {
  793. JsonElement data = msg.ToObject<JsonElement>();
  794. string scope = "";
  795. string tmdid = "";
  796. string lessonId;
  797. string school;
  798. string tbname;
  799. string code;
  800. string blobname;
  801. List<LessonUpdate> updates = new List<LessonUpdate>();
  802. //更新课堂记录
  803. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  804. {
  805. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  806. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  807. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  808. data.TryGetProperty("school", out JsonElement _school);
  809. school = $"{_school}";
  810. scope = $"{_scope}";
  811. tmdid = $"{_tmdid}";
  812. lessonId = $"{_lessonId}";
  813. updates = _grant_types.ToObject<List<LessonUpdate>>();
  814. }//创建课堂记录
  815. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  816. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  817. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  818. {
  819. data.TryGetProperty("school", out JsonElement _school);
  820. school = $"{_school}";
  821. scope = $"{_scope}";
  822. tmdid = $"{_tmdid}";
  823. lessonId = $"{_id}";
  824. updates.Add(new LessonUpdate { grant_type = "create" });
  825. }//删除课堂记录
  826. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  827. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  828. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  829. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  830. {
  831. data.TryGetProperty("school", out JsonElement _dschool);
  832. school = $"{_dschool}";
  833. if ($"{_opt}".Equals("delete"))
  834. {
  835. scope = $"{_dscope}";
  836. tmdid = $"{_dtmdid}";
  837. lessonId = $"{_delete_id}";
  838. updates.Add(new LessonUpdate { grant_type = "delete" });
  839. }
  840. else { return; }
  841. }
  842. else
  843. {
  844. return;
  845. }
  846. var client = _azureCosmos.GetCosmosClient();
  847. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  848. {
  849. blobname = $"{school}";
  850. code = $"LessonRecord-{school}";
  851. tbname = "School";
  852. }
  853. else if ($"{scope}".Equals("private"))
  854. {
  855. blobname = $"{tmdid}";
  856. code = $"LessonRecord";
  857. tbname = "Teacher";
  858. }
  859. else
  860. {
  861. return;
  862. }
  863. LessonDis lessonDis = new LessonDis();
  864. List<LessonUpdate> msgs = new List<LessonUpdate>();
  865. try
  866. {
  867. LessonRecord oldlessonRecord = null;
  868. LessonRecord lessonRecord = null;
  869. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  870. if (response.Status == 200)
  871. {
  872. var doc = JsonDocument.Parse(response.ContentStream);
  873. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  874. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  875. }
  876. else
  877. {
  878. lessonRecord = null;
  879. }
  880. bool isReplace = true;
  881. if (updates.IsNotEmpty())
  882. {
  883. foreach (LessonUpdate update in updates)
  884. {
  885. switch (update.grant_type)
  886. {
  887. //更新课堂时长
  888. case "up-duration":
  889. var duration = double.Parse($"{update.data}");
  890. lessonRecord.duration = duration;
  891. msgs.Add(update);
  892. try {
  893. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  894. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  895. if (RecordingJson.TryGetProperty("duration",out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number)) {
  896. var durationFile = double.Parse($"{_duration}");
  897. if (duration < durationFile) {
  898. lessonRecord.duration = durationFile;
  899. }
  900. }
  901. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) &&!string.IsNullOrWhiteSpace($"{_streamUrl}"))
  902. {
  903. lessonRecord.hasVideo = 1;
  904. }
  905. }
  906. catch (Exception ex ) {
  907. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  908. }
  909. isReplace = true;
  910. break;
  911. //更新T分
  912. case "up-tScore":
  913. var tScore = int.Parse($"{update.data}");
  914. lessonRecord.tScore = tScore;
  915. msgs.Add(update);
  916. break;
  917. //更新课P分
  918. case "up-pScore":
  919. var pScore = int.Parse($"{update.data}");
  920. lessonRecord.pScore = pScore;
  921. msgs.Add(update);
  922. break;
  923. //更新 学生人数
  924. case "up-mCount":
  925. var mCount = int.Parse($"{update.data}");
  926. lessonRecord.mCount = mCount;
  927. msgs.Add(update);
  928. break;
  929. //更新 议课次数
  930. case "up-techCount":
  931. var techCount = int.Parse($"{update.data}");
  932. lessonRecord.mCount = techCount;
  933. msgs.Add(update);
  934. break;
  935. //更新 基础统计信息
  936. case "up-base":
  937. //如果有更新 则去读取/{_lessonId}/IES/base.json
  938. try
  939. {
  940. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  941. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  942. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  943. if (lessonBase != null && lessonBase.summary!=null)
  944. {
  945. //lessonRecord.name = lessonBase.summary.activityName;
  946. lessonRecord.attendCount = lessonBase.summary.attendCount;
  947. lessonRecord.clientCount = lessonBase.summary.clientCount;
  948. lessonRecord.attendRate = lessonBase.summary.attendRate;
  949. lessonRecord.groupCount = lessonBase.summary.groupCount;
  950. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  951. lessonRecord.collateCount = lessonBase.summary.collateCount;
  952. lessonRecord.pushCount = lessonBase.summary.pushCount;
  953. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  954. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  955. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  956. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  957. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  958. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  959. lessonRecord.examCount = lessonBase.summary.examCount;
  960. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  961. }
  962. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  963. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  964. Bloblog bloblog = new Bloblog
  965. {
  966. id = lessonRecord.id,
  967. code = $"Bloblog-{blobname}",
  968. name = lessonRecord.name,
  969. pk = "Bloblog",
  970. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  971. type = "records",
  972. url = $"records/{_lessonId}",
  973. subjectId =string.IsNullOrWhiteSpace(lessonRecord.subjectId)?new List<string>(): new List<string> { lessonRecord.subjectId },
  974. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  975. size = size.HasValue ? size.Value : 0,
  976. };
  977. await client.GetContainer(Constant.TEAMModelOS,tbname).UpsertItemAsync(bloblog);
  978. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  979. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  980. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  981. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  982. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  983. msgs.Add(update);
  984. }
  985. catch (Exception ex)
  986. {
  987. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  988. }
  989. break;
  990. //更新 时间线
  991. case "up-TimeLine":
  992. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  993. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  994. msgs.Add(update);
  995. break;
  996. //更新 课堂总览信息
  997. case "up-ActivityInfo":
  998. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  999. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1000. msgs.Add(update);
  1001. break;
  1002. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1003. isReplace = true;
  1004. msgs.Add(update);
  1005. break;
  1006. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1007. try {
  1008. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1009. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1010. foreach (var record in records)
  1011. {
  1012. try
  1013. {
  1014. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1015. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1016. }
  1017. catch (Exception)
  1018. {
  1019. continue;
  1020. }
  1021. }
  1022. } catch (Exception) {
  1023. break;
  1024. }
  1025. isReplace = true;
  1026. msgs.Add(update);
  1027. break;
  1028. case "delete":
  1029. try
  1030. {
  1031. if (lessonRecord.expire > 0) {
  1032. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1033. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1034. foreach (var record in records)
  1035. {
  1036. try
  1037. {
  1038. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1039. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1040. }
  1041. catch (Exception)
  1042. {
  1043. continue;
  1044. }
  1045. }
  1046. }
  1047. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1048. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id,new PartitionKey ($"Bloblog-{blobname}"));
  1049. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1050. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1051. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1052. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1053. msgs.Add(update);
  1054. }
  1055. catch (CosmosException)
  1056. {
  1057. msgs.Add(update);
  1058. }
  1059. lessonRecord = null;
  1060. isReplace = false;
  1061. break;
  1062. case "create":
  1063. oldlessonRecord = null;
  1064. //处理课堂选用的课程信息
  1065. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  1066. lessonRecord.show = teacher.lessonShow;
  1067. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1068. {
  1069. Course course = null;
  1070. try
  1071. {
  1072. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1073. if (cresponse.Status == 200)
  1074. {
  1075. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1076. course = cJson.ToObject<Course>();
  1077. }
  1078. else
  1079. {
  1080. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1081. if (sresponse.Status == 200)
  1082. {
  1083. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1084. course = cJson.ToObject<Course>();
  1085. }
  1086. else
  1087. {
  1088. course = null;
  1089. }
  1090. }
  1091. }
  1092. catch (Exception ex) {
  1093. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1094. }
  1095. /*catch (CosmosException ex) when (ex.Status != 404)
  1096. {
  1097. try
  1098. {
  1099. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1100. }
  1101. catch (CosmosException e) when (e.Status != 404)
  1102. {
  1103. course = null;
  1104. }
  1105. }*/
  1106. if (course != null)
  1107. {
  1108. lessonRecord.periodId = course.period?.id;
  1109. lessonRecord.subjectId = course.subject?.id;
  1110. }
  1111. }
  1112. //处理课堂选用的名单
  1113. if (lessonRecord.groupIds.IsNotEmpty())
  1114. {
  1115. HashSet<string> grades = new HashSet<string>();
  1116. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1117. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1118. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1119. {
  1120. try
  1121. {
  1122. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1123. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1124. //年级算法
  1125. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1126. int? Count = period?.grades?.Count;
  1127. if (Count.HasValue)
  1128. {
  1129. int Day = DateTimeOffset.UtcNow.Day;
  1130. int Month = DateTimeOffset.UtcNow.Month;
  1131. int Year = DateTimeOffset.UtcNow.Year;
  1132. int start = int.Parse($"{Year}0901");
  1133. var se = period.semesters.Find(x => x.start == 1);
  1134. if (se == null)
  1135. {
  1136. se = period.semesters.First();
  1137. }
  1138. if (se != null)
  1139. {
  1140. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1141. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1142. start = int.Parse($"{Year}{sm}{sd}");
  1143. }
  1144. int curr = int.Parse(DateTimeOffset.UtcNow.ToString("yyyyMMdd"));
  1145. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  1146. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  1147. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  1148. int dis = start - curr;
  1149. foreach (int year in gplist.Select(x => x.year))
  1150. {
  1151. int grade;
  1152. if (dis > 0)
  1153. {
  1154. grade = (Year - year - 1) % Count.Value;
  1155. }
  1156. else
  1157. {
  1158. grade = (Year - year) % Count.Value;
  1159. }
  1160. grades.Add($"{grade}");
  1161. }
  1162. }
  1163. }
  1164. catch (CosmosException ex) when (ex.Status == 404)
  1165. {
  1166. }
  1167. catch (Exception ex) {
  1168. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1169. }
  1170. }
  1171. lessonRecord.grade= grades.ToList();
  1172. }
  1173. //个人课例保存规则
  1174. try {
  1175. if (scope.Equals("private"))
  1176. {
  1177. if (teacher.lessonLimit != -1)
  1178. {
  1179. HashSet<string> ids = new HashSet<string>();
  1180. //未定义的 以及过期时间小于等于0 的 课例
  1181. string private_count_sql = "select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) ";
  1182. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1183. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1184. {
  1185. ids.Add(item);
  1186. }
  1187. //包含收藏的本人的个人课例
  1188. string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.scope='private' ";
  1189. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1190. queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1191. {
  1192. ids.Add(item);
  1193. }
  1194. //教师个人预设的,可以通过设置的方式增加
  1195. int limit = teacher.lessonLimit;
  1196. if (teacher.lessonLimit == 0)
  1197. {
  1198. //未设置的的采用系统设置的默认值50
  1199. limit = Constant.private_lesson_limit;
  1200. }
  1201. if (ids.Count >= limit)
  1202. {
  1203. // 1-时间戳,7-时间戳
  1204. Dictionary<int, long> result = new Dictionary<int, long>();
  1205. //暂定7天
  1206. var now = DateTimeOffset.UtcNow;
  1207. //剩余3天的通知
  1208. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1209. //result.Add(3, day3);
  1210. //剩余1天的通知
  1211. var day1 = now.AddDays(Constant.private_lesson_expire -6).ToUnixTimeMilliseconds();
  1212. result.Add(1, day1);
  1213. //到期通知
  1214. lessonRecord.expire = now.AddDays(Constant.private_lesson_expire).ToUnixTimeMilliseconds();
  1215. result.Add(Constant.private_lesson_expire, lessonRecord.expire);
  1216. string biz = "expire";
  1217. Notification notification = new Notification
  1218. {
  1219. hubName = "hita",
  1220. type = "msg",
  1221. from = $"ies5:{ Environment.GetEnvironmentVariable("Option:Location")}:private",
  1222. to = new List<string> { tmdid },
  1223. label = $"{biz}_lessonRecord",
  1224. body = new {
  1225. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1226. biz = biz,
  1227. tmdid = teacher.id,
  1228. tmdname = teacher.name,
  1229. sid = lessonRecord.id,
  1230. sname = lessonRecord.name,
  1231. stime = lessonRecord.startTime,
  1232. expire = lessonRecord.expire,
  1233. status = 1,
  1234. day = Constant.private_lesson_expire,
  1235. time = now
  1236. }.ToJsonString(),
  1237. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1238. };
  1239. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1240. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1241. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1242. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1243. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1244. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1245. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1246. if (records.Count <= 0)
  1247. {
  1248. foreach (var item in result)
  1249. {
  1250. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  1251. //课堂的id ,
  1252. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1253. var message = new ServiceBusMessage(new
  1254. {
  1255. id = lessonRecord.id,
  1256. progress = item.Key,
  1257. code = lessonRecord.code,
  1258. scope = lessonRecord.scope,
  1259. school = lessonRecord.school,
  1260. opt = "delete",
  1261. expire = lessonRecord.expire,
  1262. tmdid = tmdid,
  1263. tmdname = teacher.name,
  1264. name = lessonRecord.name,
  1265. startTime = lessonRecord.startTime
  1266. }.ToJsonString());
  1267. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1268. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value));
  1269. ChangeRecord changeRecord = new ChangeRecord
  1270. {
  1271. RowKey = lessonRecord.id,
  1272. PartitionKey = PartitionKey,
  1273. sequenceNumber = start,
  1274. msgId = message.MessageId
  1275. };
  1276. await table.Save<ChangeRecord>(changeRecord);
  1277. }
  1278. }
  1279. }
  1280. }
  1281. else
  1282. {
  1283. //=-1 则表示不限制上传数量
  1284. }
  1285. }
  1286. } catch (Exception e) {
  1287. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1288. }
  1289. msgs.Add(update);
  1290. break;
  1291. default:
  1292. break;
  1293. }
  1294. }
  1295. //如果被删除则不能再被更新
  1296. if (isReplace) {
  1297. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1298. }
  1299. //计算课堂更新前后的差值
  1300. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1301. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1302. }
  1303. }
  1304. catch (CosmosException e)
  1305. {
  1306. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1307. }
  1308. catch (Exception ex)
  1309. {
  1310. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1311. }
  1312. }
  1313. [Function("LessonRecordExpire")]
  1314. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1315. {
  1316. try
  1317. {
  1318. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1319. jsonMsg.TryGetProperty("id", out JsonElement id);
  1320. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1321. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1322. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1323. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1324. jsonMsg.TryGetProperty("name", out JsonElement name);
  1325. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1326. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1327. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1328. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1329. var client = _azureCosmos.GetCosmosClient();
  1330. //处理到期删除
  1331. if ($"{progress}".Equals($"{Constant.private_lesson_expire}")) {
  1332. string lessonId = $"{id}";
  1333. string tbname;
  1334. string school=$"{_school}";
  1335. string code = "";
  1336. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1337. {
  1338. code = $"LessonRecord-{school}";
  1339. tbname = "School";
  1340. }
  1341. else if ($"{scope}".Equals("private"))
  1342. {
  1343. code = $"LessonRecord";
  1344. tbname = "Teacher";
  1345. }
  1346. else
  1347. {
  1348. return;
  1349. }
  1350. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1351. if (response.Status == 200)
  1352. {
  1353. LessonRecord lessonRecord;
  1354. var doc = JsonDocument.Parse(response.ContentStream);
  1355. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1356. lessonRecord.status = 404;
  1357. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1358. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1359. var messageChange = new ServiceBusMessage(new { delete_id =lessonId, tmdid =tmdid,scope=scope,opt="delete",school=school}.ToJsonString());
  1360. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1361. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1362. await _dingDing.SendBotMsg($"课例因【{lessonRecord.name}】,【{lessonRecord.id}】时间到期,即将被自动删除,到期时间:" +
  1363. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1364. }
  1365. }
  1366. string biz = "expire";
  1367. Notification notification = new Notification
  1368. {
  1369. hubName = "hita",
  1370. type = "msg",
  1371. from = $"ies5:{_option.Location}:private",
  1372. to = new List<string> { $"{tmdid}" },
  1373. label = $"{biz}_lessonRecord",
  1374. body = new {
  1375. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1376. biz = biz,
  1377. tmdid = $"{tmdid}",
  1378. tmdname = tmdname,
  1379. sid =$"{id}",
  1380. sname = $"{name}",
  1381. stime = long.Parse($"{startTime}"),
  1382. expire = long.Parse($"{expire}"),
  1383. status = 1,
  1384. day = Constant.private_lesson_expire,
  1385. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1386. }.ToJsonString(),
  1387. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1388. };
  1389. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1390. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1391. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1392. var location =$"{Environment.GetEnvironmentVariable("Option:Location")}";
  1393. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1394. }
  1395. catch (Exception ex)
  1396. {
  1397. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  1398. }
  1399. }
  1400. /// <summary>
  1401. /// 完善课程变更
  1402. /// </summary>
  1403. /// <data msg>
  1404. /// CourseChange
  1405. ///// </data>
  1406. /// <param name="msg"></param>
  1407. /// <returns></returns>
  1408. [Function("Course")]
  1409. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1410. {
  1411. var client = _azureCosmos.GetCosmosClient();
  1412. try
  1413. {
  1414. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1415. var jsonMsg = JsonDocument.Parse(msg);
  1416. CourseChange courseChange = msg.ToObject<CourseChange>();
  1417. if (courseChange == null)
  1418. {
  1419. return;
  1420. }
  1421. foreach (var cls in courseChange.addClass)
  1422. {
  1423. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1424. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1425. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1426. foreach (var stu in addStudentsCls)
  1427. {
  1428. try
  1429. {
  1430. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1431. if (!stuCourse.Value.classId.Contains(cls))
  1432. {
  1433. stuCourse.Value.classId.Add(cls);
  1434. }
  1435. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1436. }
  1437. catch (CosmosException ex)
  1438. {
  1439. if (ex.Response.Status == 404)
  1440. {
  1441. var course = new StuCourse
  1442. {
  1443. id = courseChange.id,
  1444. scode = courseChange.code,
  1445. name = courseChange.name,
  1446. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1447. scope = courseChange.scope,
  1448. school = courseChange.school,
  1449. creatorId = courseChange.creatorId,
  1450. classId = new List<string> { cls },
  1451. pk = "StuCourse",
  1452. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1453. };
  1454. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1455. }
  1456. else
  1457. {
  1458. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1459. }
  1460. }
  1461. }
  1462. foreach (var tmd in addTmdidsCls)
  1463. {
  1464. try
  1465. {
  1466. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1467. if (!stuCourse.Value.classId.Contains(cls))
  1468. {
  1469. stuCourse.Value.classId.Add(cls);
  1470. }
  1471. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1472. }
  1473. catch (CosmosException ex)
  1474. {
  1475. if (ex.Response.Status == 404)
  1476. {
  1477. var course = new StuCourse
  1478. {
  1479. id = courseChange.id,
  1480. scode = courseChange.code,
  1481. name = courseChange.name,
  1482. code = $"StuCourse-{tmd.id}",
  1483. scope = courseChange.scope,
  1484. school = courseChange.school,
  1485. creatorId = courseChange.creatorId,
  1486. classId = new List<string> { cls },
  1487. pk = "StuCourse",
  1488. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1489. };
  1490. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1491. }
  1492. else
  1493. {
  1494. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1495. }
  1496. }
  1497. }
  1498. }
  1499. foreach (var list in courseChange.addList)
  1500. {
  1501. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1502. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1503. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1504. foreach (var stu in addStudentsCls)
  1505. {
  1506. try
  1507. {
  1508. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1509. if (!stuCourse.Value.stulist.Contains(list))
  1510. {
  1511. stuCourse.Value.stulist.Add(list);
  1512. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1513. }
  1514. }
  1515. catch (CosmosException ex)
  1516. {
  1517. if (ex.Response.Status == 404)
  1518. {
  1519. var course = new StuCourse
  1520. {
  1521. id = courseChange.id,
  1522. scode = courseChange.code,
  1523. name = courseChange.name,
  1524. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1525. scope = courseChange.scope,
  1526. school = courseChange.school,
  1527. creatorId = courseChange.creatorId,
  1528. stulist = new List<string> { list },
  1529. pk = "StuCourse",
  1530. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1531. };
  1532. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1533. }
  1534. else
  1535. {
  1536. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1537. }
  1538. }
  1539. }
  1540. foreach (var tmd in addTmdidsCls)
  1541. {
  1542. try
  1543. {
  1544. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1545. if (!stuCourse.Value.stulist.Contains(list))
  1546. {
  1547. stuCourse.Value.stulist.Add(list);
  1548. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1549. }
  1550. }
  1551. catch (CosmosException ex)
  1552. {
  1553. if (ex.Response.Status == 404)
  1554. {
  1555. var course = new StuCourse
  1556. {
  1557. id = courseChange.id,
  1558. scode = courseChange.code,
  1559. name = courseChange.name,
  1560. code = $"StuCourse-{tmd.id}",
  1561. scope = courseChange.scope,
  1562. school = courseChange.school,
  1563. creatorId = courseChange.creatorId,
  1564. stulist = new List<string> { list },
  1565. pk = "StuCourse",
  1566. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1567. };
  1568. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1569. }
  1570. else
  1571. {
  1572. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. foreach (var delCls in courseChange.delClass)
  1578. {
  1579. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1580. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1581. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1582. foreach (var stu in delStudentsCls)
  1583. {
  1584. try
  1585. {
  1586. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1587. if (stuCourse.Value.classId.Contains(delCls))
  1588. {
  1589. stuCourse.Value.classId.Remove(delCls);
  1590. }
  1591. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1592. {
  1593. //当两个列表都不存在时则直接删除
  1594. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1595. }
  1596. else
  1597. {
  1598. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1599. }
  1600. }
  1601. catch (CosmosException ex)
  1602. {
  1603. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1604. }
  1605. }
  1606. foreach (var tmd in delTmdidsCls)
  1607. {
  1608. try
  1609. {
  1610. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1611. if (stuCourse.Value.classId.Contains(delCls))
  1612. {
  1613. stuCourse.Value.classId.Remove(delCls);
  1614. }
  1615. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1616. {
  1617. //当两个列表都不存在时则直接删除
  1618. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1619. }
  1620. else
  1621. {
  1622. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1623. }
  1624. }
  1625. catch (CosmosException ex)
  1626. {
  1627. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1628. }
  1629. }
  1630. }
  1631. foreach (var delList in courseChange.delList)
  1632. {
  1633. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1634. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1635. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1636. foreach (var stu in delStudentsCls)
  1637. {
  1638. try
  1639. {
  1640. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1641. if (stuCourse.Value.stulist.Contains(delList))
  1642. {
  1643. stuCourse.Value.stulist.Remove(delList);
  1644. }
  1645. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1646. {
  1647. //当两个列表都不存在时则直接删除
  1648. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1649. }
  1650. else
  1651. {
  1652. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1653. }
  1654. }
  1655. catch (CosmosException ex)
  1656. {
  1657. continue;
  1658. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1659. }
  1660. }
  1661. foreach (var tmd in delTmdidsCls)
  1662. {
  1663. try
  1664. {
  1665. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1666. if (stuCourse.Value.stulist.Contains(delList))
  1667. {
  1668. stuCourse.Value.stulist.Remove(delList);
  1669. }
  1670. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1671. {
  1672. //当两个列表都不存在时则直接删除
  1673. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1674. }
  1675. else
  1676. {
  1677. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1678. }
  1679. }
  1680. catch (CosmosException ex)
  1681. {
  1682. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1683. }
  1684. }
  1685. }
  1686. }
  1687. catch (Exception ex)
  1688. {
  1689. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1690. }
  1691. }
  1692. }
  1693. }