IESHttpTrigger.cs 46 KB

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