IESHttpTrigger.cs 65 KB

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