ActiveTaskTopic.cs 110 KB

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