IESHttpTrigger.cs 49 KB

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