ActiveTaskTopic.cs 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. using Azure.Cosmos;
  7. using Azure.Messaging.ServiceBus;
  8. using Microsoft.Extensions.Logging;
  9. using StackExchange.Redis;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using System.Linq;
  17. using TEAMModelOS.SDK.Models.Service;
  18. using TEAMModelOS.SDK.Models.Cosmos.BI;
  19. using TEAMModelOS.Models;
  20. using Microsoft.Extensions.Options;
  21. using Microsoft.Extensions.Configuration;
  22. using HTEXLib.COMM.Helpers;
  23. using Microsoft.Azure.Functions.Worker;
  24. using TEAMModelOS.SDK.Services;
  25. using Azure.Storage.Blobs.Models;
  26. using System.IO;
  27. using Azure;
  28. namespace TEAMModelOS.FunctionV4.ServiceBus
  29. {
  30. public class ActiveTaskTopic
  31. {
  32. private readonly AzureCosmosFactory _azureCosmos;
  33. private readonly DingDing _dingDing;
  34. private readonly AzureStorageFactory _azureStorage;
  35. private readonly AzureRedisFactory _azureRedis;
  36. private readonly AzureServiceBusFactory _serviceBus;
  37. private readonly Option _option;
  38. private readonly NotificationService _notificationService;
  39. private readonly CoreAPIHttpService _coreAPIHttpService;
  40. private readonly IConfiguration _configuration;
  41. public ActiveTaskTopic(CoreAPIHttpService coreAPIHttpService,AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
  42. {
  43. _azureCosmos = azureCosmos;
  44. _dingDing = dingDing;
  45. _azureStorage = azureStorage;
  46. _azureRedis = azureRedis;
  47. _serviceBus = serviceBus;
  48. _option = option?.Value;
  49. _notificationService = notificationService;
  50. _configuration = configuration;
  51. _coreAPIHttpService = coreAPIHttpService;
  52. }
  53. [Function("Exam")]
  54. public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  55. {
  56. try
  57. {
  58. var json = JsonDocument.Parse(msg);
  59. json.RootElement.TryGetProperty("id", out JsonElement id);
  60. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  61. json.RootElement.TryGetProperty("code", out JsonElement code);
  62. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  63. var client = _azureCosmos.GetCosmosClient();
  64. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  65. exam.progress = progress.ToString();
  66. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  67. }
  68. catch (CosmosException e)
  69. {
  70. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  71. }
  72. catch (Exception ex)
  73. {
  74. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  75. }
  76. }
  77. [Function("Vote")]
  78. public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  79. {
  80. try
  81. {
  82. var jsonMsg = JsonDocument.Parse(msg);
  83. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  84. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  85. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  86. var client = _azureCosmos.GetCosmosClient();
  87. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  88. vote.progress = progress.ToString();
  89. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  90. }
  91. catch (CosmosException e)
  92. {
  93. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  94. }
  95. catch (Exception ex)
  96. {
  97. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  98. }
  99. }
  100. [Function("Correct")]
  101. public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  102. {
  103. try
  104. {
  105. var jsonMsg = JsonDocument.Parse(msg);
  106. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  107. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  108. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  109. var client = _azureCosmos.GetCosmosClient();
  110. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  111. correct.progress = progress.ToString();
  112. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  113. }
  114. catch (CosmosException e)
  115. {
  116. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  117. }
  118. catch (Exception ex)
  119. {
  120. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  121. }
  122. }
  123. [Function("Survey")]
  124. public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  125. {
  126. try
  127. {
  128. var jsonMsg = JsonDocument.Parse(msg);
  129. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  130. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  131. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  132. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  133. var client = _azureCosmos.GetCosmosClient();
  134. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  135. survey.progress = progress.ToString();
  136. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  137. }
  138. catch (CosmosException e)
  139. {
  140. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
  141. }
  142. catch (Exception ex)
  143. {
  144. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  145. }
  146. }
  147. [Function("Homework")]
  148. public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  149. {
  150. try
  151. {
  152. var jsonMsg = JsonDocument.Parse(msg);
  153. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  154. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  155. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  156. var client = _azureCosmos.GetCosmosClient();
  157. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  158. homework.progress = progress.ToString();
  159. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  160. }
  161. catch (CosmosException e)
  162. {
  163. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.StackTrace}{e.Message}{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
  164. }
  165. catch (Exception ex)
  166. {
  167. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  168. }
  169. }
  170. [Function("Study")]
  171. public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  172. {
  173. string activityId = string.Empty;
  174. try
  175. {
  176. var jsonMsg = JsonDocument.Parse(msg);
  177. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  178. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  179. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  180. var client = _azureCosmos.GetCosmosClient();
  181. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  182. study.progress = progress.ToString();
  183. activityId = id.ToString();
  184. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  185. }
  186. catch (CosmosException e)
  187. {
  188. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
  189. }
  190. catch (Exception ex)
  191. {
  192. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  193. }
  194. }
  195. [Function("ExamLite")]
  196. public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  197. {
  198. try
  199. {
  200. var jsonMsg = JsonDocument.Parse(msg);
  201. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  202. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  203. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  204. var client = _azureCosmos.GetCosmosClient();
  205. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  206. lite.progress = progress.ToString();
  207. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  208. }
  209. catch (CosmosException e)
  210. {
  211. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
  212. }
  213. catch (Exception ex)
  214. {
  215. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  216. }
  217. }
  218. /// <summary>
  219. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  220. /// </summary>
  221. /// <param name="msg"></param>
  222. /// <returns></returns>
  223. [Function("BlobRoot")]
  224. public async Task BlobRootFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  225. {
  226. try
  227. {
  228. var jsonMsg = JsonDocument.Parse(msg);
  229. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  230. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  231. {
  232. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:触发变更,{jsonMsg.ToJsonString()}",
  233. // GroupNames.成都开发測試群組);
  234. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  235. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  236. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  237. string name = $"{_name}";
  238. string lockKey = $"Blob:Lock:{name}:{u}";
  239. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  240. if (!exist)
  241. { ///key不存在则正常进行计算
  242. bool condition = false;
  243. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  244. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  245. //准备处理Blob刷新时间
  246. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  247. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  248. await RefreshBlob(name, u);
  249. //将action 与Redis最新的时间进行比较,如果
  250. var rds = await CheckLockKey(lockKey, action);
  251. condition = rds.condition;
  252. exist = rds.exist;
  253. if (condition || !exist)
  254. {
  255. await RefreshBlob(name, u);
  256. }
  257. //使用 CancellationToken
  258. //while (condition || !exist)
  259. //{
  260. //}
  261. }
  262. else
  263. {
  264. ///key存在则,则刷新key对应的值
  265. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  266. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  267. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  268. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  269. }
  270. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
  271. // GroupNames.成都开发測試群組);
  272. }
  273. }
  274. catch (Exception ex)
  275. {
  276. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  277. }
  278. }
  279. private async Task<(bool condition, bool exist)> CheckLockKey(string lockKey, long nowTime)
  280. {
  281. //Redis的最新时间
  282. long newestTime = 0;
  283. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  284. if (value != default && !value.IsNullOrEmpty)
  285. {
  286. JsonElement record = value.ToString().ToObject<JsonElement>();
  287. if (record.TryGetInt64(out newestTime))
  288. {
  289. }
  290. }
  291. //说明key已经不存在
  292. if (newestTime == 0)
  293. {
  294. return (false, true);
  295. }
  296. //说明key存在
  297. else
  298. {
  299. //说明Redis记录了最新的时间戳
  300. if (nowTime != newestTime)
  301. {
  302. return (true, false);
  303. }
  304. //时间相同,没有被再次记录最新的时间戳
  305. else
  306. {
  307. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  308. return (false, true);
  309. }
  310. }
  311. }
  312. private async Task RefreshBlob(string name, string u)
  313. {
  314. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  315. var client = _azureStorage.GetBlobContainerClient(name);
  316. var size = await client.GetBlobsSize(u);
  317. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  318. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  319. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  320. double blobsize = 0;
  321. if (scores != default && scores != null)
  322. {
  323. foreach (var score in scores)
  324. {
  325. blobsize = blobsize + score.Score;
  326. }
  327. }
  328. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  329. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  330. long dis = (end - statr) / 1000;
  331. long timeout = 10;
  332. if (dis > timeout)
  333. {
  334. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  335. }
  336. }
  337. /// <summary>
  338. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  339. /// </summary>
  340. /// <data msg>
  341. /// CourseChange
  342. ///// </data>
  343. /// <param name="msg"></param>
  344. /// <returns></returns>
  345. [Function("TeacherTrainChange")]
  346. public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  347. {
  348. try
  349. {
  350. // await _dingDing.SendBotMsg($"teacher-train-change\n{msg}",GroupNames.成都开发測試群組);
  351. TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
  352. if (change.update == null || change.update.Count <= 0 || change.tmdids.IsEmpty())
  353. {
  354. return;
  355. }
  356. var client = _azureCosmos.GetCosmosClient();
  357. string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
  358. string selsql = $"select value(c) from c {insql} ";
  359. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  360. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
  361. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
  362. {
  363. teacherTrains.Add(item);
  364. }
  365. if (change.statistics != 1)
  366. {
  367. List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
  368. teacherTrains.ForEach(x =>
  369. {
  370. x.update.UnionWith(change.update);
  371. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
  372. });
  373. await task.TaskPage(5);
  374. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  375. if (unchange != null)
  376. {
  377. task.Clear();
  378. unchange.ToList().ForEach(x =>
  379. {
  380. TeacherTrain teacherTrain = new TeacherTrain
  381. {
  382. pk = "TeacherTrain",
  383. id = x,
  384. code = $"TeacherTrain-{change.school}",
  385. tmdid = x,
  386. school = change.school,
  387. update = new HashSet<string> { StatisticsService.TeacherAbility,
  388. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  389. };
  390. teacherTrain.update.UnionWith(change.update);
  391. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
  392. });
  393. await task.TaskPage(1);
  394. }
  395. }
  396. else
  397. {
  398. Area area = null;
  399. string sql = $"select value(c) from c where c.standard='{change.standard}'";
  400. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
  401. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  402. {
  403. area = item;
  404. }
  405. AreaSetting setting = null;
  406. if (area != null)
  407. {
  408. try
  409. {
  410. //优先找校级
  411. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  412. }
  413. catch (CosmosException)
  414. {
  415. try
  416. {
  417. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  418. }
  419. catch (CosmosException)
  420. {
  421. setting = null;
  422. }
  423. }
  424. }
  425. if (setting == null)
  426. {
  427. setting = new AreaSetting
  428. {
  429. allTime = 50,
  430. classTime = 5,
  431. submitTime = 15,
  432. onlineTime = 20,
  433. offlineTime = 10,
  434. lessonMinutes = 45,
  435. };
  436. }
  437. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  438. teacherTrains.ForEach(x =>
  439. {
  440. x.update.UnionWith(change.update);
  441. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  442. });
  443. await task.TaskPage(1);
  444. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  445. if (unchange != null)
  446. {
  447. task.Clear();
  448. unchange.ToList().ForEach(x =>
  449. {
  450. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  451. {
  452. pk = "TeacherTrain",
  453. id = x,
  454. code = $"TeacherTrain-{change.school}",
  455. tmdid = x,
  456. school = change.school,
  457. update = new HashSet<string> { StatisticsService.TeacherAbility,
  458. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  459. }, setting, area, client, null));
  460. });
  461. await task.TaskPage(1);
  462. }
  463. }
  464. }
  465. catch (CosmosException ex)
  466. {
  467. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}CosmosException{ex.Status}", GroupNames.成都开发測試群組);
  468. }
  469. catch (Exception ex)
  470. {
  471. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  472. }
  473. }
  474. /// <summary>
  475. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  476. /// </summary>
  477. /// <data msg>
  478. /// CourseChange
  479. ///// </data>
  480. /// <param name="msg"></param>
  481. /// <returns></returns>
  482. [Function("GroupChange")]
  483. public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  484. {
  485. var client = _azureCosmos.GetCosmosClient();
  486. try
  487. {
  488. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.成都开发測試群組);
  489. var jsonMsg = JsonDocument.Parse(msg);
  490. GroupChange groupChange = msg.ToObject<GroupChange>();
  491. //名单变动修改学生课程关联信息
  492. //await StuListService.FixStuCourse(client, stuListChange);
  493. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  494. //名单变动修改学生问卷关联信息
  495. await ActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
  496. //名单变动修改学生投票关联信息
  497. await ActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
  498. //名单变动修改学生评测关联信息
  499. await ActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
  500. //TODO学习活动
  501. //await FixActivity(client, stuListChange, "Learn");
  502. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  503. {
  504. //课程名单变动修改学生课程关联信息
  505. await ActivityService.FixStuCourse(client, _dingDing, groupChange);
  506. //名单变动修改学生研修关联信息
  507. await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  508. //名单变动修改学生简易评测关联信息
  509. await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  510. //名单变动修改学生作业活动信息
  511. await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  512. }
  513. }
  514. catch (Exception ex)
  515. {
  516. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange-GroupChange\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  517. }
  518. }
  519. [Function("ItemCond")]
  520. public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  521. {
  522. try
  523. {
  524. var client = _azureCosmos.GetCosmosClient();
  525. var jsonMsg = JsonDocument.Parse(msg);
  526. List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
  527. foreach (var itemCondDto in itemCondDtos)
  528. {
  529. if (itemCondDto.scope.Equals("school"))
  530. {
  531. ItemCond itemCond = null;
  532. List<ItemInfo> items = new List<ItemInfo>();
  533. 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 ";
  534. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
  535. {
  536. items.Add(item);
  537. }
  538. itemCond = new ItemCond()
  539. {
  540. id = $"{itemCondDto.filed}",
  541. code = $"ItemCond-{itemCondDto.key}",
  542. pk = "ItemCond",
  543. ttl = -1,
  544. count = items.Count,
  545. grades = new List<GradeCount>(),
  546. subjects = new List<SubjectItemCount>()
  547. };
  548. items.ForEach(z =>
  549. {
  550. if (!string.IsNullOrEmpty(z.type))
  551. {
  552. ItemService.CountItemCond(z, null, itemCond);
  553. }
  554. });
  555. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
  556. }
  557. else
  558. {
  559. ItemCond itemCond = null;
  560. List<ItemInfo> items = new List<ItemInfo>();
  561. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
  562. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
  563. {
  564. items.Add(item);
  565. }
  566. itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
  567. items.ForEach(z =>
  568. {
  569. if (!string.IsNullOrEmpty(z.type))
  570. {
  571. ItemService.CountItemCond(z, null, itemCond);
  572. }
  573. });
  574. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
  575. }
  576. }
  577. }
  578. catch (CosmosException ex)
  579. {
  580. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  581. }
  582. catch (Exception ex)
  583. {
  584. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  585. }
  586. }
  587. //更新產品一覽表
  588. [Function("Product")]
  589. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  590. {
  591. try
  592. {
  593. var jsonMsg = JsonDocument.Parse(msg);
  594. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  595. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  596. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  597. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  598. var client = _azureCosmos.GetCosmosClient();
  599. string strQuery = string.Empty;
  600. //取得所有學校產品
  601. ////序號
  602. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  603. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  604. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  605. {
  606. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  607. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  608. {
  609. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  610. {
  611. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  612. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  613. if (serialProd == null)
  614. {
  615. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  616. serialProdAdd.prodCode = serialInfo.prodCode;
  617. serialProdAdd.ids.Add(serialInfo.id);
  618. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  619. serialsProductSumOrg.Add(serialProdAdd);
  620. }
  621. else
  622. {
  623. if (!serialProd.ids.Contains(serialInfo.id))
  624. {
  625. serialProd.ids.Add(serialInfo.id);
  626. }
  627. serialProd.avaliable = serialProd.ids.Count;
  628. }
  629. }
  630. }
  631. }
  632. ////服務
  633. List<SchoolProductSumData> servicesProductSumOrg = new List<SchoolProductSumData>();
  634. long timestampToday = DateTimeOffset.UtcNow.AddSeconds(1).ToUnixTimeSeconds(); //比現實時間延遲1秒
  635. strQuery = $"SELECT * FROM c WHERE c.dataType = 'service' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0"; //在授權期間、ttl < 0 才取
  636. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  637. {
  638. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  639. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  640. {
  641. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  642. {
  643. SchoolProductService serviceInfo = obj.ToObject<SchoolProductService>();
  644. SchoolProductSumData serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == serviceInfo.prodCode).FirstOrDefault();
  645. if (serviceProd == null)
  646. {
  647. SchoolProductSumData serviceProdAdd = new SchoolProductSumData();
  648. serviceProdAdd.prodCode = serviceInfo.prodCode;
  649. serviceProdAdd.avaliable = 0;
  650. serviceProdAdd.ids.Add(serviceInfo.id);
  651. serviceProdAdd.avaliable += serviceInfo.number;
  652. servicesProductSumOrg.Add(serviceProdAdd);
  653. }
  654. else
  655. {
  656. if (!serviceProd.ids.Contains(serviceInfo.id))
  657. {
  658. serviceProd.ids.Add(serviceInfo.id);
  659. serviceProd.avaliable += serviceInfo.number;
  660. }
  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 (SchoolProductSumData 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{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{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 = _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 = _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{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-{tmdid}";
  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. foreach (LessonUpdate update in updates)
  885. {
  886. switch (update.grant_type)
  887. {
  888. //更新课堂时长
  889. case "up-duration":
  890. var duration = double.Parse($"{update.data}");
  891. lessonRecord.duration = duration;
  892. msgs.Add(update);
  893. try {
  894. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  895. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  896. if (RecordingJson.TryGetProperty("duration",out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number)) {
  897. var durationFile = double.Parse($"{_duration}");
  898. if (duration < durationFile) {
  899. lessonRecord.duration = durationFile;
  900. }
  901. }
  902. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) &&!string.IsNullOrWhiteSpace($"{_streamUrl}"))
  903. {
  904. lessonRecord.hasVideo = 1;
  905. }
  906. }
  907. catch (Exception ex ) {
  908. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.成都开发測試群組);
  909. }
  910. isReplace = true;
  911. break;
  912. //更新T分
  913. case "up-tScore":
  914. var tScore = int.Parse($"{update.data}");
  915. lessonRecord.tScore = tScore;
  916. msgs.Add(update);
  917. break;
  918. //更新课P分
  919. case "up-pScore":
  920. var pScore = int.Parse($"{update.data}");
  921. lessonRecord.pScore = pScore;
  922. msgs.Add(update);
  923. break;
  924. //更新 学生人数
  925. case "up-mCount":
  926. var mCount = int.Parse($"{update.data}");
  927. lessonRecord.mCount = mCount;
  928. msgs.Add(update);
  929. break;
  930. //更新 议课次数
  931. case "up-techCount":
  932. var techCount = int.Parse($"{update.data}");
  933. lessonRecord.mCount = techCount;
  934. msgs.Add(update);
  935. break;
  936. //更新 基础统计信息
  937. case "up-base":
  938. //如果有更新 则去读取/{_lessonId}/IES/base.json
  939. try
  940. {
  941. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.成都开发測試群組);
  942. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  943. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  944. if (lessonBase != null && lessonBase.summary!=null)
  945. {
  946. lessonRecord.attendCount = lessonBase.summary.attendCount;
  947. lessonRecord.clientCount = lessonBase.summary.clientCount;
  948. lessonRecord.attendRate = lessonBase.summary.attendRate;
  949. lessonRecord.groupCount = lessonBase.summary.groupCount;
  950. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  951. lessonRecord.collateCount = lessonBase.summary.collateCount;
  952. lessonRecord.pushCount = lessonBase.summary.pushCount;
  953. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  954. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  955. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  956. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  957. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  958. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  959. lessonRecord.examCount = lessonBase.summary.examCount;
  960. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  961. }
  962. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.成都开发測試群組);
  963. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  964. Bloblog bloblog = new Bloblog
  965. {
  966. id = lessonRecord.id,
  967. code = $"Bloblog-{blobname}",
  968. name = lessonRecord.name,
  969. pk = "Bloblog",
  970. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  971. type = "records",
  972. url = $"records/{_lessonId}",
  973. subjectId =string.IsNullOrWhiteSpace(lessonRecord.subjectId)?new List<string>(): new List<string> { lessonRecord.subjectId },
  974. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  975. size = size.HasValue ? size.Value : 0,
  976. };
  977. await client.GetContainer(Constant.TEAMModelOS,tbname).UpsertItemAsync(bloblog);
  978. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  979. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  980. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  981. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  982. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.成都开发測試群組);
  983. msgs.Add(update);
  984. }
  985. catch (Exception ex)
  986. {
  987. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  988. }
  989. break;
  990. //更新 时间线
  991. case "up-TimeLine":
  992. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  993. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  994. msgs.Add(update);
  995. break;
  996. //更新 课堂总览信息
  997. case "up-ActivityInfo":
  998. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  999. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1000. msgs.Add(update);
  1001. break;
  1002. ///更新基础信息,名称科目,年级,分类等。
  1003. case "up-baseinfo":
  1004. if (updates.Count > 1)
  1005. {
  1006. isReplace = true;
  1007. }
  1008. else
  1009. {
  1010. isReplace = false;
  1011. }
  1012. msgs.Add(update);
  1013. break;
  1014. case "delete":
  1015. try
  1016. {
  1017. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemAsync<LessonRecord>(lessonId, new PartitionKey(code));
  1018. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1019. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id,new PartitionKey ($"Bloblog-{blobname}"));
  1020. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1021. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1022. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1023. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1024. msgs.Add(update);
  1025. }
  1026. catch (CosmosException)
  1027. {
  1028. msgs.Add(update);
  1029. }
  1030. lessonRecord = null;
  1031. isReplace = false;
  1032. break;
  1033. case "create":
  1034. oldlessonRecord = null;
  1035. //处理课堂选用的课程信息
  1036. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1037. {
  1038. Course course = null;
  1039. try
  1040. {
  1041. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1042. if (cresponse.Status == 200)
  1043. {
  1044. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1045. course = cJson.ToObject<Course>();
  1046. }
  1047. else
  1048. {
  1049. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1050. if (sresponse.Status == 200)
  1051. {
  1052. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1053. course = cJson.ToObject<Course>();
  1054. }
  1055. else
  1056. {
  1057. course = null;
  1058. }
  1059. }
  1060. }
  1061. catch (Exception ex) {
  1062. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1063. }
  1064. /*catch (CosmosException ex) when (ex.Status != 404)
  1065. {
  1066. try
  1067. {
  1068. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1069. }
  1070. catch (CosmosException e) when (e.Status != 404)
  1071. {
  1072. course = null;
  1073. }
  1074. }*/
  1075. if (course != null)
  1076. {
  1077. lessonRecord.periodId = course.period?.id;
  1078. lessonRecord.subjectId = course.subject?.id;
  1079. }
  1080. }
  1081. //处理课堂选用的名单
  1082. if (lessonRecord.groupIds.IsNotEmpty())
  1083. {
  1084. HashSet<string> grades = new HashSet<string>();
  1085. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1086. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1087. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1088. {
  1089. try {
  1090. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1091. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1092. //年级算法
  1093. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1094. int? Count = period?.grades?.Count;
  1095. if (Count.HasValue)
  1096. {
  1097. int Month = DateTimeOffset.UtcNow.Month;
  1098. int Year = DateTimeOffset.UtcNow.Year;
  1099. foreach (int year in gplist.Select(x => x.year))
  1100. {
  1101. int grade;
  1102. if (Month >= 1 && Month <= 6)
  1103. {
  1104. grade = (Year - year -1) % Count.Value;
  1105. }
  1106. else
  1107. {
  1108. grade = (Year - year) % Count.Value;
  1109. }
  1110. grades.Add($"{grade}");
  1111. }
  1112. }
  1113. } catch (CosmosException ex) when (ex.Status == 404) {
  1114. }
  1115. }
  1116. lessonRecord.grade= grades.ToList();
  1117. }
  1118. msgs.Add(update);
  1119. break;
  1120. default:
  1121. break;
  1122. }
  1123. }
  1124. //如果被删除则不能再被更新
  1125. if (isReplace) {
  1126. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1127. }
  1128. //计算课堂更新前后的差值
  1129. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1130. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1131. }
  1132. }
  1133. catch (CosmosException e)
  1134. {
  1135. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  1136. }
  1137. catch (Exception ex)
  1138. {
  1139. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n{data}\n{code}\n{updates}\n", GroupNames.成都开发測試群組);
  1140. }
  1141. }
  1142. /// <summary>
  1143. /// 完善课程变更
  1144. /// </summary>
  1145. /// <data msg>
  1146. /// CourseChange
  1147. ///// </data>
  1148. /// <param name="msg"></param>
  1149. /// <returns></returns>
  1150. [Function("Course")]
  1151. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1152. {
  1153. var client = _azureCosmos.GetCosmosClient();
  1154. try
  1155. {
  1156. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1157. var jsonMsg = JsonDocument.Parse(msg);
  1158. CourseChange courseChange = msg.ToObject<CourseChange>();
  1159. if (courseChange == null)
  1160. {
  1161. return;
  1162. }
  1163. foreach (var cls in courseChange.addClass)
  1164. {
  1165. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1166. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1167. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1168. foreach (var stu in addStudentsCls)
  1169. {
  1170. try
  1171. {
  1172. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1173. if (!stuCourse.Value.classId.Contains(cls))
  1174. {
  1175. stuCourse.Value.classId.Add(cls);
  1176. }
  1177. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1178. }
  1179. catch (CosmosException ex)
  1180. {
  1181. if (ex.Response.Status == 404)
  1182. {
  1183. var course = new StuCourse
  1184. {
  1185. id = courseChange.id,
  1186. scode = courseChange.code,
  1187. name = courseChange.name,
  1188. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1189. scope = courseChange.scope,
  1190. school = courseChange.school,
  1191. creatorId = courseChange.creatorId,
  1192. classId = new List<string> { cls },
  1193. pk = "StuCourse",
  1194. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1195. };
  1196. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1197. }
  1198. else
  1199. {
  1200. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1201. }
  1202. }
  1203. }
  1204. foreach (var tmd in addTmdidsCls)
  1205. {
  1206. try
  1207. {
  1208. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1209. if (!stuCourse.Value.classId.Contains(cls))
  1210. {
  1211. stuCourse.Value.classId.Add(cls);
  1212. }
  1213. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1214. }
  1215. catch (CosmosException ex)
  1216. {
  1217. if (ex.Response.Status == 404)
  1218. {
  1219. var course = new StuCourse
  1220. {
  1221. id = courseChange.id,
  1222. scode = courseChange.code,
  1223. name = courseChange.name,
  1224. code = $"StuCourse-{tmd.id}",
  1225. scope = courseChange.scope,
  1226. school = courseChange.school,
  1227. creatorId = courseChange.creatorId,
  1228. classId = new List<string> { cls },
  1229. pk = "StuCourse",
  1230. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1231. };
  1232. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1233. }
  1234. else
  1235. {
  1236. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1237. }
  1238. }
  1239. }
  1240. }
  1241. foreach (var list in courseChange.addList)
  1242. {
  1243. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1244. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1245. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1246. foreach (var stu in addStudentsCls)
  1247. {
  1248. try
  1249. {
  1250. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1251. if (!stuCourse.Value.stulist.Contains(list))
  1252. {
  1253. stuCourse.Value.stulist.Add(list);
  1254. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1255. }
  1256. }
  1257. catch (CosmosException ex)
  1258. {
  1259. if (ex.Response.Status == 404)
  1260. {
  1261. var course = new StuCourse
  1262. {
  1263. id = courseChange.id,
  1264. scode = courseChange.code,
  1265. name = courseChange.name,
  1266. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1267. scope = courseChange.scope,
  1268. school = courseChange.school,
  1269. creatorId = courseChange.creatorId,
  1270. stulist = new List<string> { list },
  1271. pk = "StuCourse",
  1272. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1273. };
  1274. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1275. }
  1276. else
  1277. {
  1278. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1279. }
  1280. }
  1281. }
  1282. foreach (var tmd in addTmdidsCls)
  1283. {
  1284. try
  1285. {
  1286. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1287. if (!stuCourse.Value.stulist.Contains(list))
  1288. {
  1289. stuCourse.Value.stulist.Add(list);
  1290. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1291. }
  1292. }
  1293. catch (CosmosException ex)
  1294. {
  1295. if (ex.Response.Status == 404)
  1296. {
  1297. var course = new StuCourse
  1298. {
  1299. id = courseChange.id,
  1300. scode = courseChange.code,
  1301. name = courseChange.name,
  1302. code = $"StuCourse-{tmd.id}",
  1303. scope = courseChange.scope,
  1304. school = courseChange.school,
  1305. creatorId = courseChange.creatorId,
  1306. stulist = new List<string> { list },
  1307. pk = "StuCourse",
  1308. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1309. };
  1310. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1311. }
  1312. else
  1313. {
  1314. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. foreach (var delCls in courseChange.delClass)
  1320. {
  1321. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1322. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1323. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1324. foreach (var stu in delStudentsCls)
  1325. {
  1326. try
  1327. {
  1328. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1329. if (stuCourse.Value.classId.Contains(delCls))
  1330. {
  1331. stuCourse.Value.classId.Remove(delCls);
  1332. }
  1333. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1334. {
  1335. //当两个列表都不存在时则直接删除
  1336. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1337. }
  1338. else
  1339. {
  1340. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1341. }
  1342. }
  1343. catch (CosmosException ex)
  1344. {
  1345. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1346. }
  1347. }
  1348. foreach (var tmd in delTmdidsCls)
  1349. {
  1350. try
  1351. {
  1352. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1353. if (stuCourse.Value.classId.Contains(delCls))
  1354. {
  1355. stuCourse.Value.classId.Remove(delCls);
  1356. }
  1357. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1358. {
  1359. //当两个列表都不存在时则直接删除
  1360. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1361. }
  1362. else
  1363. {
  1364. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1365. }
  1366. }
  1367. catch (CosmosException ex)
  1368. {
  1369. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1370. }
  1371. }
  1372. }
  1373. foreach (var delList in courseChange.delList)
  1374. {
  1375. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1376. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1377. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1378. foreach (var stu in delStudentsCls)
  1379. {
  1380. try
  1381. {
  1382. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1383. if (stuCourse.Value.stulist.Contains(delList))
  1384. {
  1385. stuCourse.Value.stulist.Remove(delList);
  1386. }
  1387. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1388. {
  1389. //当两个列表都不存在时则直接删除
  1390. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1391. }
  1392. else
  1393. {
  1394. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1395. }
  1396. }
  1397. catch (CosmosException ex)
  1398. {
  1399. continue;
  1400. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1401. }
  1402. }
  1403. foreach (var tmd in delTmdidsCls)
  1404. {
  1405. try
  1406. {
  1407. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1408. if (stuCourse.Value.stulist.Contains(delList))
  1409. {
  1410. stuCourse.Value.stulist.Remove(delList);
  1411. }
  1412. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1413. {
  1414. //当两个列表都不存在时则直接删除
  1415. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1416. }
  1417. else
  1418. {
  1419. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1420. }
  1421. }
  1422. catch (CosmosException ex)
  1423. {
  1424. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. catch (Exception ex)
  1430. {
  1431. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1432. }
  1433. }
  1434. }
  1435. }