IESHttpTrigger.cs 40 KB

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