ActiveTaskTopic.cs 129 KB

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