IESHttpTrigger.cs 49 KB

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