ActiveTaskTopic.cs 112 KB

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