IESHttpTrigger.cs 63 KB

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