ActiveTaskTopic.cs 147 KB

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