ActiveTaskTopic.cs 123 KB

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