ActiveTaskTopic.cs 109 KB

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