ActiveTaskTopic.cs 159 KB

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