ActiveTaskTopic.cs 150 KB

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