ActiveTaskTopic.cs 142 KB

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