ActiveTaskTopic.cs 142 KB

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