ActiveTaskTopic.cs 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  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.StackTrace}\n{e.Status}\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\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.StackTrace}\n{e.Status}\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\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.StackTrace}\n{e.Status}\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\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.Message}\n{e.StackTrace}\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\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.Message}\n{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\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.Message}\n{e.StackTrace}\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\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.Message}\n{e.StackTrace}\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\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\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}\nCosmosException{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}\n", 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\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\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\n{msg}", GroupNames.醍摩豆服務運維群組);
  582. }
  583. }
  584. //更新學校產品一覽表
  585. //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
  586. [Function("Product")]
  587. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  588. {
  589. try
  590. {
  591. var jsonMsg = JsonDocument.Parse(msg);
  592. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  593. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  594. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  595. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  596. var client = _azureCosmos.GetCosmosClient();
  597. string strQuery = string.Empty;
  598. //取得所有學校產品
  599. ////序號
  600. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  601. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  602. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  603. {
  604. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  605. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  606. {
  607. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  608. {
  609. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  610. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  611. if (serialProd == null)
  612. {
  613. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  614. serialProdAdd.prodCode = serialInfo.prodCode;
  615. serialProdAdd.ids.Add(serialInfo.id);
  616. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  617. serialsProductSumOrg.Add(serialProdAdd);
  618. }
  619. else
  620. {
  621. if (!serialProd.ids.Contains(serialInfo.id))
  622. {
  623. serialProd.ids.Add(serialInfo.id);
  624. }
  625. serialProd.avaliable = serialProd.ids.Count;
  626. }
  627. }
  628. }
  629. }
  630. ////服務
  631. List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
  632. //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
  633. long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  634. string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
  635. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  636. {
  637. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  638. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  639. {
  640. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  641. {
  642. SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
  643. SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
  644. if (serviceProd == null)
  645. {
  646. SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
  647. serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
  648. serviceProdAdd.avaliable = 0;
  649. serviceProdAdd.ids.Add(servicePeriodInfo.id);
  650. serviceProdAdd.avaliable += servicePeriodInfo.number;
  651. serviceProdAdd.startDate = servicePeriodInfo.startDate;
  652. serviceProdAdd.endDate = servicePeriodInfo.endDate;
  653. servicesProductSumOrg.Add(serviceProdAdd);
  654. }
  655. else
  656. {
  657. serviceProd.ids = new List<string>();
  658. serviceProd.ids.Add(servicePeriodInfo.id);
  659. serviceProd.startDate = servicePeriodInfo.startDate;
  660. serviceProd.endDate = servicePeriodInfo.endDate;
  661. }
  662. }
  663. }
  664. }
  665. ////服務產品特別對應項
  666. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  667. bool updSchool = false; //是否變更學校基本資料
  668. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  669. int schoolDefaultSize = 1; //學校空間初始值:1
  670. if (!string.IsNullOrWhiteSpace(school.id))
  671. {
  672. if (servicesProductSumOrg.Count > 0)
  673. {
  674. foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
  675. {
  676. //更新學校空間
  677. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  678. {
  679. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  680. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  681. updSchool = true;
  682. chgSchSizeCnt++;
  683. }
  684. }
  685. }
  686. if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  687. {
  688. school.size = schoolDefaultSize;
  689. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  690. updSchool = false;
  691. }
  692. }
  693. //變更學校基本資料
  694. if (updSchool)
  695. {
  696. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  697. }
  698. ////硬體
  699. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  700. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  701. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  702. {
  703. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  704. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  705. {
  706. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  707. {
  708. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  709. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  710. if (hardProd == null)
  711. {
  712. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  713. hardProdAdd.prodCode = hardInfo.prodCode;
  714. hardProdAdd.model = hardInfo.model;
  715. hardProdAdd.ids.Add(hardInfo.id);
  716. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  717. hardsProductSumOrg.Add(hardProdAdd);
  718. }
  719. else
  720. {
  721. if (!hardProd.ids.Contains(hardInfo.id))
  722. {
  723. hardProd.ids.Add(hardInfo.id);
  724. }
  725. hardProd.avaliable = hardProd.ids.Count;
  726. }
  727. }
  728. }
  729. }
  730. //更新學校產品一覽表
  731. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  732. prodSum.serial = serialsProductSumOrg;
  733. prodSum.service = servicesProductSumOrg;
  734. prodSum.hard = hardsProductSumOrg;
  735. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  736. }
  737. catch (CosmosException ex)
  738. {
  739. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  740. }
  741. catch (Exception ex)
  742. {
  743. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  744. }
  745. }
  746. /// <summary>
  747. /// 批量复制文件
  748. /// </summary>
  749. /// <param name="msg"></param>
  750. /// <returns></returns>
  751. [Function("CopyStandardFile")]
  752. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  753. {
  754. try
  755. {
  756. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
  757. var jsonMsg = JsonDocument.Parse(msg);
  758. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  759. //批量复制文件
  760. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  761. if (result == 200)
  762. {
  763. //发送消息实体
  764. Notification notification = new Notification
  765. {
  766. hubName = "hita",
  767. type = "msg",
  768. from = $"BI:{_option.Location}:private",
  769. to = bIBatchCopyFile.tmdIds,
  770. label = $"{bIBatchCopyFile.codeKey}_finish",
  771. body = new { location = $"{Environment.GetEnvironmentVariable("Option:Location")}", biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  772. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  773. };
  774. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  775. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  776. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  777. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  778. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  779. }
  780. }
  781. catch (Exception ex)
  782. {
  783. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  784. }
  785. }
  786. /// <summary>
  787. /// 更新开课数据事件
  788. /// </summary>
  789. /// <param name="msg"></param>
  790. /// <returns></returns>
  791. [Function("LessonRecordEvent")]
  792. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  793. {
  794. JsonElement data = msg.ToObject<JsonElement>();
  795. string scope = "";
  796. string tmdid = "";
  797. string lessonId;
  798. string school;
  799. string tbname;
  800. string code;
  801. string blobname;
  802. List<LessonUpdate> updates = new List<LessonUpdate>();
  803. //更新课堂记录
  804. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  805. {
  806. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  807. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  808. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  809. data.TryGetProperty("school", out JsonElement _school);
  810. school = $"{_school}";
  811. scope = $"{_scope}";
  812. tmdid = $"{_tmdid}";
  813. lessonId = $"{_lessonId}";
  814. updates = _grant_types.ToObject<List<LessonUpdate>>();
  815. }//创建课堂记录
  816. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  817. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  818. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  819. {
  820. data.TryGetProperty("school", out JsonElement _school);
  821. school = $"{_school}";
  822. scope = $"{_scope}";
  823. tmdid = $"{_tmdid}";
  824. lessonId = $"{_id}";
  825. updates.Add(new LessonUpdate { grant_type = "create" });
  826. }//删除课堂记录
  827. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  828. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  829. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  830. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  831. {
  832. data.TryGetProperty("school", out JsonElement _dschool);
  833. school = $"{_dschool}";
  834. if ($"{_opt}".Equals("delete"))
  835. {
  836. scope = $"{_dscope}";
  837. tmdid = $"{_dtmdid}";
  838. lessonId = $"{_delete_id}";
  839. updates.Add(new LessonUpdate { grant_type = "delete" });
  840. }
  841. else { return; }
  842. }
  843. else
  844. {
  845. return;
  846. }
  847. var client = _azureCosmos.GetCosmosClient();
  848. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  849. {
  850. blobname = $"{school}";
  851. code = $"LessonRecord-{school}";
  852. tbname = "School";
  853. }
  854. else if ($"{scope}".Equals("private"))
  855. {
  856. blobname = $"{tmdid}";
  857. code = $"LessonRecord";
  858. tbname = "Teacher";
  859. }
  860. else
  861. {
  862. return;
  863. }
  864. LessonDis lessonDis = new LessonDis();
  865. List<LessonUpdate> msgs = new List<LessonUpdate>();
  866. try
  867. {
  868. LessonRecord oldlessonRecord = null;
  869. LessonRecord lessonRecord = null;
  870. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  871. if (response.Status == 200)
  872. {
  873. var doc = JsonDocument.Parse(response.ContentStream);
  874. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  875. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  876. }
  877. else
  878. {
  879. lessonRecord = null;
  880. }
  881. bool isReplace = true;
  882. if (updates.IsNotEmpty())
  883. {
  884. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  885. foreach (LessonUpdate update in updates)
  886. {
  887. switch (update.grant_type)
  888. {
  889. //更新课堂时长
  890. case "up-duration":
  891. var duration = double.Parse($"{update.data}");
  892. lessonRecord.duration = duration;
  893. msgs.Add(update);
  894. try
  895. {
  896. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  897. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  898. if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
  899. {
  900. var durationFile = double.Parse($"{_duration}");
  901. if (duration < durationFile)
  902. {
  903. lessonRecord.duration = durationFile;
  904. }
  905. }
  906. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
  907. {
  908. lessonRecord.hasVideo = 1;
  909. }
  910. }
  911. catch (Exception ex)
  912. {
  913. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  914. }
  915. isReplace = true;
  916. break;
  917. //更新T分
  918. case "up-tScore":
  919. var tScore = int.Parse($"{update.data}");
  920. lessonRecord.tScore = tScore;
  921. msgs.Add(update);
  922. break;
  923. //更新课P分
  924. case "up-pScore":
  925. var pScore = int.Parse($"{update.data}");
  926. lessonRecord.pScore = pScore;
  927. msgs.Add(update);
  928. break;
  929. //更新 学生人数
  930. case "up-mCount":
  931. var mCount = int.Parse($"{update.data}");
  932. lessonRecord.mCount = mCount;
  933. msgs.Add(update);
  934. break;
  935. //更新 议课次数
  936. case "up-techCount":
  937. var techCount = int.Parse($"{update.data}");
  938. lessonRecord.mCount = techCount;
  939. msgs.Add(update);
  940. break;
  941. //更新 基础统计信息
  942. case "up-base":
  943. //如果有更新 则去读取/{_lessonId}/IES/base.json
  944. try
  945. {
  946. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  947. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  948. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  949. if (lessonBase != null && lessonBase.summary != null)
  950. {
  951. //lessonRecord.name = lessonBase.summary.activityName;
  952. lessonRecord.attendCount = lessonBase.summary.attendCount;
  953. lessonRecord.clientCount = lessonBase.summary.clientCount;
  954. lessonRecord.attendRate = lessonBase.summary.attendRate;
  955. lessonRecord.groupCount = lessonBase.summary.groupCount;
  956. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  957. lessonRecord.collateCount = lessonBase.summary.collateCount;
  958. lessonRecord.pushCount = lessonBase.summary.pushCount;
  959. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  960. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  961. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  962. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  963. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  964. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  965. lessonRecord.examCount = lessonBase.summary.examCount;
  966. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  967. if (!string.IsNullOrWhiteSpace(lessonRecord.school)) {
  968. lessonBase.student.ForEach(x => {
  969. if (string.IsNullOrWhiteSpace(x.school))
  970. {
  971. x.school = lessonRecord.school;
  972. }
  973. });
  974. }
  975. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  976. //{
  977. // clientSummaryList = lessonBase.report.clientSummaryList,
  978. // students = lessonBase.student,
  979. // name = lessonRecord.name,
  980. // school = lessonRecord.school,
  981. // id = lessonRecord.id,
  982. // scope = lessonRecord.scope,
  983. // tmdid = lessonRecord.tmdid,
  984. // code = "LessonStudentRecord",
  985. // pk = "LessonStudentRecord",
  986. // courseId =lessonRecord.courseId,
  987. // groupIds= lessonRecord.groupIds,
  988. // periodId = lessonRecord.periodId,
  989. // subjectId = lessonRecord.subjectId,
  990. //};
  991. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  992. }
  993. //有上传 base.josn.
  994. lessonRecord.upload =1;
  995. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  996. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _notificationService, _serviceBus, _azureStorage, _configuration);
  997. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  998. Bloblog bloblog = new Bloblog
  999. {
  1000. id = lessonRecord.id,
  1001. code = $"Bloblog-{blobname}",
  1002. name = lessonRecord.name,
  1003. pk = "Bloblog",
  1004. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1005. type = "records",
  1006. url = $"records/{_lessonId}",
  1007. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1008. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1009. size = size.HasValue ? size.Value : 0,
  1010. };
  1011. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1012. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1013. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1014. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1015. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1016. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1017. msgs.Add(update);
  1018. }
  1019. catch (Exception ex)
  1020. {
  1021. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1022. }
  1023. break;
  1024. //更新 时间线
  1025. case "up-TimeLine":
  1026. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1027. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1028. msgs.Add(update);
  1029. break;
  1030. //更新 课堂总览信息
  1031. case "up-ActivityInfo":
  1032. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1033. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1034. msgs.Add(update);
  1035. break;
  1036. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1037. isReplace = true;
  1038. msgs.Add(update);
  1039. break;
  1040. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1041. try
  1042. {
  1043. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1044. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1045. foreach (var record in records)
  1046. {
  1047. try
  1048. {
  1049. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1050. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1051. }
  1052. catch (Exception)
  1053. {
  1054. continue;
  1055. }
  1056. }
  1057. }
  1058. catch (Exception)
  1059. {
  1060. break;
  1061. }
  1062. isReplace = true;
  1063. msgs.Add(update);
  1064. break;
  1065. case "delete":
  1066. try
  1067. {
  1068. if (lessonRecord.expire > 0)
  1069. {
  1070. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1071. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1072. foreach (var record in records)
  1073. {
  1074. try
  1075. {
  1076. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1077. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1078. }
  1079. catch (Exception)
  1080. {
  1081. continue;
  1082. }
  1083. }
  1084. }
  1085. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1086. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1087. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1088. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1089. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1090. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1091. msgs.Add(update);
  1092. }
  1093. catch (CosmosException)
  1094. {
  1095. msgs.Add(update);
  1096. }
  1097. lessonRecord = null;
  1098. isReplace = false;
  1099. break;
  1100. case "create":
  1101. oldlessonRecord = null;
  1102. //处理课堂选用的课程信息
  1103. lessonRecord.show = teacher.lessonShow;
  1104. lessonRecord.upload = 0;
  1105. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1106. {
  1107. Course course = null;
  1108. try
  1109. {
  1110. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1111. if (cresponse.Status == 200)
  1112. {
  1113. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1114. course = cJson.ToObject<Course>();
  1115. }
  1116. else
  1117. {
  1118. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1119. if (sresponse.Status == 200)
  1120. {
  1121. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1122. course = cJson.ToObject<Course>();
  1123. }
  1124. else
  1125. {
  1126. course = null;
  1127. }
  1128. }
  1129. }
  1130. catch (Exception ex)
  1131. {
  1132. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1133. }
  1134. /*catch (CosmosException ex) when (ex.Status != 404)
  1135. {
  1136. try
  1137. {
  1138. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1139. }
  1140. catch (CosmosException e) when (e.Status != 404)
  1141. {
  1142. course = null;
  1143. }
  1144. }*/
  1145. if (course != null)
  1146. {
  1147. lessonRecord.periodId = course.period?.id;
  1148. lessonRecord.subjectId = course.subject?.id;
  1149. }
  1150. }
  1151. //处理课堂选用的名单
  1152. if (lessonRecord.groupIds.IsNotEmpty())
  1153. {
  1154. HashSet<string> grades = new HashSet<string>();
  1155. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1156. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1157. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1158. {
  1159. try
  1160. {
  1161. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1162. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1163. //年级算法
  1164. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1165. int? Count = period?.grades?.Count;
  1166. if (Count.HasValue)
  1167. {
  1168. int Day = DateTimeOffset.UtcNow.Day;
  1169. int Month = DateTimeOffset.UtcNow.Month;
  1170. int Year = DateTimeOffset.UtcNow.Year;
  1171. int start = int.Parse($"{Year}0901");
  1172. var se = period.semesters.Find(x => x.start == 1);
  1173. if (se == null)
  1174. {
  1175. se = period.semesters.First();
  1176. }
  1177. if (se != null)
  1178. {
  1179. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1180. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1181. start = int.Parse($"{Year}{sm}{sd}");
  1182. }
  1183. int curr = int.Parse(DateTimeOffset.UtcNow.ToString("yyyyMMdd"));
  1184. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  1185. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  1186. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  1187. int dis = start - curr;
  1188. foreach (int year in gplist.Select(x => x.year))
  1189. {
  1190. int grade;
  1191. if (dis > 0)
  1192. {
  1193. grade = (Year - year - 1) % Count.Value;
  1194. }
  1195. else
  1196. {
  1197. grade = (Year - year) % Count.Value;
  1198. }
  1199. grades.Add($"{grade}");
  1200. }
  1201. }
  1202. }
  1203. catch (CosmosException ex) when (ex.Status == 404)
  1204. {
  1205. }
  1206. catch (Exception ex)
  1207. {
  1208. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1209. }
  1210. }
  1211. lessonRecord.grade = grades.ToList();
  1212. }
  1213. //个人课例保存规则
  1214. try
  1215. {
  1216. if (scope.Equals("private"))
  1217. {
  1218. if (teacher.lessonLimit != -1)
  1219. {
  1220. HashSet<string> ids = new HashSet<string>();
  1221. //未定义的 以及过期时间小于等于0 的 课例
  1222. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  1223. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1224. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1225. {
  1226. ids.Add(item);
  1227. }
  1228. //包含收藏的本人的个人课例
  1229. string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  1230. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1231. queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1232. {
  1233. ids.Add(item);
  1234. }
  1235. //教师个人预设的,可以通过设置的方式增加
  1236. int limit = teacher.lessonLimit;
  1237. if (teacher.lessonLimit == 0)
  1238. {
  1239. //未设置的的采用系统设置的默认值50
  1240. limit = Constant.private_lesson_limit;
  1241. }
  1242. if (ids.Count >= limit)
  1243. {
  1244. // 1-时间戳,7-时间戳
  1245. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1246. //暂定7天
  1247. var now = DateTimeOffset.UtcNow;
  1248. //剩余3天的通知
  1249. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1250. //result.Add(3, day3);
  1251. //剩余1天的通知
  1252. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire-1)).ToUnixTimeMilliseconds();
  1253. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1254. //到期通知
  1255. //不到五点上传的课例,七天之后直接删除。
  1256. int addSecond = 0;
  1257. if (now.Hour > 5)
  1258. {
  1259. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1260. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  1261. //再加 00到05小时内的 随机秒数
  1262. Random rand = new Random();
  1263. int randInt= rand.Next(0 , 18000);
  1264. addSecond += randInt;
  1265. }
  1266. else
  1267. {
  1268. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  1269. }
  1270. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1271. //result.Add(Constant.private_lesson_expire, lessonRecord.expire);
  1272. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  1273. string biz = "expire";
  1274. Notification notification = new Notification
  1275. {
  1276. hubName = "hita",
  1277. type = "msg",
  1278. from = $"ies5:{ Environment.GetEnvironmentVariable("Option:Location")}:private",
  1279. to = new List<string> { tmdid },
  1280. label = $"{biz}_lessonRecord",
  1281. body = new
  1282. {
  1283. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1284. biz = biz,
  1285. tmdid = teacher.id,
  1286. tmdname = teacher.name,
  1287. sid = lessonRecord.id,
  1288. sname = lessonRecord.name,
  1289. scope=scope,
  1290. stime = lessonRecord.startTime,
  1291. expire = lessonRecord.expire,
  1292. status = 1,
  1293. //day = Constant.private_lesson_expire,
  1294. time = now
  1295. }.ToJsonString(),
  1296. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1297. };
  1298. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1299. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1300. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1301. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1302. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1303. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1304. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1305. if (records.Count <= 0)
  1306. {
  1307. foreach (var item in result)
  1308. {
  1309. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  1310. //课堂的id ,
  1311. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1312. var message = new ServiceBusMessage(new
  1313. {
  1314. id = lessonRecord.id,
  1315. progress = item.Key,
  1316. code = lessonRecord.code,
  1317. scope = lessonRecord.scope,
  1318. school = lessonRecord.school,
  1319. opt = "delete",
  1320. expire = lessonRecord.expire,
  1321. tmdid = tmdid,
  1322. tmdname = teacher.name,
  1323. name = lessonRecord.name,
  1324. startTime = lessonRecord.startTime,
  1325. tag = item.Value.tag
  1326. }.ToJsonString());
  1327. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1328. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1329. ChangeRecord changeRecord = new ChangeRecord
  1330. {
  1331. RowKey = lessonRecord.id,
  1332. PartitionKey = PartitionKey,
  1333. sequenceNumber = start,
  1334. msgId = message.MessageId
  1335. };
  1336. await table.Save<ChangeRecord>(changeRecord);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. else
  1342. {
  1343. //=-1 则表示不限制上传数量
  1344. }
  1345. }
  1346. }
  1347. catch (Exception e)
  1348. {
  1349. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1350. }
  1351. msgs.Add(update);
  1352. break;
  1353. default:
  1354. break;
  1355. }
  1356. }
  1357. //如果被删除则不能再被更新
  1358. if (isReplace)
  1359. {
  1360. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1361. }
  1362. //计算课堂更新前后的差值
  1363. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1364. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1365. }
  1366. }
  1367. catch (CosmosException e)
  1368. {
  1369. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1370. }
  1371. catch (Exception ex)
  1372. {
  1373. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1374. }
  1375. }
  1376. [Function("LessonRecordExpire")]
  1377. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1378. {
  1379. try
  1380. {
  1381. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1382. jsonMsg.TryGetProperty("id", out JsonElement id);
  1383. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1384. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1385. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1386. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1387. jsonMsg.TryGetProperty("name", out JsonElement name);
  1388. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1389. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1390. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1391. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1392. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  1393. var client = _azureCosmos.GetCosmosClient();
  1394. //处理到期删除
  1395. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete") )
  1396. {
  1397. string lessonId = $"{id}";
  1398. string tbname;
  1399. string school = $"{_school}";
  1400. string code = "";
  1401. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1402. {
  1403. code = $"LessonRecord-{school}";
  1404. tbname = "School";
  1405. }
  1406. else if ($"{scope}".Equals("private"))
  1407. {
  1408. code = $"LessonRecord";
  1409. tbname = "Teacher";
  1410. }
  1411. else
  1412. {
  1413. return;
  1414. }
  1415. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1416. if (response.Status == 200)
  1417. {
  1418. LessonRecord lessonRecord;
  1419. var doc = JsonDocument.Parse(response.ContentStream);
  1420. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1421. lessonRecord.status = 404;
  1422. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1423. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1424. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  1425. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1426. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1427. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  1428. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  1429. }
  1430. }
  1431. string biz = "expire";
  1432. Notification notification = new Notification
  1433. {
  1434. hubName = "hita",
  1435. type = "msg",
  1436. from = $"ies5:{_option.Location}:private",
  1437. to = new List<string> { $"{tmdid}" },
  1438. label = $"{biz}_lessonRecord",
  1439. body = new
  1440. {
  1441. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1442. biz = biz,
  1443. tmdid = $"{tmdid}",
  1444. tmdname = tmdname,
  1445. sid = $"{id}",
  1446. sname = $"{name}",
  1447. stime = long.Parse($"{startTime}"),
  1448. expire = long.Parse($"{expire}"),
  1449. status = 1,
  1450. //day = Constant.private_lesson_expire,
  1451. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1452. }.ToJsonString(),
  1453. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1454. };
  1455. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1456. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1457. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1458. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1459. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1460. }
  1461. catch (Exception ex)
  1462. {
  1463. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1464. }
  1465. }
  1466. /// <summary>
  1467. /// 完善课程变更
  1468. /// </summary>
  1469. /// <data msg>
  1470. /// CourseChange
  1471. ///// </data>
  1472. /// <param name="msg"></param>
  1473. /// <returns></returns>
  1474. [Function("Course")]
  1475. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1476. {
  1477. var client = _azureCosmos.GetCosmosClient();
  1478. try
  1479. {
  1480. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1481. var jsonMsg = JsonDocument.Parse(msg);
  1482. CourseChange courseChange = msg.ToObject<CourseChange>();
  1483. if (courseChange == null)
  1484. {
  1485. return;
  1486. }
  1487. foreach (var cls in courseChange.addClass)
  1488. {
  1489. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1490. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1491. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1492. foreach (var stu in addStudentsCls)
  1493. {
  1494. try
  1495. {
  1496. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1497. if (!stuCourse.Value.classId.Contains(cls))
  1498. {
  1499. stuCourse.Value.classId.Add(cls);
  1500. }
  1501. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1502. }
  1503. catch (CosmosException ex)
  1504. {
  1505. if (ex.Response.Status == 404)
  1506. {
  1507. var course = new StuCourse
  1508. {
  1509. id = courseChange.id,
  1510. scode = courseChange.code,
  1511. name = courseChange.name,
  1512. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1513. scope = courseChange.scope,
  1514. school = courseChange.school,
  1515. creatorId = courseChange.creatorId,
  1516. classId = new List<string> { cls },
  1517. pk = "StuCourse",
  1518. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1519. };
  1520. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1521. }
  1522. else
  1523. {
  1524. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1525. }
  1526. }
  1527. }
  1528. foreach (var tmd in addTmdidsCls)
  1529. {
  1530. try
  1531. {
  1532. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1533. if (!stuCourse.Value.classId.Contains(cls))
  1534. {
  1535. stuCourse.Value.classId.Add(cls);
  1536. }
  1537. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1538. }
  1539. catch (CosmosException ex)
  1540. {
  1541. if (ex.Response.Status == 404)
  1542. {
  1543. var course = new StuCourse
  1544. {
  1545. id = courseChange.id,
  1546. scode = courseChange.code,
  1547. name = courseChange.name,
  1548. code = $"StuCourse-{tmd.id}",
  1549. scope = courseChange.scope,
  1550. school = courseChange.school,
  1551. creatorId = courseChange.creatorId,
  1552. classId = new List<string> { cls },
  1553. pk = "StuCourse",
  1554. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1555. };
  1556. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1557. }
  1558. else
  1559. {
  1560. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1561. }
  1562. }
  1563. }
  1564. }
  1565. foreach (var list in courseChange.addList)
  1566. {
  1567. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1568. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1569. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1570. foreach (var stu in addStudentsCls)
  1571. {
  1572. try
  1573. {
  1574. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1575. if (!stuCourse.Value.stulist.Contains(list))
  1576. {
  1577. stuCourse.Value.stulist.Add(list);
  1578. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1579. }
  1580. }
  1581. catch (CosmosException ex)
  1582. {
  1583. if (ex.Response.Status == 404)
  1584. {
  1585. var course = new StuCourse
  1586. {
  1587. id = courseChange.id,
  1588. scode = courseChange.code,
  1589. name = courseChange.name,
  1590. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1591. scope = courseChange.scope,
  1592. school = courseChange.school,
  1593. creatorId = courseChange.creatorId,
  1594. stulist = new List<string> { list },
  1595. pk = "StuCourse",
  1596. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1597. };
  1598. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1599. }
  1600. else
  1601. {
  1602. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1603. }
  1604. }
  1605. }
  1606. foreach (var tmd in addTmdidsCls)
  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.stulist.Contains(list))
  1612. {
  1613. stuCourse.Value.stulist.Add(list);
  1614. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1615. }
  1616. }
  1617. catch (CosmosException ex)
  1618. {
  1619. if (ex.Response.Status == 404)
  1620. {
  1621. var course = new StuCourse
  1622. {
  1623. id = courseChange.id,
  1624. scode = courseChange.code,
  1625. name = courseChange.name,
  1626. code = $"StuCourse-{tmd.id}",
  1627. scope = courseChange.scope,
  1628. school = courseChange.school,
  1629. creatorId = courseChange.creatorId,
  1630. stulist = new List<string> { list },
  1631. pk = "StuCourse",
  1632. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1633. };
  1634. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1635. }
  1636. else
  1637. {
  1638. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1639. }
  1640. }
  1641. }
  1642. }
  1643. foreach (var delCls in courseChange.delClass)
  1644. {
  1645. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1646. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1647. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1648. foreach (var stu in delStudentsCls)
  1649. {
  1650. try
  1651. {
  1652. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1653. if (stuCourse.Value.classId.Contains(delCls))
  1654. {
  1655. stuCourse.Value.classId.Remove(delCls);
  1656. }
  1657. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1658. {
  1659. //当两个列表都不存在时则直接删除
  1660. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1661. }
  1662. else
  1663. {
  1664. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1665. }
  1666. }
  1667. catch (CosmosException ex)
  1668. {
  1669. //await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1670. }
  1671. }
  1672. foreach (var tmd in delTmdidsCls)
  1673. {
  1674. try
  1675. {
  1676. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1677. if (stuCourse.Value.classId.Contains(delCls))
  1678. {
  1679. stuCourse.Value.classId.Remove(delCls);
  1680. }
  1681. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1682. {
  1683. //当两个列表都不存在时则直接删除
  1684. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1685. }
  1686. else
  1687. {
  1688. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1689. }
  1690. }
  1691. catch (CosmosException ex)
  1692. {
  1693. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1694. }
  1695. }
  1696. }
  1697. foreach (var delList in courseChange.delList)
  1698. {
  1699. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1700. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1701. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1702. foreach (var stu in delStudentsCls)
  1703. {
  1704. try
  1705. {
  1706. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1707. if (stuCourse.Value.stulist.Contains(delList))
  1708. {
  1709. stuCourse.Value.stulist.Remove(delList);
  1710. }
  1711. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1712. {
  1713. //当两个列表都不存在时则直接删除
  1714. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1715. }
  1716. else
  1717. {
  1718. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1719. }
  1720. }
  1721. catch (CosmosException ex)
  1722. {
  1723. continue;
  1724. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1725. }
  1726. }
  1727. foreach (var tmd in delTmdidsCls)
  1728. {
  1729. try
  1730. {
  1731. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1732. if (stuCourse.Value.stulist.Contains(delList))
  1733. {
  1734. stuCourse.Value.stulist.Remove(delList);
  1735. }
  1736. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1737. {
  1738. //当两个列表都不存在时则直接删除
  1739. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1740. }
  1741. else
  1742. {
  1743. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1744. }
  1745. }
  1746. catch (CosmosException ex)
  1747. {
  1748. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1749. }
  1750. }
  1751. }
  1752. }
  1753. catch (Exception ex)
  1754. {
  1755. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1756. }
  1757. }
  1758. }
  1759. }