IESHttpTrigger.cs 23 KB

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