ActiveTaskTopic.cs 159 KB

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