IESHttpTrigger.cs 43 KB

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