ActiveTaskTopic.cs 145 KB

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