ActiveTaskTopic.cs 163 KB

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