ActiveTaskTopic.cs 152 KB

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