IESHttpTrigger.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. using Azure.Cosmos;
  2. using Azure.Storage.Blobs.Models;
  3. using Azure.Storage.Blobs.Specialized;
  4. using Azure.Storage.Sas;
  5. using DocumentFormat.OpenXml.Bibliography;
  6. using DocumentFormat.OpenXml.Drawing.Wordprocessing;
  7. using DocumentFormat.OpenXml.Office2010.Excel;
  8. using DocumentFormat.OpenXml.Office2013.Excel;
  9. using DocumentFormat.OpenXml.Spreadsheet;
  10. using HTEXLib;
  11. using HTEXLib.COMM.Helpers;
  12. using HTEXLib.Models;
  13. using Microsoft.AspNetCore.Components;
  14. using Microsoft.Azure.Cosmos.Table;
  15. using Microsoft.Azure.Functions.Worker;
  16. using Microsoft.Azure.Functions.Worker.Http;
  17. using Microsoft.Extensions.Configuration;
  18. using Microsoft.Extensions.Hosting;
  19. using Microsoft.Extensions.Options;
  20. using OpenXmlPowerTools;
  21. using StackExchange.Redis;
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Dynamic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Net;
  28. using System.Net.Http;
  29. using System.Net.Http.Json;
  30. using System.Reflection;
  31. using System.Security.Policy;
  32. using System.ServiceModel.Channels;
  33. using System.Text;
  34. using System.Text.Json;
  35. using System.Threading;
  36. using System.Threading.Tasks;
  37. using System.Web;
  38. using TEAMModelOS.Models;
  39. using TEAMModelOS.SDK;
  40. using TEAMModelOS.SDK.Context.Constant;
  41. using TEAMModelOS.SDK.DI;
  42. using TEAMModelOS.SDK.Extension;
  43. using TEAMModelOS.SDK.Models;
  44. using TEAMModelOS.SDK.Models.Dtos;
  45. using TEAMModelOS.SDK.Models.Service;
  46. using TEAMModelOS.SDK.Models.Table;
  47. using static TEAMModelOS.FunctionV4.Program;
  48. using static TEAMModelOS.SDK.Models.Teacher;
  49. using static TEAMModelOS.SDK.Services.ActivityStudentService;
  50. using static TEAMModelOS.SDK.Services.BlobService;
  51. using Path = System.IO.Path;
  52. namespace TEAMModelOS.FunctionV4
  53. {
  54. public class IESHttpTrigger
  55. {
  56. private readonly AzureCosmosFactory _azureCosmos;
  57. private readonly DingDing _dingDing;
  58. private readonly AzureStorageFactory _azureStorage;
  59. private readonly AzureRedisFactory _azureRedis;
  60. private readonly IHttpClientFactory _httpClient;
  61. private readonly Option _option;
  62. private readonly CoreAPIHttpService _coreAPIHttpService;
  63. private readonly IConfiguration _configuration;
  64. private readonly BackgroundWorkerQueue _backgroundWorkerQueue;
  65. public IESHttpTrigger( AzureCosmosFactory azureCosmos, DingDing dingDing, CoreAPIHttpService coreAPIHttpService, AzureStorageFactory azureStorage
  66. , AzureRedisFactory azureRedis, IHttpClientFactory httpClient, IOptionsSnapshot<Option> option,
  67. IConfiguration configuration, BackgroundWorkerQueue backgroundWorkerQueue)
  68. {
  69. _azureCosmos = azureCosmos;
  70. _dingDing = dingDing;
  71. _azureStorage = azureStorage;
  72. _azureRedis = azureRedis;
  73. _httpClient = httpClient;
  74. _coreAPIHttpService = coreAPIHttpService;
  75. _option = option?.Value;
  76. _configuration = configuration;
  77. _backgroundWorkerQueue = backgroundWorkerQueue;
  78. }
  79. /// <summary>
  80. /// </summary>
  81. /// <param name="req"></param>
  82. /// <param name="log"></param>
  83. /// <returns></returns>
  84. [Function("upsert-student-portrait")]
  85. public async Task<HttpResponseData> UpsertStudentPortrait([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  86. {
  87. string data = await new StreamReader(req.Body).ReadToEndAsync();
  88. var json = JsonDocument.Parse(data).RootElement;
  89. var response = req.CreateResponse(HttpStatusCode.OK);
  90. var responseData = await OpenApiService.UpsertStudentPortrait(_azureCosmos, _dingDing,_azureRedis, json);
  91. await response.WriteAsJsonAsync(new {data = responseData });
  92. return response;
  93. }
  94. /// <summary>
  95. /// </summary>
  96. /// <param name="req"></param>
  97. /// <param name="log"></param>
  98. /// <returns></returns>
  99. [Function("system-info-function")]
  100. public async Task<HttpResponseData> SystemInfo([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  101. {
  102. var response = req.CreateResponse(HttpStatusCode.OK);
  103. Type attr = this.GetType();
  104. string currentDirectory = Path.GetDirectoryName(attr.Assembly.Location);
  105. Assembly assembly = Assembly.LoadFrom($"{currentDirectory}\\TEAMModelOS.FunctionV4.dll");
  106. var description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
  107. //var v1 = Assembly.GetEntryAssembly().GetName().Version;
  108. //var v2 = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
  109. // var description = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
  110. var version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
  111. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  112. //Console.WriteLine($"Assembly.GetEntryAssembly().GetName().Version: " +
  113. // $"{Assembly.GetEntryAssembly().GetName().Version}");5.2107.12.1
  114. //Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version:" +
  115. // $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version}");5.2107.12.1
  116. //Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion:" +
  117. // $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}");5.2107.12
  118. await response.WriteAsJsonAsync(new { version, description, nowtime });
  119. return response;
  120. }
  121. /// <summary>
  122. /// 空间不足发送通知
  123. /// </summary>
  124. /// <param name="req"></param>
  125. /// <param name="log"></param>
  126. /// <returns></returns>
  127. [Function("surplus-space-notify")]
  128. public async Task<HttpResponseData> SurplusSpaceNotify([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  129. var response = req.CreateResponse(HttpStatusCode.OK);
  130. string msg = "";
  131. _backgroundWorkerQueue.QueueBackgroundWorkItem(async token =>
  132. {
  133. try
  134. {
  135. string data = await new StreamReader(req.Body).ReadToEndAsync();
  136. var json = JsonDocument.Parse(data).RootElement;
  137. json.TryGetProperty("name", out JsonElement _name);
  138. json.TryGetProperty("scope", out JsonElement _scope);
  139. json.TryGetProperty("percent", out JsonElement _percent);
  140. double percent = _percent.GetDouble();
  141. string name = _name.ToString();
  142. string scope = _scope.ToString();
  143. int tag = 11;
  144. if (percent <= 10 && percent > 5)
  145. {
  146. tag = 10;
  147. }
  148. else if (percent <= 5 && percent > 0)
  149. {
  150. tag = 5;
  151. }
  152. else if (percent <= 0)
  153. {
  154. tag = 0;
  155. }
  156. List<IdNameCode> ids = new List<IdNameCode>();
  157. Teacher teacher = null;
  158. School school = null;
  159. if (scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  160. {
  161. school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(name, new PartitionKey("Base"));
  162. string sql = $"select value c from c where c.code='Teacher-{name}' and c.status='join' and array_contains(c.roles,'admin') ";
  163. List<SchoolTeacher> adminTeachers = new List<SchoolTeacher>();
  164. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  165. .GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{name}") }))
  166. {
  167. adminTeachers.Add(item);
  168. }
  169. if (adminTeachers.IsNotEmpty())
  170. {
  171. string sqlAdmin = $"select c.id,c.lang as code ,c.name from c where c.id in ({string.Join(",", adminTeachers.Select(z => $"'{z.id}'"))}) ";
  172. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  173. .GetItemQueryIterator<IdNameCode>(queryText: sqlAdmin, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  174. {
  175. ids.Add(item);
  176. }
  177. }
  178. }
  179. else
  180. {
  181. teacher= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(name, new PartitionKey("Base"));
  182. ids.Add(new IdNameCode
  183. {
  184. id = teacher.id,
  185. name = teacher.name,
  186. code = teacher.lang
  187. });
  188. }
  189. //如果已经扩容请忽略此通知!
  190. string key = scope.Equals("school", StringComparison.OrdinalIgnoreCase) ? $"Blob:Space:School:Notify:{name}" : $"Blob:Space:Private:Notify:{name}";
  191. foreach (var idnamecode in ids)
  192. {
  193. string filed = $"{idnamecode.id}-{tag}";
  194. BlobSpaceNotify? blobSpaceNotify = null;
  195. RedisValue value = await _azureRedis.GetRedisClient(8).HashGetAsync(key, filed);
  196. if (value != default && !value.IsNullOrEmpty)
  197. {
  198. blobSpaceNotify = value.ToString().ToObject<BlobSpaceNotify>();
  199. }
  200. if (tag < 11)
  201. {
  202. if (blobSpaceNotify == null)
  203. {
  204. if ("school".Equals(scope, StringComparison.OrdinalIgnoreCase))
  205. {
  206. _coreAPIHttpService.PushNotify(new List<IdNameCode> { idnamecode }, $"blob-space-school-notify", Constant.NotifyType_IES5_Management,
  207. new Dictionary<string, object> { { "tmdname", idnamecode.name }, { "schoolName", school.name }, { "percent", $"{tag}" }, { "schoolId", $"{school.id}" }, { "tmdid", idnamecode.id } },
  208. $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  209. }
  210. else
  211. {
  212. _coreAPIHttpService.PushNotify(new List<IdNameCode> { idnamecode }, $"blob-space-private-notify", Constant.NotifyType_IES5_Management,
  213. new Dictionary<string, object> { { "tmdname", idnamecode.name }, { "percent", $"{tag}" }, { "tmdid", idnamecode.id } },
  214. $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  215. }
  216. blobSpaceNotify = new BlobSpaceNotify { id = idnamecode.id, tag = tag, containerName = name, scope = scope, notifyIndex = Guid.NewGuid().ToString() };
  217. await _azureRedis.GetRedisClient(8).HashSetAsync(key, filed, blobSpaceNotify.ToJsonString());
  218. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(hours: 7*24, minutes: 0, seconds: 0));
  219. }
  220. else
  221. {
  222. //已经发送过的不在提交
  223. }
  224. }
  225. else
  226. {
  227. if (blobSpaceNotify != null)
  228. {
  229. //撤销
  230. var index = blobSpaceNotify.notifyIndex;
  231. await _azureRedis.GetRedisClient(8).HashDeleteAsync(key, filed);
  232. _coreAPIHttpService.CancelNotify(index, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration);
  233. }
  234. }
  235. }
  236. }
  237. catch (Exception ex)
  238. {
  239. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},空间不足,通知发送处理异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  240. }
  241. });
  242. return response;
  243. }
  244. /// <summary>
  245. /// 区级艺术评价变更,异步同步已开启数据同步的学校。
  246. /// </summary>
  247. /// <param name="req"></param>
  248. /// <param name="log"></param>
  249. /// <returns></returns>
  250. [Function("area-artsetting-change")]
  251. public async Task<HttpResponseData> AreaArtSettingChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  252. var response = req.CreateResponse(HttpStatusCode.OK);
  253. string msg = "";
  254. try {
  255. string data = await new StreamReader(req.Body).ReadToEndAsync();
  256. var json = JsonDocument.Parse(data).RootElement;
  257. json.TryGetProperty("areaId", out JsonElement _areaId);
  258. string schoolSQL = $"select value c from c where c.areaId='{_areaId}'";
  259. List<School> schools = new List<School>();
  260. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  261. .GetItemQueryIterator<School>(queryText: schoolSQL, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  262. {
  263. schools.Add(item);
  264. }
  265. ArtSetting artSetting = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<ArtSetting>($"{_areaId}", new PartitionKey("ArtSetting"));
  266. foreach (var school in schools)
  267. {
  268. msg = school.ToJsonString();
  269. List<Period> periods = new List<Period>();
  270. var hastype_period = school.period.Where(p => !string.IsNullOrWhiteSpace(p.periodType));
  271. if (hastype_period.Any())
  272. {
  273. periods.AddRange(hastype_period);
  274. }
  275. var nottype_period = school.period.Where(p => string.IsNullOrWhiteSpace(p.periodType));
  276. if (nottype_period!=null && nottype_period.Count()>0)
  277. {
  278. foreach (var period in nottype_period)
  279. {
  280. if (period.name.Contains("小学"))
  281. {
  282. period.periodType= "primary";
  283. }
  284. if (period.name.Contains("初中"))
  285. {
  286. period.periodType = "junior";
  287. }
  288. if (period.name.Contains("高中"))
  289. {
  290. period.periodType = "senior";
  291. }
  292. if (string.IsNullOrWhiteSpace(period.periodType) && school.period.Count == 1)
  293. {
  294. if (school.name.Contains("小学"))
  295. {
  296. period.periodType = "primary";
  297. }
  298. if (school.name.Contains("初中"))
  299. {
  300. period.periodType = "junior";
  301. }
  302. if (school.name.Contains("高中"))
  303. {
  304. period.periodType = "senior";
  305. }
  306. }
  307. if (!string.IsNullOrWhiteSpace(period.periodType))
  308. {
  309. periods.Add(period);
  310. }
  311. }
  312. }
  313. foreach (var period in periods)
  314. {
  315. var dimension = artSetting.dimensions.FindAll(x => x.type.Intersect(new List<string> { period.periodType }).Any());
  316. var bindIds = period.subjects.Where(s => !string.IsNullOrWhiteSpace(s.bindId)).Select(x => x.bindId);
  317. //该学段未同步学科的。
  318. var unBindIds = dimension.Where(z => !string.IsNullOrWhiteSpace(z.subjectBind)).Select(x => x.subjectBind).ToHashSet().Except(bindIds);
  319. if (unBindIds.Any() && unBindIds.Count()>0)
  320. {
  321. //尝试寻找同名学科且没有设置bindId的
  322. foreach (var unBindId in unBindIds)
  323. {
  324. var subjects = artSetting.dimensions.FindAll(d => !string.IsNullOrWhiteSpace(d.subjectBind) && !string.IsNullOrWhiteSpace(d.subject) && d.subjectBind.Equals(unBindId))?.Select(m => m.subject);
  325. if (subjects != null)
  326. {
  327. foreach (var subject in subjects)
  328. {
  329. //获取同名学科,且没绑定的
  330. var sub = period.subjects.FindAll(sub => sub.name.Contains(subject) && string.IsNullOrWhiteSpace(sub.bindId));
  331. if (sub.IsNotEmpty())
  332. {
  333. sub[0].bindId = unBindId;
  334. }
  335. else
  336. {
  337. period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subject, bindId = unBindId, type = 1 });
  338. }
  339. break;
  340. }
  341. }
  342. }
  343. }
  344. var period_subjects = period.subjects.Where(s => !string.IsNullOrWhiteSpace(s.bindId));
  345. foreach (var subject in period_subjects)
  346. {
  347. var dim = dimension.Where(x => x.subjectBind.Equals(subject.bindId));
  348. if (dim.Any())
  349. {
  350. Knowledge old = null;
  351. string sql = $"select value(c) from c where c.periodId = '{period.id}'";
  352. string pk = $"Knowledge-{school.id}-{subject.id}";
  353. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").
  354. GetItemQueryIterator<Knowledge>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(pk) }))
  355. {
  356. old = item;
  357. break;
  358. }
  359. //同步知识块。
  360. if (old != null)
  361. {
  362. bool change = false;
  363. //如果之前的是1 来源于区级,后面因区级删除,应该还原为0。
  364. var oldBlocks = old.blocks.Select(x => x.name).ToHashSet();
  365. var dimBlocks = dim.SelectMany(d => d.blocks);
  366. //增加的
  367. var addBlocks = dimBlocks.Except(oldBlocks);
  368. //减少的
  369. var cutBlocks = oldBlocks.Except(dimBlocks);
  370. foreach (var add in addBlocks)
  371. {
  372. old.blocks.Add(new Block { name = add, source = 1 });
  373. change = true;
  374. }
  375. //减少的还原为0
  376. if (cutBlocks.Any())
  377. {
  378. old.blocks.ForEach(ob => {
  379. if (cutBlocks.Contains(ob.name))
  380. {
  381. ob.source = 0;
  382. change = true;
  383. }
  384. });
  385. }
  386. foreach (var db in dimBlocks) {
  387. old.blocks.ForEach(ob => {
  388. if (db.Equals(ob.name))
  389. {
  390. ob.source = 1;
  391. change = true;
  392. }
  393. });
  394. }
  395. if (change)
  396. {
  397. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(old, old.id, new PartitionKey(old.code));
  398. }
  399. var count = new { pcount = old.points != null ? old.points.Count : 0, bcount = old.blocks != null ? old.blocks.Count : 0 };
  400. //处理知识点,知识块计数问题
  401. await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{old.owner}-{old.subjectId}", old.periodId, count.ToJsonString());
  402. }
  403. else
  404. {
  405. var blocks = dim.SelectMany(x => x.blocks).Select(bs => new Block { name = bs, source = 1 });
  406. if (blocks.Any())
  407. {
  408. var _new = new Knowledge
  409. {
  410. id = Guid.NewGuid().ToString(),
  411. pk = "Knowledge",
  412. code = pk,
  413. owner = school.id,
  414. periodId = period.id,
  415. subjectId = subject.id,
  416. blocks = blocks.ToList()
  417. };
  418. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(_new, new PartitionKey(_new.code));
  419. var count = new { pcount = _new.points != null ? _new.points.Count : 0, bcount = _new.blocks != null ? _new.blocks.Count : 0 };
  420. //处理知识点,知识块计数问题
  421. await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{_new.owner}-{_new.subjectId}", _new.periodId, count.ToJsonString());
  422. }
  423. }
  424. }
  425. }
  426. }
  427. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(school, school.id, new PartitionKey(school.code));
  428. }
  429. return response;
  430. } catch (Exception ex) {
  431. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},area-artsetting-change,{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  432. }
  433. return response;
  434. }
  435. /// <summary>
  436. /// 行政班,学生毕业状态变更。
  437. /// </summary>
  438. /// <param name="req"></param>
  439. /// <param name="log"></param>
  440. /// <returns></returns>
  441. [Function("graduate-change")]
  442. public async Task<HttpResponseData> GraduateChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  443. var response = req.CreateResponse(HttpStatusCode.OK);
  444. dynamic jsondata =new ExpandoObject() ;
  445. try {
  446. string data = await new StreamReader(req.Body).ReadToEndAsync();
  447. var json = JsonDocument.Parse(data).RootElement;
  448. jsondata = json;
  449. //await _dingDing.SendBotMsg( "毕业状态变更:"+json.ToJsonString(), GroupNames.成都开发測試群組);
  450. string schoolId = null;
  451. if (json.TryGetProperty("schoolId", out JsonElement _schoolId))
  452. {
  453. schoolId = $"{_schoolId}";
  454. }
  455. if (string.IsNullOrEmpty(schoolId))
  456. {
  457. return response;
  458. }
  459. //计算毕业的
  460. if (json.TryGetProperty("graduate_classes", out JsonElement _graduate_classes))
  461. {
  462. List<Class> graduate_classes = _graduate_classes.ToObject<List<Class>>();
  463. if (graduate_classes.IsNotEmpty())
  464. {
  465. var ids = graduate_classes.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => $"'{x.id}'");
  466. List<Student> students = new List<Student>();
  467. string sql = $"select value c from c where (c.graduate = 0 or IS_DEFINED(c.graduate) = false) and c.classId in ({string.Join(",", ids)})";
  468. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student)
  469. .GetItemQueryIterator<Student>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  470. {
  471. item.graduate = 1;
  472. students.Add(item);
  473. }
  474. foreach (var item in students)
  475. {
  476. item.graduate = 1;
  477. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Student>(item, item.id, new PartitionKey($"Base-{schoolId}"));
  478. }
  479. foreach (var item in graduate_classes)
  480. {
  481. item.graduate = 1;
  482. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<Class>(item, item.id, new PartitionKey($"Class-{schoolId}"));
  483. }
  484. }
  485. }
  486. //未毕业的
  487. if (json.TryGetProperty("cancel_graduate_classes", out JsonElement _cancel_graduate_classes))
  488. {
  489. List<Class> cancel_graduate_classes = _cancel_graduate_classes.ToObject<List<Class>>();
  490. if (cancel_graduate_classes.IsNotEmpty())
  491. {
  492. var ids = cancel_graduate_classes.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => $"'{x.id}'");
  493. List<Student> students = new List<Student>();
  494. string sql = $"select value c from c where c.graduate =1 and c.classId in ({string.Join(",", ids)})";
  495. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student)
  496. .GetItemQueryIterator<Student>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  497. {
  498. item.graduate = 0;
  499. students.Add(item);
  500. }
  501. foreach (var item in students)
  502. {
  503. item.graduate = 0;
  504. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Student>(item, item.id, new PartitionKey($"Base-{schoolId}"));
  505. }
  506. foreach (var item in cancel_graduate_classes)
  507. {
  508. item.graduate = 0;
  509. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<Class>(item, item.id, new PartitionKey($"Class-{schoolId}"));
  510. }
  511. }
  512. }
  513. } catch (Exception ex) {
  514. await _dingDing.SendBotMsg($"graduate-change,{ex.Message}\n{ex.StackTrace}\n{jsondata.ToJsonString()}",GroupNames.醍摩豆服務運維群組);
  515. }
  516. return response;
  517. }
  518. /// <summary>
  519. /// 数据推送接口
  520. /// </summary>
  521. /// <param name="req"></param>
  522. /// <param name="log"></param>
  523. /// <returns></returns>
  524. [Function("lesson-tag-change")]
  525. public async Task<HttpResponseData> LessonTagChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  526. var response = req.CreateResponse(HttpStatusCode.OK);
  527. string data = await new StreamReader(req.Body).ReadToEndAsync();
  528. var json = JsonDocument.Parse(data).RootElement;
  529. List<TagOldNew> old_new = null;
  530. string school = null;
  531. if (json.TryGetProperty("school", out JsonElement _school))
  532. {
  533. school = _school.GetString();
  534. }
  535. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  536. {
  537. old_new = _old_new.ToObject<List<TagOldNew>>();
  538. }
  539. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  540. {
  541. foreach (var on in old_new)
  542. {
  543. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  544. string sql = $"select value(c) from c where array_contains(c.category,'{on._old}') ";
  545. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonRecord>
  546. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{_school}") }))
  547. {
  548. lessonRecords.Add(item);
  549. }
  550. lessonRecords.ForEach(item =>
  551. {
  552. //修改标签
  553. if (!string.IsNullOrWhiteSpace(on._new))
  554. {
  555. for (int i = 0; i < item.category.Count; i++)
  556. {
  557. if (item.category[i].Equals(on._old))
  558. {
  559. item.category[i] = on._new;
  560. }
  561. }
  562. }
  563. else
  564. {
  565. //表示删除标签
  566. item.category.RemoveAll(x => x.Equals(on._old));
  567. }
  568. });
  569. foreach (var item in lessonRecords)
  570. {
  571. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  572. }
  573. }
  574. }
  575. await response.WriteAsJsonAsync(new { data = json });
  576. return response;
  577. }
  578. /// <summary>
  579. /// 数据推送接口
  580. /// </summary>
  581. /// <param name="req"></param>
  582. /// <param name="log"></param>
  583. /// <returns></returns>
  584. [Function("knowledge-change")]
  585. public async Task<HttpResponseData> KnowledgeChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  586. {
  587. var response = req.CreateResponse(HttpStatusCode.OK);
  588. string data = await new StreamReader(req.Body).ReadToEndAsync();
  589. var json = JsonDocument.Parse(data).RootElement;
  590. List<TagOldNew> old_new = null;
  591. string school = null;
  592. if (json.TryGetProperty("school", out JsonElement _school))
  593. {
  594. school = _school.GetString();
  595. }
  596. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  597. {
  598. old_new = _old_new.ToObject<List<TagOldNew>>();
  599. }
  600. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  601. {
  602. foreach (var on in old_new)
  603. {
  604. List<ItemInfo> items = new List<ItemInfo>();
  605. string sql = $"select value(c) from c where array_contains(c.knowledge,'{on._old}') ";
  606. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>
  607. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{_school}") }))
  608. {
  609. items.Add(item);
  610. }
  611. items.ForEach(item =>
  612. {
  613. //修改知识点
  614. if (!string.IsNullOrEmpty(on._new))
  615. {
  616. for (int i = 0; i < item.knowledge.Count; i++)
  617. {
  618. if (item.knowledge[i].Equals(on._old))
  619. {
  620. item.knowledge[i] = on._new;
  621. }
  622. }
  623. }
  624. else
  625. {
  626. //表示删除知识点
  627. item.knowledge.RemoveAll(x => x.Equals(on._old));
  628. }
  629. });
  630. foreach (var item in items)
  631. {
  632. ItemBlob itemBlob = null;
  633. try
  634. {
  635. BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"{school}").GetBlobClient($"/item/{item.id}/{item.id}.json").DownloadAsync();
  636. if (blobDownloadResult != null)
  637. {
  638. var blob = JsonDocument.Parse(blobDownloadResult.Content);
  639. itemBlob = blob.RootElement.ToObject<ItemBlob>();
  640. itemBlob.exercise.knowledge = item.knowledge;
  641. await _azureStorage.GetBlobContainerClient($"{school}").UploadFileByContainer(itemBlob.ToJsonString(), "item", $"{item.id}/{item.id}.json", true);
  642. }
  643. }
  644. catch (Exception ex)
  645. {
  646. itemBlob = null;
  647. }
  648. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  649. }
  650. }
  651. }
  652. await response.WriteAsJsonAsync(new { data = json });
  653. return response;
  654. }
  655. /// <summary>
  656. /// 在线人数记录
  657. /// </summary>
  658. /// <param name="msg"></param>
  659. /// <returns></returns>
  660. [Function("online-record")]
  661. public async Task<HttpResponseData> OnlineRecord([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  662. {
  663. var response = req.CreateResponse(HttpStatusCode.OK);
  664. return response;
  665. string data = await new StreamReader(req.Body).ReadToEndAsync();
  666. var json = JsonDocument.Parse(data).RootElement;
  667. try
  668. {
  669. string school = null;
  670. string scope = null;
  671. string id = null;
  672. string ip = null;
  673. int expire = 1;
  674. if (json.TryGetProperty("school", out JsonElement _school))
  675. school = _school.GetString();
  676. if (json.TryGetProperty("scope", out JsonElement _scope))
  677. scope = _scope.GetString();
  678. if (json.TryGetProperty("id", out JsonElement _id))
  679. id = _id.GetString();
  680. if (json.TryGetProperty("ip", out JsonElement _ip))
  681. ip = _ip.GetString();
  682. if (json.TryGetProperty("expire", out JsonElement _expire))
  683. expire = _expire.GetInt32();
  684. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  685. var cosmosClient = _azureCosmos.GetCosmosClient();
  686. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  687. var dateHour = dateTime.ToString("yyyyMMddHH"); //获取当天的小时
  688. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  689. var dateMonth = dateTime.ToString("yyyyMM");//获取当月的日期
  690. var currentHour = dateTime.Hour; //当前小时
  691. var currentDay = dateTime.Day; //当前天
  692. long Expire = dateTime.AddHours(expire).ToUnixTimeMilliseconds(); //token到期时间
  693. long now = dateTime.ToUnixTimeMilliseconds(); //当前时间戳
  694. DateTime hour = DateTime.UtcNow.AddHours(25); //25小时到期
  695. DateTime month = DateTime.UtcNow.AddDays(32); //一个月到期
  696. var delTbHour = dateTime.AddHours(-168).ToString("yyyyMMddHH"); //168小时前
  697. var delTbDay = dateTime.AddDays(-180).ToString("yyyyMMdd"); //180天前
  698. switch (scope)
  699. {
  700. case "teacher":
  701. try
  702. {
  703. //Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  704. //teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  705. //await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  706. }
  707. catch { }
  708. break;
  709. case "student":
  710. try
  711. {
  712. // Student student = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
  713. //student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  714. //await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<Student>(student, student.id, new PartitionKey($"Base-{school}"));
  715. string key = $"Login:School:{school}:student-day:{dateDay}";
  716. //记录一个学校每天每个学生登录的次数
  717. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(key, id, 1);
  718. //获取key到期的时间
  719. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, hour); //设置到期时间25小时
  720. }
  721. catch (Exception ex ){ await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組); }
  722. break;
  723. case "tmduser":
  724. try
  725. {
  726. //TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  727. //tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  728. //await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
  729. }
  730. catch { }
  731. break;
  732. }
  733. //天
  734. SortedSetEntry[] dayCnt = null;
  735. //月
  736. SortedSetEntry[] monthCnt = null;
  737. try
  738. {
  739. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateDay}", $"{currentHour}", 1);//一天24小时 小时为单位
  740. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateMonth}", $"{currentDay}", 1); //一天的累计 天为单位
  741. var resDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateDay}");
  742. if (resDay == null)
  743. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateDay}", hour); //设置到期时间
  744. var rspMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateMonth}");
  745. if (rspMonth == null)
  746. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateMonth}", month); //设置到期时间
  747. //保存当前小时统计
  748. dayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateDay}");
  749. //保存当前的统计数据
  750. monthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateMonth}");
  751. }
  752. catch { }
  753. if (dayCnt != null && dayCnt.Length > 0)
  754. {
  755. List<HourLogin> hourLogins = new();
  756. foreach (var dCnt in dayCnt)
  757. {
  758. if (((int)dCnt.Element) == currentHour)
  759. {
  760. var tphourLogins = await table.QueryWhereString<HourLogin>($"PartitionKey eq 'HourLogin' and RowKey eq '{dateHour}'");
  761. if (tphourLogins.Count > 0)
  762. {
  763. foreach (var hourLogin in tphourLogins)
  764. {
  765. if (scope.Equals("teacher"))
  766. hourLogin.Teacher = (int)dCnt.Score;
  767. else if (scope.Equals("student"))
  768. hourLogin.Student = (int)dCnt.Score;
  769. else
  770. hourLogin.TmdUser = (int)dCnt.Score;
  771. hourLogins.Add(hourLogin);
  772. }
  773. }
  774. else
  775. {
  776. HourLogin hourLogin = new() { PartitionKey = $"HourLogin", RowKey = dateHour, Hour = currentHour };
  777. if (scope.Equals("teacher"))
  778. {
  779. hourLogin.Teacher = 1;
  780. hourLogin.Student = 0;
  781. hourLogin.TmdUser = 0;
  782. }
  783. else if (scope.Equals("student"))
  784. {
  785. hourLogin.Teacher = 0;
  786. hourLogin.Student = 1;
  787. hourLogin.TmdUser = 0;
  788. }
  789. else
  790. {
  791. hourLogin.Teacher = 0;
  792. hourLogin.Student = 0;
  793. hourLogin.TmdUser = 1;
  794. }
  795. hourLogins.Add(hourLogin);
  796. }
  797. }
  798. }
  799. await table.SaveOrUpdateAll(hourLogins); //保存和更新保存当前小时登录次数
  800. }
  801. if (monthCnt != null && monthCnt.Length > 0)
  802. {
  803. List<DayLogin> dayLogins = new();
  804. foreach (var mCnt in monthCnt)
  805. {
  806. if (((int)mCnt.Element) == currentDay)
  807. {
  808. //保存当天的峰值
  809. var tbDays = await table.QueryWhereString<DayLogin>($"PartitionKey eq 'DayLogin' and RowKey eq '{dateDay}'");
  810. if (tbDays.Count > 0)
  811. {
  812. foreach (var dayLogin in tbDays)
  813. {
  814. if (scope.Equals("teacher"))
  815. dayLogin.Teacher = (int)mCnt.Score;
  816. else if (scope.Equals("student"))
  817. dayLogin.Student = (int)mCnt.Score;
  818. else
  819. dayLogin.TmdUser = (int)mCnt.Score;
  820. dayLogins.Add(dayLogin);
  821. }
  822. }
  823. else
  824. {
  825. //保存当月每天的峰值
  826. DayLogin dayLogin = new() { PartitionKey = $"DayLogin", RowKey = dateDay, Day = currentDay };
  827. if (scope.Equals("teacher"))
  828. {
  829. dayLogin.Teacher = 1;
  830. dayLogin.Student = 0;
  831. dayLogin.TmdUser = 0;
  832. }
  833. else if (scope.Equals("student"))
  834. {
  835. dayLogin.Teacher = 0;
  836. dayLogin.Student = 1;
  837. dayLogin.TmdUser = 0;
  838. }
  839. else
  840. {
  841. dayLogin.Teacher = 0;
  842. dayLogin.Student = 0;
  843. dayLogin.TmdUser = 1;
  844. }
  845. dayLogins.Add(dayLogin);
  846. }
  847. }
  848. }
  849. await table.SaveOrUpdateAll(dayLogins);// 保存当月每天在线数据
  850. }
  851. string tbHourSql = $"PartitionKey eq 'HourLogin' and RowKey le '{delTbHour}'";
  852. string tbDaySql = $"PartitionKey eq 'DayLogin' and RowKey le '{delTbDay}'";
  853. try
  854. {
  855. await table.DeleteStringWhere<HourLogin>(rowKey: tbHourSql); //删除168小时前的数据
  856. await table.DeleteStringWhere<DayLogin>(rowKey: tbDaySql); //删除180天前的数据
  857. }
  858. catch { }
  859. if (!string.IsNullOrWhiteSpace(school))
  860. {
  861. //天
  862. SortedSetEntry[] scDayCnt = null;
  863. //月
  864. SortedSetEntry[] scMonthCnt = null;
  865. try
  866. {
  867. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateDay}", $"{currentHour}", 1);//当天当前小时在线人加1
  868. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateMonth}", $"{currentDay}", 1); //当天的在线加1
  869. var reScDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateDay}");
  870. if (reScDay == null)
  871. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateDay}", hour); //设置到期时间
  872. var reScMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateMonth}");
  873. if (reScMonth == null)
  874. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateMonth}", month); //设置到期时间
  875. //保存学校当天每小时的
  876. scDayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateDay}");
  877. //学校天峰值
  878. scMonthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateMonth}");
  879. }
  880. catch { }
  881. if (scDayCnt != null && scDayCnt.Length > 0)
  882. {
  883. List<HourLoginSchool> hourLoginSchools = new();
  884. foreach (var scDCnt in scDayCnt)
  885. {
  886. if (((int)scDCnt.Element) == currentHour)
  887. {
  888. var tmpHour = await table.QueryWhereString<HourLoginSchool>($"PartitionKey eq 'HourLogin-{school}' and RowKey eq '{dateHour}'");
  889. if (tmpHour.Count > 0)
  890. {
  891. foreach (var hLoginSc in tmpHour)
  892. {
  893. if (scope.Equals("teacher"))
  894. hLoginSc.Teacher = (int)scDCnt.Score;
  895. else if (scope.Equals("student"))
  896. hLoginSc.Student = (int)scDCnt.Score;
  897. else
  898. hLoginSc.TmdUser = (int)scDCnt.Score;
  899. hourLoginSchools.Add(hLoginSc);
  900. }
  901. }
  902. else
  903. {
  904. //学校小时峰值
  905. HourLoginSchool hourLoginSc = new() { PartitionKey = $"HourLogin-{school}", RowKey = dateHour, Hour = currentHour, School = school };
  906. if (scope.Equals("teacher"))
  907. {
  908. hourLoginSc.Teacher = 1;
  909. hourLoginSc.Student = 0;
  910. hourLoginSc.TmdUser = 0;
  911. }
  912. else if (scope.Equals("student"))
  913. {
  914. hourLoginSc.Teacher = 0;
  915. hourLoginSc.Student = 1;
  916. hourLoginSc.TmdUser = 0;
  917. }
  918. else
  919. {
  920. hourLoginSc.Teacher = 0;
  921. hourLoginSc.Student = 0;
  922. hourLoginSc.TmdUser = 1;
  923. }
  924. hourLoginSchools.Add(hourLoginSc);
  925. }
  926. }
  927. }
  928. await table.SaveOrUpdateAll(hourLoginSchools);
  929. }
  930. if (scMonthCnt != null && scMonthCnt.Length > 0)
  931. {
  932. List<DayLoginSchool> DayLoginSchools = new();
  933. foreach (var scMCnt in scMonthCnt)
  934. {
  935. if (((int)scMCnt.Element) == currentDay)
  936. {
  937. var tempDays = await table.QueryWhereString<DayLoginSchool>($"PartitionKey eq 'DayLogin-{school}' and RowKey eq '{dateDay}'");
  938. if (tempDays.Count > 0)
  939. {
  940. foreach (var dLoginSc in tempDays)
  941. {
  942. if (scope.Equals("teacher"))
  943. dLoginSc.Teacher = (int)scMCnt.Score;
  944. else if (scope.Equals("student"))
  945. dLoginSc.Student = (int)scMCnt.Score;
  946. else
  947. dLoginSc.TmdUser = (int)scMCnt.Score;
  948. DayLoginSchools.Add(dLoginSc);
  949. }
  950. }
  951. else
  952. {
  953. //学校天峰值
  954. DayLoginSchool dayLoginSc = new() { PartitionKey = $"DayLogin-{school}", RowKey = dateDay, Day = currentDay, School = school };
  955. if (scope.Equals("teacher"))
  956. {
  957. dayLoginSc.Teacher = 1;
  958. dayLoginSc.Student = 0;
  959. dayLoginSc.TmdUser = 0;
  960. }
  961. else if (scope.Equals("student"))
  962. {
  963. dayLoginSc.Teacher = 0;
  964. dayLoginSc.Student = 1;
  965. dayLoginSc.TmdUser = 0;
  966. }
  967. else
  968. {
  969. dayLoginSc.Teacher = 0;
  970. dayLoginSc.Student = 0;
  971. dayLoginSc.TmdUser = 1;
  972. }
  973. DayLoginSchools.Add(dayLoginSc);
  974. }
  975. }
  976. }
  977. await table.SaveOrUpdateAll(DayLoginSchools);//保存学校当月在线数据
  978. }
  979. string tbScHourSql = $"PartitionKey eq 'HourLogin-{school}' and RowKey le '{delTbHour}'";
  980. List<HourLogin> scHourLog = await table.QueryWhereString<HourLogin>(tbScHourSql);
  981. if (scHourLog.Count > 0)
  982. try
  983. {
  984. //await table.DeleteStringWhere<HourLogin>(tbScHourSql); //删除学校168小时前的数据
  985. await table.DeleteAll(scHourLog);
  986. }
  987. catch { }
  988. string tbScDaySql = $"PartitionKey eq 'DayLogin-{school}' and RowKey le '{delTbDay}'";
  989. List<DayLogin> scDayLog = await table.QueryWhereString<DayLogin>(tbScDaySql);
  990. if (scDayLog.Count > 0)
  991. try
  992. {
  993. //await table.DeleteStringWhere<DayLogin>(tbScDaySql); //删除学校180天前的数据
  994. await table.DeleteAll(scDayLog);
  995. }
  996. catch { }
  997. }
  998. await response.WriteAsJsonAsync(new { data = json });
  999. return response;
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-online-record 人数记录异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1004. await response.WriteAsJsonAsync(new { data = json });
  1005. return response;
  1006. }
  1007. }
  1008. /// <summary>
  1009. /// 艺术评测报告生成
  1010. /// </summary>
  1011. /// <param name="msg"></param>
  1012. /// <returns></returns>
  1013. //[Function("gen-art-pdf")]
  1014. public async Task<HttpResponseData> GenArtPDF([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  1015. var response = req.CreateResponse(HttpStatusCode.OK);
  1016. try {
  1017. string data = await new StreamReader(req.Body).ReadToEndAsync();
  1018. var json = JsonDocument.Parse(data).RootElement;
  1019. json.TryGetProperty("studentPdfs", out JsonElement _studentPdfs);
  1020. json.TryGetProperty("artResults", out JsonElement _artResults);
  1021. json.TryGetProperty("schoolCode", out JsonElement _schoolCode);
  1022. List<ArtStudentPdf> studentPdfs = _studentPdfs.Deserialize<List<ArtStudentPdf>>();
  1023. List<StudentArtResult> artResults = _artResults.Deserialize<List<StudentArtResult>>();
  1024. List<Task<string>> uploads = new List<Task<string>>();
  1025. studentPdfs.ForEach(x => {
  1026. x.blob = $"art/{x.artId}/report/{x.studentId}.json";
  1027. uploads.Add(_azureStorage.GetBlobContainerClient($"{_schoolCode}").UploadFileByContainer(x.ToJsonString(), "art", $"{x.artId}/report/{x.studentId}.json", true));
  1028. });
  1029. var uploadJsonUrls = await Task.WhenAll(uploads);
  1030. var list = uploadJsonUrls.ToList();
  1031. List<string> urls = new List<string>();
  1032. (string uri, string sas) = _azureStorage.GetBlobContainerSAS($"{_schoolCode}", Azure.Storage.Sas.BlobContainerSasPermissions.Read);
  1033. studentPdfs.ForEach(x => {
  1034. string atrUrl = "https://teammodelos.blob.core.chinacloudapi.cn/0-public/art-report-template/report.html";
  1035. var s = _azureStorage.GetBlobSAS($"{_schoolCode}", x.blob, BlobSasPermissions.Read);
  1036. s = $"{HttpUtility.UrlEncode($"{s}", Encoding.UTF8)}";
  1037. string url = $"{atrUrl}?url={s}&pdfpath={x.artId}/report/{x.studentId}";
  1038. urls.Add(url);
  1039. //var a = list.Find(l => l.Contains(x.studentId));
  1040. //if (a != null) {
  1041. // a = $"{HttpUtility.UrlEncode($"{a}?{sas}", Encoding.UTF8)}";
  1042. // string url = $"{atrUrl}?url={a}&pdfpath={x.artId}/report/{x.studentId}";
  1043. // urls.Add(url);
  1044. //}
  1045. });
  1046. string env = "release";
  1047. if (Environment.GetEnvironmentVariable("Option:Location").Contains("Test", StringComparison.CurrentCultureIgnoreCase) ||
  1048. Environment.GetEnvironmentVariable("Option:Location").Contains("Dep", StringComparison.CurrentCultureIgnoreCase))
  1049. {
  1050. env = "develop";
  1051. }
  1052. int psize = 20;
  1053. List<string> resUrls = new List<string>();
  1054. if (urls.Count <= psize)
  1055. {
  1056. var screenshot = new ScreenshotDto
  1057. {
  1058. width = 1080,
  1059. height = 1920,
  1060. urls = urls,
  1061. fileNameKey = "pdfpath",
  1062. cnt = $"{_schoolCode}",
  1063. root = "art",
  1064. pagesize = 5,
  1065. env = env
  1066. };
  1067. var st = screenshot.ToJsonString();
  1068. await _dingDing.SendBotMsg($"艺术评测报告生成中:\n{st}", GroupNames.成都开发測試群組);
  1069. var httpResponse = await _httpClient.CreateClient().PostAsJsonAsync("http://cdhabook.teammodel.cn:8805/screen/screenshot-pdf",
  1070. screenshot
  1071. );
  1072. if (httpResponse.StatusCode == HttpStatusCode.OK)
  1073. {
  1074. JsonElement json_res = await httpResponse.Content.ReadFromJsonAsync<JsonElement>();
  1075. resUrls = json_res.GetProperty("urls").Deserialize<List<string>>();
  1076. await UpdatePdfBlob(artResults, resUrls);
  1077. }
  1078. }
  1079. else {
  1080. int pages = (urls.Count + psize) / psize;
  1081. for (int i = 0; i < pages; i++) {
  1082. var lists = urls.Skip(i * psize).Take(psize).ToList();
  1083. var screenshot = new ScreenshotDto
  1084. {
  1085. width = 1080,
  1086. height = 1920,
  1087. urls = lists,
  1088. fileNameKey = "pdfpath",
  1089. cnt = $"{_schoolCode}",
  1090. root = "art",
  1091. pagesize = 5,
  1092. env = env
  1093. };
  1094. //var st = screenshot.ToJsonString();
  1095. // await _dingDing.SendBotMsg($"艺术评测报告生成中:\n{st}", GroupNames.成都开发測試群組);
  1096. var httpResponse = await _httpClient.CreateClient().PostAsJsonAsync("http://cdhabook.teammodel.cn:8805/screen/screenshot-pdf",
  1097. screenshot
  1098. );
  1099. if (httpResponse.StatusCode == HttpStatusCode.OK)
  1100. {
  1101. JsonElement json_res = await httpResponse.Content.ReadFromJsonAsync<JsonElement>();
  1102. resUrls = json_res.GetProperty("urls").Deserialize<List<string>>();
  1103. await UpdatePdfBlob(artResults, resUrls);
  1104. }
  1105. }
  1106. }
  1107. await response.WriteAsJsonAsync(new { data = new { count = studentPdfs.Count, resUrls } });
  1108. } catch (Exception ex) {
  1109. await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1110. }
  1111. return response;
  1112. }
  1113. //https://teammodeltest.blob.core.chinacloudapi.cn/hbcn/art/e864a924-e644-42dc-87c4-e970e6185065/report/202201001.pdf
  1114. private async Task UpdatePdfBlob(List<StudentArtResult> studentArts ,List<string> urls)
  1115. {
  1116. List<Task<ItemResponse<StudentArtResult>>> artResults =new List<Task<ItemResponse<StudentArtResult>>>();
  1117. urls.ForEach(z => {
  1118. var res = studentArts.FindAll(x => z.Contains(x.artId) && z.Contains($"{x.studentId}"));
  1119. if (res.Any()) {
  1120. if (string.IsNullOrWhiteSpace(res[0].blob)) {
  1121. res[0].blob = $"art/{res[0].artId}/report/{res[0].studentId}.pdf";
  1122. artResults.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(res[0], res[0].id, new PartitionKey(res[0].code)));
  1123. }
  1124. }
  1125. });
  1126. if (artResults.Any())
  1127. {
  1128. await Task.WhenAll(artResults);
  1129. }
  1130. }
  1131. public class ScreenshotDto
  1132. {
  1133. public int width { get; set; } = 1920;
  1134. public int height { get; set; } = 1080;
  1135. public string? url { get; set; }
  1136. /// <summary>
  1137. /// 批量地址
  1138. /// </summary>
  1139. public List<string> urls { get; set; } = new List<string>();
  1140. /// <summary>
  1141. /// 提取参数的唯一id作为文件名
  1142. /// </summary>
  1143. public string? fileNameKey { get; set; }
  1144. /// <summary>
  1145. /// 存在哪个容器里
  1146. /// </summary>
  1147. public string? cnt { get; set; }
  1148. public int delay { get; set; }
  1149. public int pagesize { get; set; } = 5;
  1150. public string? root { get; set; }
  1151. public string? env { get; set; } = "release";
  1152. public string? msgId { get; set; }
  1153. }
  1154. }
  1155. }