IESHttpTrigger.cs 66 KB

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