IESHttpTrigger.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. /// </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.GetBlobContainerClient($"{school}").UploadFileByContainer(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("online-record")]
  149. public async Task<HttpResponseData> OnlineRecord([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. try
  155. {
  156. string school = null;
  157. string scope = null;
  158. string id = null;
  159. string ip = null;
  160. int expire = 1;
  161. if (json.TryGetProperty("school", out JsonElement _school))
  162. school = _school.GetString();
  163. if (json.TryGetProperty("scope", out JsonElement _scope))
  164. scope = _scope.GetString();
  165. if (json.TryGetProperty("id", out JsonElement _id))
  166. id = _id.GetString();
  167. if (json.TryGetProperty("ip", out JsonElement _ip))
  168. ip = _ip.GetString();
  169. if (json.TryGetProperty("expire", out JsonElement _expire))
  170. expire = _expire.GetInt32();
  171. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  172. var cosmosClient = _azureCosmos.GetCosmosClient();
  173. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  174. var dateHour = dateTime.ToString("yyyyMMddHH"); //获取当天的小时
  175. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  176. var dateMonth = dateTime.ToString("yyyyMM");//获取当月的日期
  177. var currentHour = dateTime.Hour; //当前小时
  178. var currentDay = dateTime.Day; //当前天
  179. long Expire = dateTime.AddHours(expire).ToUnixTimeMilliseconds(); //token到期时间
  180. long now = dateTime.ToUnixTimeMilliseconds(); //当前时间戳
  181. DateTime hour = DateTime.UtcNow.AddHours(25); //25小时到期
  182. DateTime month = DateTime.UtcNow.AddDays(32); //一个月到期
  183. var delTbHour = dateTime.AddHours(-168).ToString("yyyyMMddHH"); //168小时前
  184. var delTbDay = dateTime.AddDays(-180).ToString("yyyyMMdd"); //180天前
  185. switch (scope)
  186. {
  187. case "teacher":
  188. try
  189. {
  190. Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  191. teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  192. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  193. }
  194. catch { }
  195. break;
  196. case "student":
  197. try
  198. {
  199. Student student = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
  200. student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  201. await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<Student>(student, student.id, new PartitionKey($"Base-{school}"));
  202. }
  203. catch { }
  204. break;
  205. case "tmduser":
  206. try
  207. {
  208. TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  209. tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  210. await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
  211. }
  212. catch { }
  213. break;
  214. }
  215. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateDay}", $"{currentHour}", 1);//一天24小时 小时为单位
  216. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateMonth}", $"{currentDay}", 1); //一天的累计 天为单位
  217. var resDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateDay}");
  218. if (resDay == null)
  219. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateDay}", hour); //设置到期时间
  220. var rspMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateMonth}");
  221. if (rspMonth == null)
  222. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateMonth}", month); //设置到期时间
  223. //保存当前小时统计
  224. var dayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateDay}");
  225. if (dayCnt != null && dayCnt.Length > 0)
  226. {
  227. List<HourLogin> hourLogins = new();
  228. foreach (var dCnt in dayCnt)
  229. {
  230. if (((int)dCnt.Element) == currentHour)
  231. {
  232. var tphourLogins = await table.QueryWhereString<HourLogin>($"PartitionKey eq 'HourLogin' and RowKey eq '{dateHour}'");
  233. if (tphourLogins.Count > 0)
  234. {
  235. foreach (var hourLogin in tphourLogins)
  236. {
  237. if (scope.Equals("teacher"))
  238. hourLogin.Teacher = (int)dCnt.Score;
  239. else if (scope.Equals("student"))
  240. hourLogin.Student = (int)dCnt.Score;
  241. else
  242. hourLogin.TmdUser = (int)dCnt.Score;
  243. hourLogins.Add(hourLogin);
  244. }
  245. }
  246. else
  247. {
  248. HourLogin hourLogin = new() { PartitionKey = $"HourLogin", RowKey = dateHour, Hour = currentHour };
  249. if (scope.Equals("teacher"))
  250. {
  251. hourLogin.Teacher = 1;
  252. hourLogin.Student = 0;
  253. hourLogin.TmdUser = 0;
  254. }
  255. else if (scope.Equals("student"))
  256. {
  257. hourLogin.Teacher = 0;
  258. hourLogin.Student = 1;
  259. hourLogin.TmdUser = 0;
  260. }
  261. else
  262. {
  263. hourLogin.Teacher = 0;
  264. hourLogin.Student = 0;
  265. hourLogin.TmdUser = 1;
  266. }
  267. hourLogins.Add(hourLogin);
  268. }
  269. }
  270. }
  271. await table.SaveOrUpdateAll(hourLogins); //保存和更新保存当前小时登录次数
  272. }
  273. //保存当前的统计数据
  274. var monthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateMonth}");
  275. if (monthCnt != null && monthCnt.Length > 0)
  276. {
  277. List<DayLogin> dayLogins = new();
  278. foreach (var mCnt in monthCnt)
  279. {
  280. if (((int)mCnt.Element) == currentDay)
  281. {
  282. //保存当天的峰值
  283. var tbDays = await table.QueryWhereString<DayLogin>($"PartitionKey eq 'DayLogin' and RowKey eq '{dateDay}'");
  284. if (tbDays.Count > 0)
  285. {
  286. foreach (var dayLogin in tbDays)
  287. {
  288. if (scope.Equals("teacher"))
  289. dayLogin.Teacher = (int)mCnt.Score;
  290. else if (scope.Equals("student"))
  291. dayLogin.Student = (int)mCnt.Score;
  292. else
  293. dayLogin.TmdUser = (int)mCnt.Score;
  294. dayLogins.Add(dayLogin);
  295. }
  296. }
  297. else
  298. {
  299. //保存当月每天的峰值
  300. DayLogin dayLogin = new() { PartitionKey = $"DayLogin", RowKey = dateDay, Day = currentDay };
  301. if (scope.Equals("teacher"))
  302. {
  303. dayLogin.Teacher = 1;
  304. dayLogin.Student = 0;
  305. dayLogin.TmdUser = 0;
  306. }
  307. else if (scope.Equals("student"))
  308. {
  309. dayLogin.Teacher = 0;
  310. dayLogin.Student = 1;
  311. dayLogin.TmdUser = 0;
  312. }
  313. else
  314. {
  315. dayLogin.Teacher = 0;
  316. dayLogin.Student = 0;
  317. dayLogin.TmdUser = 1;
  318. }
  319. dayLogins.Add(dayLogin);
  320. }
  321. }
  322. }
  323. await table.SaveOrUpdateAll(dayLogins);// 保存当月每天在线数据
  324. }
  325. string tbHourSql = $"PartitionKey eq 'HourLogin' and RowKey le '{delTbHour}'";
  326. await table.DeleteStringWhere<HourLogin>(rowKey: tbHourSql); //删除168小时前的数据
  327. string tbDaySql = $"PartitionKey eq 'DayLogin' and RowKey le '{delTbDay}'";
  328. await table.DeleteStringWhere<DayLogin>(rowKey: tbDaySql); //删除180天前的数据
  329. if (!string.IsNullOrWhiteSpace(school))
  330. {
  331. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateDay}", $"{currentHour}", 1);//当天当前小时在线人加1
  332. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateMonth}", $"{currentDay}", 1); //当天的在线加1
  333. var reScDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateDay}");
  334. if (reScDay == null)
  335. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateDay}", hour); //设置到期时间
  336. var reScMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateMonth}");
  337. if (reScMonth == null)
  338. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateMonth}", month); //设置到期时间
  339. //保存学校当天每小时的
  340. var scDayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateDay}");
  341. if (scDayCnt != null && scDayCnt.Length > 0)
  342. {
  343. List<HourLoginSchool> hourLoginSchools = new();
  344. foreach (var scDCnt in scDayCnt)
  345. {
  346. if (((int)scDCnt.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)scDCnt.Score;
  355. else if (scope.Equals("student"))
  356. hLoginSc.Student = (int)scDCnt.Score;
  357. else
  358. hLoginSc.TmdUser = (int)scDCnt.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. //学校天峰值
  391. var scMonthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateMonth}");
  392. if (scMonthCnt != null && scMonthCnt.Length > 0)
  393. {
  394. List<DayLoginSchool> DayLoginSchools = new();
  395. foreach (var scMCnt in scMonthCnt)
  396. {
  397. if (((int)scMCnt.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)scMCnt.Score;
  406. else if (scope.Equals("student"))
  407. dLoginSc.Student = (int)scMCnt.Score;
  408. else
  409. dLoginSc.TmdUser = (int)scMCnt.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. List<HourLogin> scHourLog = await table.QueryWhereString<HourLogin>(tbScHourSql);
  443. if (scHourLog.Count > 0)
  444. //await table.DeleteStringWhere<HourLogin>(tbScHourSql); //删除学校168小时前的数据
  445. await table.DeleteAll(scHourLog);
  446. string tbScDaySql = $"PartitionKey eq 'DayLogin-{school}' and RowKey le '{delTbDay}'";
  447. List<DayLogin> scDayLog = await table.QueryWhereString<DayLogin>(tbScDaySql);
  448. if (scDayLog.Count > 0)
  449. await table.DeleteAll(scDayLog);
  450. //await table.DeleteStringWhere<DayLogin>(tbScDaySql); //删除学校180天前的数据
  451. }
  452. await response.WriteAsJsonAsync(new { data = json });
  453. return response;
  454. }
  455. catch (Exception ex)
  456. {
  457. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-online-record 人数记录异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  458. await response.WriteAsJsonAsync(new { data = json });
  459. return response;
  460. }
  461. }
  462. }
  463. }