IESHttpTrigger.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Reflection;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Threading.Tasks;
  16. using TEAMModelOS.SDK;
  17. using TEAMModelOS.SDK.DI;
  18. using TEAMModelOS.SDK.Extension;
  19. using TEAMModelOS.SDK.Models;
  20. using TEAMModelOS.SDK.Models.Cosmos.Teacher;
  21. using TEAMModelOS.SDK.Models.Table;
  22. using static TEAMModelOS.SDK.Models.Teacher;
  23. namespace TEAMModelOS.FunctionV4.HttpTrigger
  24. {
  25. public class IESHttpTrigger
  26. {
  27. private readonly AzureCosmosFactory _azureCosmos;
  28. private readonly DingDing _dingDing;
  29. private readonly AzureStorageFactory _azureStorage;
  30. private readonly AzureRedisFactory _azureRedis;
  31. public IESHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage
  32. , AzureRedisFactory azureRedis)
  33. {
  34. _azureCosmos = azureCosmos;
  35. _dingDing = dingDing;
  36. _azureStorage = azureStorage;
  37. _azureRedis = azureRedis;
  38. }
  39. /// <summary>
  40. /// 数据推送接口
  41. /// </summary>
  42. /// <param name="req"></param>
  43. /// <param name="log"></param>
  44. /// <returns></returns>
  45. [Function("system-info-function")]
  46. public async Task<HttpResponseData> SystemInfo([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestData req)
  47. {
  48. var response = req.CreateResponse(HttpStatusCode.OK);
  49. Type attr = this.GetType();
  50. string currentDirectory = Path.GetDirectoryName(attr.Assembly.Location);
  51. Assembly assembly = Assembly.LoadFrom($"{currentDirectory}\\TEAMModelOS.FunctionV4.dll");
  52. var description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
  53. //var v1 = Assembly.GetEntryAssembly().GetName().Version;
  54. //var v2 = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
  55. // var description = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
  56. var version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
  57. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  58. //Console.WriteLine($"Assembly.GetEntryAssembly().GetName().Version: " +
  59. // $"{Assembly.GetEntryAssembly().GetName().Version}");5.2107.12.1
  60. //Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version:" +
  61. // $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version}");5.2107.12.1
  62. //Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion:" +
  63. // $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}");5.2107.12
  64. await response.WriteAsJsonAsync(new { version, description, nowtime });
  65. return response;
  66. }
  67. /// <summary>
  68. /// 数据推送接口
  69. /// </summary>
  70. /// <param name="req"></param>
  71. /// <param name="log"></param>
  72. /// <returns></returns>
  73. [Function("knowledge-change")]
  74. public async Task<HttpResponseData> KnowledgeChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  75. {
  76. var response = req.CreateResponse(HttpStatusCode.OK);
  77. string data = await new StreamReader(req.Body).ReadToEndAsync();
  78. var json = JsonDocument.Parse(data).RootElement;
  79. List<OldNew> old_new = null;
  80. string school = null;
  81. if (json.TryGetProperty("school", out JsonElement _school))
  82. {
  83. school = _school.GetString();
  84. }
  85. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  86. {
  87. old_new = _old_new.ToObject<List<OldNew>>();
  88. }
  89. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  90. {
  91. foreach (var on in old_new)
  92. {
  93. List<ItemInfo> items = new List<ItemInfo>();
  94. string sql = $"select value(c) from c where array_contains(c.knowledge,'{on._old}') ";
  95. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>
  96. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{_school}") }))
  97. {
  98. items.Add(item);
  99. }
  100. items.ForEach(item =>
  101. {
  102. //修改知识点
  103. if (!string.IsNullOrEmpty(on._new))
  104. {
  105. for (int i = 0; i < item.knowledge.Count; i++)
  106. {
  107. if (item.knowledge[i].Equals(on._old))
  108. {
  109. item.knowledge[i] = on._new;
  110. }
  111. }
  112. }
  113. else
  114. {
  115. //表示删除知识点
  116. item.knowledge.RemoveAll(x => x.Equals(on._old));
  117. }
  118. });
  119. foreach (var item in items)
  120. {
  121. ItemBlob itemBlob = null;
  122. try
  123. {
  124. BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"{school}").GetBlobClient($"/item/{item.id}/{item.id}.json").DownloadAsync();
  125. if (blobDownloadResult != null)
  126. {
  127. var blob = JsonDocument.Parse(blobDownloadResult.Content);
  128. itemBlob = blob.RootElement.ToObject<ItemBlob>();
  129. itemBlob.exercise.knowledge = item.knowledge;
  130. await _azureStorage.UploadFileByContainer($"{school}", itemBlob.ToJsonString(), "item", $"{item.id}/{item.id}.json", true);
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. itemBlob = null;
  136. }
  137. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  138. }
  139. }
  140. }
  141. await response.WriteAsJsonAsync(new { data = json });
  142. return response;
  143. }
  144. /// <summary>
  145. /// 在线人数记录
  146. /// </summary>
  147. /// <param name="msg"></param>
  148. /// <returns></returns>
  149. [Function("onlin-record")]
  150. public async Task<HttpResponseData> OnlinRecord([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
  151. {
  152. var response = req.CreateResponse(HttpStatusCode.OK);
  153. string data = await new StreamReader(req.Body).ReadToEndAsync();
  154. var json = JsonDocument.Parse(data).RootElement;
  155. string school = null;
  156. string scope = null;
  157. string id = null;
  158. string ip = null;
  159. int expire = 1;
  160. if (json.TryGetProperty("school", out JsonElement _school))
  161. school = _school.GetString();
  162. if (json.TryGetProperty("scope", out JsonElement _scope))
  163. scope = _scope.GetString();
  164. if (json.TryGetProperty("id", out JsonElement _id))
  165. id = _id.GetString();
  166. if (json.TryGetProperty("ip", out JsonElement _ip))
  167. ip = _ip.GetString();
  168. if (json.TryGetProperty("expire", out JsonElement _expire))
  169. expire = _expire.GetInt32();
  170. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  171. var cosmosClient = _azureCosmos.GetCosmosClient();
  172. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  173. var dateHour = dateTime.ToString("yyyyMMddHH"); //获取当天的小时
  174. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  175. var dateMonth = dateTime.ToString("yyyyMM");//获取当月的日期
  176. var currentHour = dateTime.Hour; //当前小时
  177. var currentDay = dateTime.Day; //当前天
  178. long Expire = dateTime.AddHours(expire).ToUnixTimeMilliseconds(); //token到期时间
  179. long now = dateTime.ToUnixTimeMilliseconds(); //当前时间戳
  180. DateTime hour = DateTime.UtcNow.AddHours(25); //25小时到期
  181. DateTime month = DateTime.UtcNow.AddDays(32); //一个月到期
  182. var delTbHour = dateTime.AddHours(-168).ToString("yyyyMMddHH"); //168小时前
  183. var delTbDay = dateTime.AddDays(-180).ToString("yyyyMMdd"); //180天前
  184. switch (scope)
  185. {
  186. case "teacher":
  187. try
  188. {
  189. Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  190. teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  191. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  192. }
  193. catch { }
  194. break;
  195. case "student":
  196. try
  197. {
  198. Student student = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
  199. student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  200. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Student>(student, student.id, new PartitionKey("Base"));
  201. }
  202. catch { }
  203. break;
  204. case "tmduser":
  205. try
  206. {
  207. TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  208. tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  209. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
  210. }
  211. catch { }
  212. break;
  213. }
  214. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateDay}", $"{currentHour}", 1);//一天24小时
  215. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateMonth}", $"{currentDay}", 1); //当天的累计
  216. var resDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateDay}");
  217. if (resDay == null)
  218. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateDay}", hour); //设置到期时间
  219. var rspMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateMonth}");
  220. if (rspMonth == null)
  221. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateMonth}", month); //设置到期时间
  222. //查询Redis是否有值
  223. var dayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateDay}");
  224. if (dayCnt != null && dayCnt.Length > 0)
  225. {
  226. List<HourLogin> hourLogins = new();
  227. foreach (var hourCnt in dayCnt)
  228. {
  229. if (((int)hourCnt.Element) == currentHour)
  230. {
  231. var tphourLogins = await table.QueryWhereString<HourLogin>($"PartitionKey eq 'HourLogin' and RowKey eq '{dateHour}'");
  232. if (tphourLogins.Count > 0)
  233. {
  234. foreach (var hourLogin in tphourLogins)
  235. {
  236. if (scope.Equals("teacher"))
  237. hourLogin.Teacher = (int)hourCnt.Score;
  238. else if (scope.Equals("student"))
  239. hourLogin.Student = (int)hourCnt.Score;
  240. else
  241. hourLogin.TmdUser = (int)hourCnt.Score;
  242. hourLogins.Add(hourLogin);
  243. }
  244. }
  245. else
  246. {
  247. HourLogin hourLogin = new() { PartitionKey = $"HourLogin", RowKey = dateHour, Hour = currentHour };
  248. if (scope.Equals("teacher"))
  249. {
  250. hourLogin.Teacher = 1;
  251. hourLogin.Student = 0;
  252. hourLogin.TmdUser = 0;
  253. }
  254. else if (scope.Equals("student"))
  255. {
  256. hourLogin.Teacher = 0;
  257. hourLogin.Student = 1;
  258. hourLogin.TmdUser = 0;
  259. }
  260. else
  261. {
  262. hourLogin.Teacher = 0;
  263. hourLogin.Student = 0;
  264. hourLogin.TmdUser = 1;
  265. }
  266. hourLogins.Add(hourLogin);
  267. }
  268. }
  269. }
  270. await table.SaveOrUpdateAll(hourLogins); //保存和更新保存当前小时登录次数
  271. }
  272. var monthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateMonth}");
  273. if (monthCnt != null && monthCnt.Length > 0)
  274. {
  275. List<DayLogin> dayLogins = new();
  276. foreach (var mCnt in monthCnt)
  277. {
  278. if (((int)mCnt.Element) == currentDay)
  279. {
  280. //保存当天的峰值
  281. var tbDays = await table.QueryWhereString<DayLogin>($"PartitionKey eq 'DayLogin' and RowKey eq '{dateDay}'");
  282. if (tbDays.Count > 0)
  283. {
  284. foreach (var dayLogin in tbDays)
  285. {
  286. if (scope.Equals("teacher"))
  287. dayLogin.Teacher = (int)mCnt.Score;
  288. else if (scope.Equals("student"))
  289. dayLogin.Student = (int)mCnt.Score;
  290. else
  291. dayLogin.TmdUser = (int)mCnt.Score;
  292. dayLogins.Add(dayLogin);
  293. }
  294. }
  295. else
  296. {
  297. //保存当月每天的峰值
  298. DayLogin dayLogin = new() { PartitionKey = $"DayLogin", RowKey = dateDay, Day = currentDay };
  299. if (scope.Equals("teacher"))
  300. {
  301. dayLogin.Teacher = 1;
  302. dayLogin.Student = 0;
  303. dayLogin.TmdUser = 0;
  304. }
  305. else if (scope.Equals("student"))
  306. {
  307. dayLogin.Teacher = 0;
  308. dayLogin.Student = 1;
  309. dayLogin.TmdUser = 0;
  310. }
  311. else
  312. {
  313. dayLogin.Teacher = 0;
  314. dayLogin.Student = 0;
  315. dayLogin.TmdUser = 1;
  316. }
  317. dayLogins.Add(dayLogin);
  318. }
  319. }
  320. }
  321. await table.SaveOrUpdateAll(dayLogins);// 保存当月每天在线数据
  322. }
  323. string tbHourSql = $"PartitionKey eq 'HourLogin' and RowKey le '{delTbHour}'";
  324. await table.DeleteStringWhere<BIOptLog>(rowKey: tbHourSql); //删除168小时前的数据
  325. string tbDaySql = $"PartitionKey eq 'DayLogin' and RowKey le '{delTbDay}'";
  326. await table.DeleteStringWhere<BIOptLog>(rowKey: tbDaySql); //删除180天前的数据
  327. if (!string.IsNullOrWhiteSpace(school))
  328. {
  329. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateDay}", $"{currentHour}", 1);//当天当前小时在线人加1
  330. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateMonth}", $"{currentDay}", 1); //当天的在线加1
  331. var reScDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateDay}");
  332. if (reScDay == null)
  333. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateDay}", hour); //设置到期时间
  334. var reScMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateMonth}");
  335. if (reScMonth == null)
  336. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateMonth}", month); //设置到期时间
  337. //查询Redis是否有值
  338. var scDayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateDay}");
  339. List<dynamic> scDayCounts = new();
  340. if (scDayCnt != null && scDayCnt.Length > 0)
  341. {
  342. //保存学校当天每小时的
  343. List<HourLoginSchool> hourLoginSchools = new();
  344. foreach (var itemHour in scDayCnt)
  345. {
  346. if (((int)itemHour.Element) == currentHour)
  347. {
  348. var tmpHour = await table.QueryWhereString<HourLoginSchool>($"PartitionKey eq 'HourLogin-{school}' and RowKey eq '{dateHour}'");
  349. if (tmpHour.Count > 0)
  350. {
  351. foreach (var hLoginSc in tmpHour)
  352. {
  353. if (scope.Equals("teacher"))
  354. hLoginSc.Teacher = (int)itemHour.Score;
  355. else if (scope.Equals("student"))
  356. hLoginSc.Student = (int)itemHour.Score;
  357. else
  358. hLoginSc.TmdUser = (int)itemHour.Score;
  359. hourLoginSchools.Add(hLoginSc);
  360. }
  361. }
  362. else
  363. {
  364. //学校小时峰值
  365. HourLoginSchool hourLoginSc = new() { PartitionKey = $"HourLogin-{school}", RowKey = dateHour, Hour = currentHour, School = school };
  366. if (scope.Equals("teacher"))
  367. {
  368. hourLoginSc.Teacher = 1;
  369. hourLoginSc.Student = 0;
  370. hourLoginSc.TmdUser = 0;
  371. }
  372. else if (scope.Equals("student"))
  373. {
  374. hourLoginSc.Teacher = 0;
  375. hourLoginSc.Student = 1;
  376. hourLoginSc.TmdUser = 0;
  377. }
  378. else
  379. {
  380. hourLoginSc.Teacher = 0;
  381. hourLoginSc.Student = 0;
  382. hourLoginSc.TmdUser = 1;
  383. }
  384. hourLoginSchools.Add(hourLoginSc);
  385. }
  386. }
  387. }
  388. await table.SaveOrUpdateAll(hourLoginSchools);
  389. }
  390. var ScMonth = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateMonth}");
  391. if (ScMonth != null && ScMonth.Length > 0)
  392. {
  393. //学校天峰值
  394. List<DayLoginSchool> DayLoginSchools = new();
  395. foreach (var count in ScMonth)
  396. {
  397. if (((int)count.Element) == currentDay)
  398. {
  399. var tempDays = await table.QueryWhereString<DayLoginSchool>($"PartitionKey eq 'DayLogin-{school}' and RowKey eq '{dateDay}'");
  400. if (tempDays.Count > 0)
  401. {
  402. foreach (var dLoginSc in tempDays)
  403. {
  404. if (scope.Equals("teacher"))
  405. dLoginSc.Teacher = (int)count.Score;
  406. else if (scope.Equals("student"))
  407. dLoginSc.Student = (int)count.Score;
  408. else
  409. dLoginSc.TmdUser = (int)count.Score;
  410. DayLoginSchools.Add(dLoginSc);
  411. }
  412. }
  413. else
  414. {
  415. //学校天峰值
  416. DayLoginSchool dayLoginSc = new() { PartitionKey = $"DayLogin-{school}", RowKey = dateDay, Day = currentDay, School = school };
  417. if (scope.Equals("teacher"))
  418. {
  419. dayLoginSc.Teacher = 1;
  420. dayLoginSc.Student = 0;
  421. dayLoginSc.TmdUser = 0;
  422. }
  423. else if (scope.Equals("student"))
  424. {
  425. dayLoginSc.Teacher = 0;
  426. dayLoginSc.Student = 1;
  427. dayLoginSc.TmdUser = 0;
  428. }
  429. else
  430. {
  431. dayLoginSc.Teacher = 0;
  432. dayLoginSc.Student = 0;
  433. dayLoginSc.TmdUser = 1;
  434. }
  435. DayLoginSchools.Add(dayLoginSc);
  436. }
  437. }
  438. }
  439. await table.SaveOrUpdateAll(DayLoginSchools);//保存学校当月在线数据
  440. }
  441. string tbScHourSql = $"PartitionKey eq 'HourLogin-{school}' and RowKey le '{delTbHour}'";
  442. await table.DeleteStringWhere<BIOptLog>(rowKey: tbHourSql); //删除学校168小时前的数据
  443. string tbScDaySql = $"PartitionKey eq 'DayLogin-{school}' and RowKey le '{delTbDay}'";
  444. await table.DeleteStringWhere<BIOptLog>(rowKey: tbDaySql); //删除学校180天前的数据
  445. }
  446. await response.WriteAsJsonAsync(new { data = json });
  447. return response;
  448. }
  449. }
  450. }