IESHttpTrigger.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. string data = await new StreamReader(req.Body).ReadToEndAsync();
  79. var json = JsonDocument.Parse(data).RootElement;
  80. json.TryGetProperty("areaId", out JsonElement _areaId);
  81. string schoolSQL = $"select c.id ,c.name ,c.period from c where c.areaId='{_areaId}'";
  82. List<School> schools = new List<School>();
  83. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  84. .GetItemQueryIterator<School>(queryText: schoolSQL, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  85. {
  86. schools.Add(item);
  87. }
  88. ArtSetting artSetting= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<ArtSetting>($"{_areaId}", new PartitionKey());
  89. foreach (var school in schools) {
  90. var periods = school.period.Where(p => !string.IsNullOrWhiteSpace(p.type));
  91. foreach (var period in periods)
  92. {
  93. var dimension = artSetting.dimensions.FindAll(x => x.type.Contains(period.type));
  94. var bindIds = period.subjects.Where(s => !string.IsNullOrWhiteSpace(s.bindId)).Select(x => x.bindId);
  95. //该学段未同步学科的。
  96. var unBindIds = dimension.Where(z => !string.IsNullOrWhiteSpace(z.subjectBind)).Select(x => x.subjectBind).ToHashSet().Except(bindIds);
  97. if (unBindIds.Any())
  98. {
  99. //尝试寻找同名学科且没有设置bindId的
  100. foreach (var unBindId in unBindIds)
  101. {
  102. var subjects = artSetting.dimensions.FindAll(d => !string.IsNullOrWhiteSpace(d.subjectBind) && !string.IsNullOrWhiteSpace(d.subject) && d.subjectBind.Equals(unBindId))?.Select(m => m.subject);
  103. if (subjects != null)
  104. {
  105. foreach (var subject in subjects)
  106. {
  107. //获取同名学科,且没绑定的
  108. var sub = period.subjects.FindAll(sub => sub.name.Equals(subject) && string.IsNullOrWhiteSpace(sub.bindId));
  109. if (sub.IsNotEmpty())
  110. {
  111. sub[0].bindId = unBindId;
  112. }
  113. else
  114. {
  115. period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subject, bindId = unBindId, type = 1 });
  116. }
  117. break;
  118. }
  119. }
  120. }
  121. }
  122. var period_subjects = period.subjects.Where(s => !string.IsNullOrWhiteSpace(s.bindId));
  123. foreach (var subject in period_subjects)
  124. {
  125. var dim= dimension.Where(x => x.subjectBind.Equals(subject.bindId));
  126. if (dim.Any()) {
  127. Knowledge old = null;
  128. string sql = $"select value(c) from c where c.periodId = '{period.id}'";
  129. string pk = $"Knowledge-{school.id}-{subject.id}";
  130. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").
  131. GetItemQueryIterator<Knowledge>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(pk) }))
  132. {
  133. old = item;
  134. break;
  135. }
  136. var blocks = dim.SelectMany(x => x.blocks);
  137. //同步知识块。
  138. if (old != null)
  139. {
  140. }
  141. else {
  142. }
  143. }
  144. }
  145. }
  146. }
  147. return response;
  148. }
  149. /// <summary>
  150. /// 行政班,学生毕业状态变更。
  151. /// </summary>
  152. /// <param name="req"></param>
  153. /// <param name="log"></param>
  154. /// <returns></returns>
  155. [Function("graduate-change")]
  156. public async Task<HttpResponseData> GraduateChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  157. var response = req.CreateResponse(HttpStatusCode.OK);
  158. dynamic jsondata =new ExpandoObject() ;
  159. try {
  160. string data = await new StreamReader(req.Body).ReadToEndAsync();
  161. var json = JsonDocument.Parse(data).RootElement;
  162. jsondata = json;
  163. await _dingDing.SendBotMsg( "毕业状态变更:"+json.ToJsonString(), GroupNames.成都开发測試群組);
  164. string schoolId = null;
  165. if (json.TryGetProperty("schoolId", out JsonElement _schoolId))
  166. {
  167. schoolId = $"{_schoolId}";
  168. }
  169. if (string.IsNullOrEmpty(schoolId))
  170. {
  171. return response;
  172. }
  173. //计算毕业的
  174. if (json.TryGetProperty("graduate_classes", out JsonElement _graduate_classes))
  175. {
  176. List<Class> graduate_classes = _graduate_classes.ToObject<List<Class>>();
  177. if (graduate_classes.IsNotEmpty())
  178. {
  179. var ids = graduate_classes.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => $"'{x.id}'");
  180. List<Student> students = new List<Student>();
  181. string sql = $"select value c from c where (c.graduate = 0 or IS_DEFINED(c.graduate) = false) and c.classId in ({string.Join(",", ids)})";
  182. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student)
  183. .GetItemQueryIterator<Student>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  184. {
  185. item.graduate = 1;
  186. students.Add(item);
  187. }
  188. foreach (var item in students)
  189. {
  190. item.graduate = 1;
  191. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Student>(item, item.id, new PartitionKey($"Base-{schoolId}"));
  192. }
  193. foreach (var item in graduate_classes)
  194. {
  195. item.graduate = 1;
  196. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<Class>(item, item.id, new PartitionKey($"Class-{schoolId}"));
  197. }
  198. }
  199. }
  200. //未毕业的
  201. if (json.TryGetProperty("cancel_graduate_classes", out JsonElement _cancel_graduate_classes))
  202. {
  203. List<Class> cancel_graduate_classes = _cancel_graduate_classes.ToObject<List<Class>>();
  204. if (cancel_graduate_classes.IsNotEmpty())
  205. {
  206. var ids = cancel_graduate_classes.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => $"'{x.id}'");
  207. List<Student> students = new List<Student>();
  208. string sql = $"select value c from c where c.graduate =1 and c.classId in ({string.Join(",", ids)})";
  209. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student)
  210. .GetItemQueryIterator<Student>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  211. {
  212. item.graduate = 0;
  213. students.Add(item);
  214. }
  215. foreach (var item in students)
  216. {
  217. item.graduate = 0;
  218. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Student>(item, item.id, new PartitionKey($"Base-{schoolId}"));
  219. }
  220. foreach (var item in cancel_graduate_classes)
  221. {
  222. item.graduate = 0;
  223. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<Class>(item, item.id, new PartitionKey($"Class-{schoolId}"));
  224. }
  225. }
  226. }
  227. } catch (Exception ex) {
  228. await _dingDing.SendBotMsg($"graduate-change,{ex.Message}\n{ex.StackTrace}\n{jsondata.ToJsonString()}",GroupNames.醍摩豆服務運維群組);
  229. }
  230. return response;
  231. }
  232. /// <summary>
  233. /// 数据推送接口
  234. /// </summary>
  235. /// <param name="req"></param>
  236. /// <param name="log"></param>
  237. /// <returns></returns>
  238. [Function("lesson-tag-change")]
  239. public async Task<HttpResponseData> LessonTagChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
  240. var response = req.CreateResponse(HttpStatusCode.OK);
  241. string data = await new StreamReader(req.Body).ReadToEndAsync();
  242. var json = JsonDocument.Parse(data).RootElement;
  243. List<TagOldNew> old_new = null;
  244. string school = null;
  245. if (json.TryGetProperty("school", out JsonElement _school))
  246. {
  247. school = _school.GetString();
  248. }
  249. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  250. {
  251. old_new = _old_new.ToObject<List<TagOldNew>>();
  252. }
  253. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  254. {
  255. foreach (var on in old_new)
  256. {
  257. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  258. string sql = $"select value(c) from c where array_contains(c.category,'{on._old}') ";
  259. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonRecord>
  260. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{_school}") }))
  261. {
  262. lessonRecords.Add(item);
  263. }
  264. lessonRecords.ForEach(item =>
  265. {
  266. //修改标签
  267. if (!string.IsNullOrWhiteSpace(on._new))
  268. {
  269. for (int i = 0; i < item.category.Count; i++)
  270. {
  271. if (item.category[i].Equals(on._old))
  272. {
  273. item.category[i] = on._new;
  274. }
  275. }
  276. }
  277. else
  278. {
  279. //表示删除标签
  280. item.category.RemoveAll(x => x.Equals(on._old));
  281. }
  282. });
  283. foreach (var item in lessonRecords)
  284. {
  285. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  286. }
  287. }
  288. }
  289. await response.WriteAsJsonAsync(new { data = json });
  290. return response;
  291. }
  292. /// <summary>
  293. /// 数据推送接口
  294. /// </summary>
  295. /// <param name="req"></param>
  296. /// <param name="log"></param>
  297. /// <returns></returns>
  298. [Function("knowledge-change")]
  299. public async Task<HttpResponseData> KnowledgeChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  300. {
  301. var response = req.CreateResponse(HttpStatusCode.OK);
  302. string data = await new StreamReader(req.Body).ReadToEndAsync();
  303. var json = JsonDocument.Parse(data).RootElement;
  304. List<TagOldNew> old_new = null;
  305. string school = null;
  306. if (json.TryGetProperty("school", out JsonElement _school))
  307. {
  308. school = _school.GetString();
  309. }
  310. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  311. {
  312. old_new = _old_new.ToObject<List<TagOldNew>>();
  313. }
  314. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  315. {
  316. foreach (var on in old_new)
  317. {
  318. List<ItemInfo> items = new List<ItemInfo>();
  319. string sql = $"select value(c) from c where array_contains(c.knowledge,'{on._old}') ";
  320. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>
  321. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{_school}") }))
  322. {
  323. items.Add(item);
  324. }
  325. items.ForEach(item =>
  326. {
  327. //修改知识点
  328. if (!string.IsNullOrEmpty(on._new))
  329. {
  330. for (int i = 0; i < item.knowledge.Count; i++)
  331. {
  332. if (item.knowledge[i].Equals(on._old))
  333. {
  334. item.knowledge[i] = on._new;
  335. }
  336. }
  337. }
  338. else
  339. {
  340. //表示删除知识点
  341. item.knowledge.RemoveAll(x => x.Equals(on._old));
  342. }
  343. });
  344. foreach (var item in items)
  345. {
  346. ItemBlob itemBlob = null;
  347. try
  348. {
  349. BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"{school}").GetBlobClient($"/item/{item.id}/{item.id}.json").DownloadAsync();
  350. if (blobDownloadResult != null)
  351. {
  352. var blob = JsonDocument.Parse(blobDownloadResult.Content);
  353. itemBlob = blob.RootElement.ToObject<ItemBlob>();
  354. itemBlob.exercise.knowledge = item.knowledge;
  355. await _azureStorage.GetBlobContainerClient($"{school}").UploadFileByContainer(itemBlob.ToJsonString(), "item", $"{item.id}/{item.id}.json", true);
  356. }
  357. }
  358. catch (Exception ex)
  359. {
  360. itemBlob = null;
  361. }
  362. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  363. }
  364. }
  365. }
  366. await response.WriteAsJsonAsync(new { data = json });
  367. return response;
  368. }
  369. /// <summary>
  370. /// 在线人数记录
  371. /// </summary>
  372. /// <param name="msg"></param>
  373. /// <returns></returns>
  374. [Function("online-record")]
  375. public async Task<HttpResponseData> OnlineRecord([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  376. {
  377. var response = req.CreateResponse(HttpStatusCode.OK);
  378. string data = await new StreamReader(req.Body).ReadToEndAsync();
  379. var json = JsonDocument.Parse(data).RootElement;
  380. try
  381. {
  382. string school = null;
  383. string scope = null;
  384. string id = null;
  385. string ip = null;
  386. int expire = 1;
  387. if (json.TryGetProperty("school", out JsonElement _school))
  388. school = _school.GetString();
  389. if (json.TryGetProperty("scope", out JsonElement _scope))
  390. scope = _scope.GetString();
  391. if (json.TryGetProperty("id", out JsonElement _id))
  392. id = _id.GetString();
  393. if (json.TryGetProperty("ip", out JsonElement _ip))
  394. ip = _ip.GetString();
  395. if (json.TryGetProperty("expire", out JsonElement _expire))
  396. expire = _expire.GetInt32();
  397. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  398. var cosmosClient = _azureCosmos.GetCosmosClient();
  399. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  400. var dateHour = dateTime.ToString("yyyyMMddHH"); //获取当天的小时
  401. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  402. var dateMonth = dateTime.ToString("yyyyMM");//获取当月的日期
  403. var currentHour = dateTime.Hour; //当前小时
  404. var currentDay = dateTime.Day; //当前天
  405. long Expire = dateTime.AddHours(expire).ToUnixTimeMilliseconds(); //token到期时间
  406. long now = dateTime.ToUnixTimeMilliseconds(); //当前时间戳
  407. DateTime hour = DateTime.UtcNow.AddHours(25); //25小时到期
  408. DateTime month = DateTime.UtcNow.AddDays(32); //一个月到期
  409. var delTbHour = dateTime.AddHours(-168).ToString("yyyyMMddHH"); //168小时前
  410. var delTbDay = dateTime.AddDays(-180).ToString("yyyyMMdd"); //180天前
  411. switch (scope)
  412. {
  413. case "teacher":
  414. try
  415. {
  416. Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  417. teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  418. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  419. }
  420. catch { }
  421. break;
  422. case "student":
  423. try
  424. {
  425. Student student = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
  426. student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  427. await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<Student>(student, student.id, new PartitionKey($"Base-{school}"));
  428. }
  429. catch { }
  430. break;
  431. case "tmduser":
  432. try
  433. {
  434. TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  435. tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  436. await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
  437. }
  438. catch { }
  439. break;
  440. }
  441. //天
  442. SortedSetEntry[] dayCnt = null;
  443. //月
  444. SortedSetEntry[] monthCnt = null;
  445. try
  446. {
  447. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateDay}", $"{currentHour}", 1);//一天24小时 小时为单位
  448. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateMonth}", $"{currentDay}", 1); //一天的累计 天为单位
  449. var resDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateDay}");
  450. if (resDay == null)
  451. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateDay}", hour); //设置到期时间
  452. var rspMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateMonth}");
  453. if (rspMonth == null)
  454. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateMonth}", month); //设置到期时间
  455. //保存当前小时统计
  456. dayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateDay}");
  457. //保存当前的统计数据
  458. monthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateMonth}");
  459. }
  460. catch { }
  461. if (dayCnt != null && dayCnt.Length > 0)
  462. {
  463. List<HourLogin> hourLogins = new();
  464. foreach (var dCnt in dayCnt)
  465. {
  466. if (((int)dCnt.Element) == currentHour)
  467. {
  468. var tphourLogins = await table.QueryWhereString<HourLogin>($"PartitionKey eq 'HourLogin' and RowKey eq '{dateHour}'");
  469. if (tphourLogins.Count > 0)
  470. {
  471. foreach (var hourLogin in tphourLogins)
  472. {
  473. if (scope.Equals("teacher"))
  474. hourLogin.Teacher = (int)dCnt.Score;
  475. else if (scope.Equals("student"))
  476. hourLogin.Student = (int)dCnt.Score;
  477. else
  478. hourLogin.TmdUser = (int)dCnt.Score;
  479. hourLogins.Add(hourLogin);
  480. }
  481. }
  482. else
  483. {
  484. HourLogin hourLogin = new() { PartitionKey = $"HourLogin", RowKey = dateHour, Hour = currentHour };
  485. if (scope.Equals("teacher"))
  486. {
  487. hourLogin.Teacher = 1;
  488. hourLogin.Student = 0;
  489. hourLogin.TmdUser = 0;
  490. }
  491. else if (scope.Equals("student"))
  492. {
  493. hourLogin.Teacher = 0;
  494. hourLogin.Student = 1;
  495. hourLogin.TmdUser = 0;
  496. }
  497. else
  498. {
  499. hourLogin.Teacher = 0;
  500. hourLogin.Student = 0;
  501. hourLogin.TmdUser = 1;
  502. }
  503. hourLogins.Add(hourLogin);
  504. }
  505. }
  506. }
  507. await table.SaveOrUpdateAll(hourLogins); //保存和更新保存当前小时登录次数
  508. }
  509. if (monthCnt != null && monthCnt.Length > 0)
  510. {
  511. List<DayLogin> dayLogins = new();
  512. foreach (var mCnt in monthCnt)
  513. {
  514. if (((int)mCnt.Element) == currentDay)
  515. {
  516. //保存当天的峰值
  517. var tbDays = await table.QueryWhereString<DayLogin>($"PartitionKey eq 'DayLogin' and RowKey eq '{dateDay}'");
  518. if (tbDays.Count > 0)
  519. {
  520. foreach (var dayLogin in tbDays)
  521. {
  522. if (scope.Equals("teacher"))
  523. dayLogin.Teacher = (int)mCnt.Score;
  524. else if (scope.Equals("student"))
  525. dayLogin.Student = (int)mCnt.Score;
  526. else
  527. dayLogin.TmdUser = (int)mCnt.Score;
  528. dayLogins.Add(dayLogin);
  529. }
  530. }
  531. else
  532. {
  533. //保存当月每天的峰值
  534. DayLogin dayLogin = new() { PartitionKey = $"DayLogin", RowKey = dateDay, Day = currentDay };
  535. if (scope.Equals("teacher"))
  536. {
  537. dayLogin.Teacher = 1;
  538. dayLogin.Student = 0;
  539. dayLogin.TmdUser = 0;
  540. }
  541. else if (scope.Equals("student"))
  542. {
  543. dayLogin.Teacher = 0;
  544. dayLogin.Student = 1;
  545. dayLogin.TmdUser = 0;
  546. }
  547. else
  548. {
  549. dayLogin.Teacher = 0;
  550. dayLogin.Student = 0;
  551. dayLogin.TmdUser = 1;
  552. }
  553. dayLogins.Add(dayLogin);
  554. }
  555. }
  556. }
  557. await table.SaveOrUpdateAll(dayLogins);// 保存当月每天在线数据
  558. }
  559. string tbHourSql = $"PartitionKey eq 'HourLogin' and RowKey le '{delTbHour}'";
  560. string tbDaySql = $"PartitionKey eq 'DayLogin' and RowKey le '{delTbDay}'";
  561. try
  562. {
  563. await table.DeleteStringWhere<HourLogin>(rowKey: tbHourSql); //删除168小时前的数据
  564. await table.DeleteStringWhere<DayLogin>(rowKey: tbDaySql); //删除180天前的数据
  565. }
  566. catch { }
  567. if (!string.IsNullOrWhiteSpace(school))
  568. {
  569. //天
  570. SortedSetEntry[] scDayCnt = null;
  571. //月
  572. SortedSetEntry[] scMonthCnt = null;
  573. try
  574. {
  575. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateDay}", $"{currentHour}", 1);//当天当前小时在线人加1
  576. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateMonth}", $"{currentDay}", 1); //当天的在线加1
  577. var reScDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateDay}");
  578. if (reScDay == null)
  579. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateDay}", hour); //设置到期时间
  580. var reScMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateMonth}");
  581. if (reScMonth == null)
  582. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateMonth}", month); //设置到期时间
  583. //保存学校当天每小时的
  584. scDayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateDay}");
  585. //学校天峰值
  586. scMonthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateMonth}");
  587. }
  588. catch { }
  589. if (scDayCnt != null && scDayCnt.Length > 0)
  590. {
  591. List<HourLoginSchool> hourLoginSchools = new();
  592. foreach (var scDCnt in scDayCnt)
  593. {
  594. if (((int)scDCnt.Element) == currentHour)
  595. {
  596. var tmpHour = await table.QueryWhereString<HourLoginSchool>($"PartitionKey eq 'HourLogin-{school}' and RowKey eq '{dateHour}'");
  597. if (tmpHour.Count > 0)
  598. {
  599. foreach (var hLoginSc in tmpHour)
  600. {
  601. if (scope.Equals("teacher"))
  602. hLoginSc.Teacher = (int)scDCnt.Score;
  603. else if (scope.Equals("student"))
  604. hLoginSc.Student = (int)scDCnt.Score;
  605. else
  606. hLoginSc.TmdUser = (int)scDCnt.Score;
  607. hourLoginSchools.Add(hLoginSc);
  608. }
  609. }
  610. else
  611. {
  612. //学校小时峰值
  613. HourLoginSchool hourLoginSc = new() { PartitionKey = $"HourLogin-{school}", RowKey = dateHour, Hour = currentHour, School = school };
  614. if (scope.Equals("teacher"))
  615. {
  616. hourLoginSc.Teacher = 1;
  617. hourLoginSc.Student = 0;
  618. hourLoginSc.TmdUser = 0;
  619. }
  620. else if (scope.Equals("student"))
  621. {
  622. hourLoginSc.Teacher = 0;
  623. hourLoginSc.Student = 1;
  624. hourLoginSc.TmdUser = 0;
  625. }
  626. else
  627. {
  628. hourLoginSc.Teacher = 0;
  629. hourLoginSc.Student = 0;
  630. hourLoginSc.TmdUser = 1;
  631. }
  632. hourLoginSchools.Add(hourLoginSc);
  633. }
  634. }
  635. }
  636. await table.SaveOrUpdateAll(hourLoginSchools);
  637. }
  638. if (scMonthCnt != null && scMonthCnt.Length > 0)
  639. {
  640. List<DayLoginSchool> DayLoginSchools = new();
  641. foreach (var scMCnt in scMonthCnt)
  642. {
  643. if (((int)scMCnt.Element) == currentDay)
  644. {
  645. var tempDays = await table.QueryWhereString<DayLoginSchool>($"PartitionKey eq 'DayLogin-{school}' and RowKey eq '{dateDay}'");
  646. if (tempDays.Count > 0)
  647. {
  648. foreach (var dLoginSc in tempDays)
  649. {
  650. if (scope.Equals("teacher"))
  651. dLoginSc.Teacher = (int)scMCnt.Score;
  652. else if (scope.Equals("student"))
  653. dLoginSc.Student = (int)scMCnt.Score;
  654. else
  655. dLoginSc.TmdUser = (int)scMCnt.Score;
  656. DayLoginSchools.Add(dLoginSc);
  657. }
  658. }
  659. else
  660. {
  661. //学校天峰值
  662. DayLoginSchool dayLoginSc = new() { PartitionKey = $"DayLogin-{school}", RowKey = dateDay, Day = currentDay, School = school };
  663. if (scope.Equals("teacher"))
  664. {
  665. dayLoginSc.Teacher = 1;
  666. dayLoginSc.Student = 0;
  667. dayLoginSc.TmdUser = 0;
  668. }
  669. else if (scope.Equals("student"))
  670. {
  671. dayLoginSc.Teacher = 0;
  672. dayLoginSc.Student = 1;
  673. dayLoginSc.TmdUser = 0;
  674. }
  675. else
  676. {
  677. dayLoginSc.Teacher = 0;
  678. dayLoginSc.Student = 0;
  679. dayLoginSc.TmdUser = 1;
  680. }
  681. DayLoginSchools.Add(dayLoginSc);
  682. }
  683. }
  684. }
  685. await table.SaveOrUpdateAll(DayLoginSchools);//保存学校当月在线数据
  686. }
  687. string tbScHourSql = $"PartitionKey eq 'HourLogin-{school}' and RowKey le '{delTbHour}'";
  688. List<HourLogin> scHourLog = await table.QueryWhereString<HourLogin>(tbScHourSql);
  689. if (scHourLog.Count > 0)
  690. try
  691. {
  692. //await table.DeleteStringWhere<HourLogin>(tbScHourSql); //删除学校168小时前的数据
  693. await table.DeleteAll(scHourLog);
  694. }
  695. catch { }
  696. string tbScDaySql = $"PartitionKey eq 'DayLogin-{school}' and RowKey le '{delTbDay}'";
  697. List<DayLogin> scDayLog = await table.QueryWhereString<DayLogin>(tbScDaySql);
  698. if (scDayLog.Count > 0)
  699. try
  700. {
  701. //await table.DeleteStringWhere<DayLogin>(tbScDaySql); //删除学校180天前的数据
  702. await table.DeleteAll(scDayLog);
  703. }
  704. catch { }
  705. }
  706. await response.WriteAsJsonAsync(new { data = json });
  707. return response;
  708. }
  709. catch (Exception ex)
  710. {
  711. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-online-record 人数记录异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  712. await response.WriteAsJsonAsync(new { data = json });
  713. return response;
  714. }
  715. }
  716. }
  717. }