SystemService.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. using Azure.Storage.Blobs.Models;
  2. using DocumentFormat.OpenXml.Bibliography;
  3. using DocumentFormat.OpenXml.Office2010.Excel;
  4. using DocumentFormat.OpenXml.Wordprocessing;
  5. using HTEXLib;
  6. using HTEXLib.COMM.Helpers;
  7. using Microsoft.Azure.Amqp.Framing;
  8. using Newtonsoft.Json.Linq;
  9. using OpenXmlPowerTools;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Diagnostics.PerformanceData;
  14. using System.IdentityModel.Tokens.Jwt;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.Json;
  18. using System.Text.RegularExpressions;
  19. using System.Threading.Tasks;
  20. using TEAMModelOS.SDK.DI;
  21. using TEAMModelOS.SDK.Extension;
  22. using TEAMModelOS.SDK.Models.Dtos;
  23. using static Azure.Core.HttpHeader;
  24. using static OpenXmlPowerTools.RevisionProcessor;
  25. using static TEAMModelOS.SDK.Models.Service.SystemService;
  26. namespace TEAMModelOS.SDK.Models.Service
  27. {
  28. public static class SystemService
  29. {
  30. public static async Task RecordAccumulateData(AzureRedisFactory azureRedis, DingDing dingDing, Accumulate accumulate)
  31. {
  32. if (!string.IsNullOrWhiteSpace(accumulate.key) && !string.IsNullOrWhiteSpace(accumulate.target) &&
  33. !string.IsNullOrWhiteSpace(accumulate.id) && !string.IsNullOrWhiteSpace(accumulate.name) &&
  34. !string.IsNullOrWhiteSpace(accumulate.scope) && !string.IsNullOrWhiteSpace(accumulate.client))
  35. {
  36. await RecordAccumulateData(azureRedis, accumulate.key, accumulate.target, accumulate.id, accumulate.name, accumulate.scope, accumulate.client, accumulate.count);
  37. }
  38. else
  39. {
  40. await dingDing.SendBotMsg($"IES累计数据变更统计参数异常,{accumulate.ToJsonString()}", GroupNames.成都开发測試群組);
  41. }
  42. }
  43. /// <summary>
  44. /// 记录累计数据
  45. /// </summary>
  46. public static async Task RecordAccumulateData(AzureRedisFactory azureRedis, string key, string target, string id, string name, string scope, string client, int count)
  47. {
  48. if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(target) &&
  49. !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(name) &&
  50. !string.IsNullOrWhiteSpace(scope)&& !string.IsNullOrWhiteSpace(client))
  51. {
  52. //处理UTC时差
  53. var nowTime = DateTimeOffset.UtcNow.GetGMTTime();
  54. int difference = (DayOfWeek.Sunday - nowTime.DayOfWeek + 7) % 7; //1-7的结果0-6
  55. var day = nowTime.ToString("yyyyMMdd");
  56. string redisKey = $"Accumulate:Daily:{scope}:{key}:{day}";
  57. string member = $"{target}::{id}::{client}::{name}";
  58. await azureRedis.GetRedisClient(8).SortedSetIncrementAsync(redisKey, member, count);
  59. await azureRedis.GetRedisClient(8).KeyExpireAsync(redisKey, new TimeSpan((difference+1)*24, 10, 0));
  60. //if (key.Equals("lesson") || key.StartsWith("login_"))
  61. //{
  62. // redisKey = $"Accumulate:Daily:ies:{key}:{day}";
  63. // if (scope.Equals("school"))
  64. // {
  65. // member = $"ies::{id}::{name}";
  66. // }
  67. // else {
  68. // member = $"ies::ies::{name}";
  69. // }
  70. // await azureRedis.GetRedisClient(8).SortedSetIncrementAsync(redisKey, member, 1);
  71. //}
  72. }
  73. }
  74. static double GetUserDuration(List<long> times )
  75. {
  76. if (times.IsNotEmpty() && times.Count>=2)
  77. {
  78. double totalDuration = 0;
  79. // DateTime lastTime = DateTimeOffset.FromUnixTimeMilliseconds((long)jsonData[0]["time"]).UtcDateTime;
  80. long ltime = times[0];
  81. for (int i = 1; i < times.Count; i++)
  82. {
  83. long ctime = times[i];
  84. //DateTime currentTime = DateTimeOffset.FromUnixTimeMilliseconds((long)jsonData[i]["time"]).UtcDateTime;
  85. long timeDifference = ctime - ltime;
  86. ///如果一小时内连续操作,则按真实时间累计
  87. if (timeDifference < 3600000)
  88. {
  89. totalDuration += timeDifference;
  90. }
  91. else
  92. { ///如果一小时内没有连续操作,则按象征性加10秒,以确保数据有效性。 如果因为一小时没有操作,则表示没有新的接口再次请求,当即就已经退出系统。否则后续仍然会有接口进入,并且带有时间戳
  93. totalDuration += 10000;
  94. }
  95. ltime = ctime;
  96. }
  97. return totalDuration;
  98. }
  99. else {
  100. return 10000;
  101. }
  102. }
  103. /// <summary>
  104. /// 结算访问日志
  105. /// </summary>
  106. public static async Task VisitSettle(List<string> times ,AzureStorageFactory _azureStorage,AzureRedisFactory _azureRedis, Region2LongitudeLatitudeTranslator _longitudeLatitudeTranslator, IPSearcher _ipSearcher) {
  107. foreach (var timeDate in times)
  108. {
  109. List<ApiVist> apiVists = new List<ApiVist>();
  110. if (DateTimeOffset.TryParse(timeDate, out DateTimeOffset date))
  111. {
  112. var BlobClient = _azureStorage.GetBlobContainerClient("0-service-log").GetBlobClient($"http-log/{date:yyyy}/{date:MM}/{date:dd}/index.log");
  113. BlobDownloadResult result = await _azureStorage.GetBlobContainerClient("0-service-log").GetBlobClient($"http-log/{date:yyyy}/{date:MM}/{date:dd}/index.log").DownloadContentAsync();
  114. var content = result.Content.ToString();
  115. content= content.Substring(0, content.Length-2);
  116. if (content.EndsWith("}"))
  117. {
  118. content=$"[{content}]";
  119. }
  120. else
  121. {
  122. content=$"[{content}}}]";
  123. }
  124. apiVists.AddRange(content.ToObject<List<ApiVist>>());
  125. var dateNow = DateTimeOffset.Now.GetGMTTime(8);
  126. if ($"{dateNow:yyyy-MM-dd}".Equals($"{date:yyyy-MM-dd}"))
  127. { //当前小时一致的
  128. BlobDownloadResult resultHour = await _azureStorage.GetBlobContainerClient("0-service-log").GetBlobClient($"http-log/{date:yyyy}/{date:MM}/{date:dd}/{date:HH}.log").DownloadContentAsync();
  129. var contentHour = resultHour.Content.ToString();
  130. contentHour= contentHour.Substring(0, contentHour.Length-2);
  131. if (contentHour.EndsWith("}"))
  132. {
  133. contentHour=$"[{contentHour}]";
  134. }
  135. else
  136. {
  137. contentHour=$"[{contentHour}}}]";
  138. }
  139. var httpLog = contentHour.ToObject<List<HttpLog>>();
  140. (ConcurrentBag<ApiVist> vists, ConcurrentBag<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo) = await SystemService.ConvertHttpLog(httpLog, _azureRedis, _ipSearcher, _longitudeLatitudeTranslator, dateNow, false);
  141. apiVists.AddRange(vists);
  142. }
  143. }
  144. //处理教师使用时长
  145. var groupUsers= apiVists.Where(x => !string.IsNullOrWhiteSpace(x.userId)).GroupBy(x=>x.userId).Select(x=> new { key = x.Key, list = x.ToList() });
  146. foreach (var user in groupUsers)
  147. {
  148. var vistTimes = user.list.OrderBy(x => x.time);
  149. var duration= GetUserDuration(vistTimes.Select(x => x.time).ToList());
  150. }
  151. //处理学校使用时长
  152. var groupSchools = apiVists.Where(x => !string.IsNullOrWhiteSpace(x.school) ).GroupBy(x => x.school).Select(x => new { key = x.Key, list = x.ToList() });
  153. foreach (var school in groupSchools) {
  154. var vistTimes = school.list.OrderBy(x => x.time);
  155. var duration = GetUserDuration(vistTimes.Select(x => x.time).ToList());
  156. }
  157. var clientProvince = apiVists.GroupBy(x => $"{x.client}::{x.province}").Select(x => new CountData { pk=x.Key.Split("::")[0], sk=x.Key.Split("::")[1], count=x.Count() }).OrderByDescending(x => x.count);
  158. var clientUser = apiVists.GroupBy(x => $"{x.client}::{x.userId}::{x.scope}").Select(x => new CountData { pk=x.Key.Split("::")[0], sk=x.Key.Split("::")[1], sp=x.Key.Split("::")[2], count=x.Count() }).OrderByDescending(x => x.count);
  159. var clientSchool = apiVists.GroupBy(x => $"{x.client}::{x.school}::{x.scope}").Select(x => new CountData { pk=x.Key.Split("::")[0], sk=x.Key.Split("::")[1], sp=x.Key.Split("::")[2], count=x.Count() }).OrderByDescending(x => x.count);
  160. var clientSchoolLesson = apiVists.Where(x => x.path.Contains("hiteach/create-lesson")).GroupBy(x => $"{x.client}::{x.school}::{x.scope}").Select(x => new CountData { pk=x.Key.Split("::")[0], sk=x.Key.Split("::")[1], sp=x.Key.Split("::")[2], count=x.Count() }).OrderByDescending(x => x.count);
  161. Dictionary<string, List<CountData>> ldatas = new Dictionary<string, List<CountData>>();
  162. foreach (var data in clientSchoolLesson)
  163. {
  164. if (!ldatas.ContainsKey(data.pk))
  165. {
  166. ldatas[data.pk] = new List<CountData>();
  167. }
  168. ldatas[data.pk].Add(data);
  169. }
  170. Dictionary<string, List<CountData>> sdatas = new Dictionary<string, List<CountData>>();
  171. foreach (var data in clientSchool)
  172. {
  173. if (!sdatas.ContainsKey(data.pk))
  174. {
  175. sdatas[data.pk] = new List<CountData>();
  176. }
  177. sdatas[data.pk].Add(data);
  178. }
  179. Dictionary<string, List<CountData>> udatas = new Dictionary<string, List<CountData>>();
  180. foreach (var data in clientUser)
  181. {
  182. if (!udatas.ContainsKey(data.pk))
  183. {
  184. udatas[data.pk] = new List<CountData>();
  185. }
  186. udatas[data.pk].Add(data);
  187. }
  188. Dictionary<string, List<CountData>> pdatas = new Dictionary<string, List<CountData>>();
  189. foreach (var data in clientProvince)
  190. {
  191. if (!pdatas.ContainsKey(data.pk))
  192. {
  193. pdatas[data.pk] = new List<CountData>();
  194. }
  195. pdatas[data.pk].Add(data);
  196. }
  197. }
  198. }
  199. public static async Task<(ConcurrentBag<ApiVist> vists, ConcurrentBag<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo)>
  200. ConvertHttpLog(List<HttpLog> logs, AzureRedisFactory _azureRedis, IPSearcher _ipSearcher, Region2LongitudeLatitudeTranslator _longitudeLatitudeTranslator, DateTimeOffset gmt8Time, bool test = false)
  201. {
  202. ConcurrentBag<ApiVist> vists = new ConcurrentBag<ApiVist>();
  203. ConcurrentBag<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo = new ConcurrentBag<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)>();
  204. object lockObj = new object();
  205. await Parallel.ForEachAsync(logs, async (log, _) =>
  206. {
  207. string uuid = Guid.NewGuid().ToString();
  208. List<string> schoolMatch = new List<string>();
  209. List<string> useridMatch = new List<string>();
  210. var vist = new ApiVist()
  211. {
  212. id=uuid,
  213. ip=log.ip,
  214. tid=log.tid,
  215. time= log.time,
  216. userId= log.id,
  217. school= log.school,
  218. tname= log.name,
  219. path = log.path,
  220. client=log.p.Equals("os", StringComparison.OrdinalIgnoreCase) ? "ies5" : log.p,
  221. scope=log.scope,
  222. host= log.host,
  223. hostName=log.hostName,
  224. l=log.l,
  225. year = $"{gmt8Time:yyyy}",
  226. month = $"{gmt8Time:MM}",
  227. day = $"{gmt8Time:dd}",
  228. hour =$"{gmt8Time:HH}"
  229. };
  230. if (test)
  231. {
  232. var time = DateTimeOffset.FromUnixTimeMilliseconds(log.time);
  233. //本地调试时间
  234. if (vist.ip.Equals("0.0.0.1"))
  235. {
  236. time= time.AddHours(8);
  237. }
  238. vist.year = $"{time:yyyy}";
  239. vist.month = $"{time:MM}";
  240. vist.day = $"{time:dd}";
  241. vist.hour =$"{time:HH}";
  242. }
  243. if (string.IsNullOrWhiteSpace(vist.userId))
  244. {
  245. //var jsonPathContext = new JsonPathContext();
  246. //jsonPathContext.ValueSystem= new JsonTextValueSystem();
  247. string path = "$..['id_token','idToken','idtoken','tmdid','id','teacherId','teacher','tid','tId','userid','userId','code','studentId','student','studentid']";
  248. JObject jsonObject = JObject.Parse(log.param.GetRawText());
  249. //var nodes_path = jsonPathContext.SelectNodes(log.param, path);
  250. var nodes_path = jsonObject.SelectTokens(path);
  251. foreach (var node in nodes_path)
  252. {
  253. // 只获取是字符串的
  254. if (node.Type.Equals(JTokenType.String))
  255. {
  256. switch (true)
  257. {
  258. case bool when node.Path.Contains("id_token")||node.Path.Contains("idToken")||node.Path.Contains("idtoken"):
  259. {
  260. try
  261. {
  262. var jwt = new JwtSecurityToken($"{node}");
  263. string id = jwt.Payload.Sub;
  264. var name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
  265. if (!string.IsNullOrWhiteSpace(id) && long.TryParse(id, out long _id))
  266. {
  267. vist.userId=id;
  268. vist.scope="teacher";
  269. vist.tname=name;
  270. useridMatch.Add(id);
  271. }
  272. }
  273. catch (Exception ex) { }
  274. break;
  275. }
  276. case bool when node.Path.Contains("tmdid")||node.Path.Contains("id")||node.Path.Contains("teacherId")
  277. ||node.Path.Contains("teacher")||node.Path.Contains("tid")||node.Path.Contains("tId")||node.Path.Contains("userid")
  278. ||node.Path.Contains("userId"):
  279. {
  280. if (!string.IsNullOrWhiteSpace($"{node}") && long.TryParse($"{node}", out long _id))
  281. {
  282. vist.userId=$"{node}";
  283. vist.scope="teacher";
  284. useridMatch.Add($"{node}");
  285. }
  286. break;
  287. }
  288. case bool when node.Path.Contains("studentId")||node.Path.Contains("student")||node.Path.Contains("studentid"):
  289. {
  290. if (!string.IsNullOrWhiteSpace($"{node}") && long.TryParse($"{node}", out long _id))
  291. {
  292. vist.userId=$"{node}";
  293. vist.scope="student";
  294. useridMatch.Add($"{node}");
  295. }
  296. break;
  297. }
  298. case bool when node.Path.Contains("code"):
  299. {
  300. if (!string.IsNullOrWhiteSpace($"{node}"))
  301. {
  302. if (long.TryParse($"{node}", out long _id))
  303. {
  304. vist.userId=$"{node}";
  305. useridMatch.Add($"{node}");
  306. }
  307. else
  308. {
  309. string[] codes = $"{node}".Split("-");
  310. foreach (var _code in codes)
  311. {
  312. if (long.TryParse(_code, out long _codeid))
  313. {
  314. vist.userId=$"{node}";
  315. useridMatch.Add($"{_code}");
  316. break;
  317. }
  318. }
  319. }
  320. }
  321. break;
  322. }
  323. }
  324. }
  325. }
  326. if (log.path.Contains("process-notify", StringComparison.OrdinalIgnoreCase))
  327. {
  328. string s = log.param.ToJsonString().Replace("\\", "");
  329. Regex regextmdid = new Regex("\"tmdid\":\"(\\d+)\"");
  330. Match matchtmdid = regextmdid.Match(s);
  331. if (matchtmdid.Success)
  332. {
  333. var t = matchtmdid.Groups[1].Value;
  334. if (!string.IsNullOrWhiteSpace(t))
  335. {
  336. vist.userId=t;
  337. vist.scope="teacher";
  338. useridMatch.Add(t);
  339. }
  340. }
  341. Regex regexname = new Regex("\"tmdname\":\"(.+?)\"");
  342. Match matchname = regexname.Match(s);
  343. if (matchname.Success)
  344. {
  345. var t = matchname.Groups[1].Value;
  346. if (!string.IsNullOrWhiteSpace(t))
  347. {
  348. vist.tname=t;
  349. }
  350. }
  351. }
  352. }
  353. else
  354. {
  355. if (string.IsNullOrWhiteSpace($"{vist.scope}"))
  356. {
  357. vist.scope="teacher";
  358. uuidInfo.Add((uuid, log, new List<string>() { vist.userId }, new List<string>()));
  359. }
  360. }
  361. if (string.IsNullOrWhiteSpace(vist.school) || vist.school.Equals("true") || vist.school.Equals("false"))
  362. {
  363. vist.school="";
  364. string path = "$..['school','id','schoolId','schoolid','schoolCode','school_code','schoolcode','code']";
  365. JObject jsonObject = JObject.Parse(log.param.GetRawText());
  366. var nodes_path = jsonObject.SelectTokens(path);
  367. foreach (var node in nodes_path)
  368. {
  369. // 只获取是字符串的
  370. if (node.Type.Equals(JTokenType.String))
  371. {
  372. switch (true)
  373. {
  374. case bool when node.Path.Contains("school")||node.Path.Contains("id")||node.Path.Contains("schoolId")
  375. ||node.Path.Contains("schoolid")||node.Path.Contains("schoolCode")||node.Path.Contains("school_code")||node.Path.Contains("schoolcode"):
  376. {
  377. if (!$"{node}".Contains("-")&& $"{node}".Length<=8 && $"{node}".Length>=1)
  378. {
  379. vist.school=$"{node}";
  380. schoolMatch.Add($"{node}");
  381. }
  382. break;
  383. }
  384. case bool when node.Path.Contains("code"):
  385. {
  386. if (!$"{node}".Contains("-")&& $"{node}".Length<=8&& $"{node}".Length>=1)
  387. {
  388. vist.school=$"{node}";
  389. schoolMatch.Add($"{node}");
  390. }
  391. else
  392. {
  393. string[] codes = $"{node}".Split("-");
  394. foreach (var _code in codes)
  395. {
  396. if ($"{_code}".Length<=8 && $"{_code}".Length>=1)
  397. {
  398. vist.school=$"{_code}";
  399. schoolMatch.Add($"{_code}");
  400. break;
  401. }
  402. }
  403. }
  404. break;
  405. }
  406. }
  407. }
  408. }
  409. if (log.path.Contains("process-notify", StringComparison.OrdinalIgnoreCase))
  410. {
  411. string s = log.param.ToJsonString().Replace("\\", "");
  412. Regex regexname = new Regex("\"schoolId\":\"(.+?)\"");
  413. Match matchname = regexname.Match(s);
  414. if (matchname.Success)
  415. {
  416. var t = matchname.Groups[1].Value;
  417. if (!string.IsNullOrWhiteSpace(t))
  418. {
  419. vist.school=t;
  420. }
  421. }
  422. }
  423. }
  424. //处理 client
  425. {
  426. if (!string.IsNullOrWhiteSpace(log.client))
  427. {
  428. if (log.client.Equals("IES", StringComparison.OrdinalIgnoreCase))
  429. {
  430. vist.client="ies5";
  431. }
  432. if (log.client.Equals("AClassONE", StringComparison.OrdinalIgnoreCase))
  433. {
  434. vist.client="aclassone";
  435. }
  436. if (log.client.Equals("BB", StringComparison.OrdinalIgnoreCase))
  437. {
  438. vist.client="habb";
  439. }
  440. if (log.client.Equals("HiTool", StringComparison.OrdinalIgnoreCase) ||log.client.Equals("HiTools", StringComparison.OrdinalIgnoreCase))
  441. {
  442. vist.client="hiscan";
  443. }
  444. if (log.client.Equals("HiTA", StringComparison.OrdinalIgnoreCase))
  445. {
  446. vist.client="hita";
  447. vist.scope="teacher";
  448. }
  449. if (log.client.Equals("HiTeachCC", StringComparison.OrdinalIgnoreCase))
  450. {
  451. vist.client="hiteachcc";
  452. }
  453. if (log.client.Equals("HiTeach", StringComparison.OrdinalIgnoreCase))
  454. {
  455. vist.scope="teacher";
  456. vist.client="hiteach";
  457. }
  458. if (log.client.Equals("Open", StringComparison.OrdinalIgnoreCase))
  459. {
  460. vist.client="open";
  461. }
  462. }
  463. }
  464. //补全站点
  465. {
  466. if (
  467. (log.host.Equals("wwww.teammodel.net")||log.host.Equals("ies5-rc.teammodel.net")))
  468. {
  469. vist.hostName="国际站";
  470. vist.host="www.teammodel.net";
  471. vist.client="ies5";
  472. vist.l="Global";
  473. }
  474. else if (
  475. log.host.Equals("teammodelos-yx.chinacloudsites.cn")||log.host.Equals("teammodelos.chinacloudsites.cn")
  476. ||log.host.Equals("yx.teammodel.cn")||log.host.Equals("teammodelos-rc.chinacloudsites.cn")||log.host.Equals("rc.teammodel.cn")|| log.host.Equals("www.teammodel.cn"))
  477. {
  478. vist.hostName="大陆站";
  479. vist.host="www.teammodel.cn";
  480. vist.client="ies5"; vist.l="China";
  481. }
  482. else if ((log.host.Contains("localhost") && log.p.Equals("os"))|| log.host.Equals("teammodelos-test.chinacloudsites.cn") ||log.host.Equals("test.teammodel.cn"))
  483. {
  484. vist.hostName="测试站";
  485. vist.host="test.teammodel.cn";
  486. vist.client="ies5";
  487. vist.l="China";
  488. }
  489. else if (
  490. (log.host.Equals("scyx.teammodel.cn") ||log.host.Equals("jinniu.teammodel.cn")))
  491. {
  492. vist.hostName="研修2.0";
  493. vist.host="scyx.teammodel.cn";
  494. vist.client="ability"; vist.l="China";
  495. }
  496. else if (
  497. log.host.Equals("open.teammodel.cn")||log.host.Equals("open-test.teammodel.cn") ||log.host.Equals("zhiyin-test.teammodel.cn"))
  498. {
  499. vist.hostName="开放平台";
  500. vist.host="open.teammodel.cn";
  501. vist.client="open";
  502. vist.l="China";
  503. }
  504. else if ((log.host.Equals("bi-rc.teammodel.net") || log.host.Equals("bi.teammodel.net")))
  505. {
  506. vist.hostName="国际站";
  507. vist.host="bi.teammodel.net";
  508. vist.client="bi";
  509. vist.scope="admin";
  510. vist.l="Global";
  511. }
  512. else if (log.host.Equals("teammodelbi.chinacloudsites.cn") ||log.host.Equals("bi.teammodel.cn"))
  513. {
  514. vist.hostName="大陆站";
  515. vist.host="bi.teammodel.cn";
  516. vist.client="bi";
  517. vist.scope="admin";
  518. vist.l="China";
  519. }
  520. else if (log.host.Equals("bitest.teammodel.cn")||log.host.Equals("teammodelbi-test.chinacloudsites.cn")||(log.host.Contains("localhost") && (log.p.Equals("bi"))))
  521. {
  522. vist.hostName="测试站";
  523. vist.host="testbi.teammodel.cn";
  524. vist.client="bi";
  525. vist.scope="admin";
  526. vist.l="China";
  527. }
  528. else if (
  529. log.host.Equals("teamcontest.chinacloudsites.cn")||log.host.Equals("contest.chinacloudsites.cn")||log.host.Equals("contest-test.chinacloudsites.cn"))
  530. {
  531. vist.hostName="大陆站";
  532. vist.host="contest.teammodel.cn";
  533. vist.client="contest"; vist.l="China";
  534. }
  535. else if (
  536. log.host.Equals("hiteachcc.chinacloudsites.cn"))
  537. {
  538. vist.hostName="正式站";
  539. vist.host="hiteachcc.teammodel.cn";
  540. vist.client="hiteachcc";
  541. vist.l="China";
  542. }
  543. else if (log.host.Equals("appraisal.chinacloudsites.cn"))
  544. {
  545. vist.hostName="大陆站";
  546. vist.host="appraisal.teammodel.cn";
  547. vist.client="appraisal";
  548. vist.l="China";
  549. }
  550. else if ((log.host.Contains("localhost") && log.p.Equals("appraisal"))||log.host.Equals("appraisal-test.teammodel.cn") ||log.host.Equals("appraisal-test.chinacloudsites.cn"))
  551. {
  552. vist.hostName="测试站";
  553. vist.host="appraisal-test.teammodel.cn";
  554. vist.client="appraisal";
  555. vist.l="China";
  556. }
  557. else
  558. {
  559. if (!string.IsNullOrWhiteSpace(log.p))
  560. {
  561. vist.client=log.p.Equals("os", StringComparison.OrdinalIgnoreCase) ? "ies5" : log.p;
  562. }
  563. else
  564. {
  565. vist.client="other";
  566. }
  567. if (log.host.EndsWith(".cn"))
  568. {
  569. vist.hostName="大陆站";
  570. vist.l="China";
  571. }
  572. else if (log.host.EndsWith(".net"))
  573. {
  574. vist.hostName="国际站";
  575. vist.l="Global";
  576. }
  577. else
  578. {
  579. vist.hostName="其他";
  580. vist.l="其他";
  581. }
  582. }
  583. }
  584. //补全产品端
  585. {
  586. //研修2.0
  587. if (log.path.Contains("research") || log.path.Contains("study") || log.path.Contains("standard-file"))
  588. {
  589. vist.client="ability";
  590. }
  591. if (log.path.Contains("teacher"))
  592. {
  593. vist.scope="teacher";
  594. }
  595. if (log.path.Contains("tmduser"))
  596. {
  597. vist.scope=Constant.ScopeTmdUser;
  598. }
  599. if (log.path.Contains("student/login"))
  600. {
  601. vist.scope=Constant.ScopeStudent;
  602. }
  603. if (log.path.StartsWith("/activity"))
  604. {
  605. vist.client="contest";
  606. }
  607. //小程序
  608. if (log.path.Contains("aclassone"))
  609. {
  610. vist.client="aclassone";
  611. }
  612. // /// <summary>
  613. /// ExamInfo qamode 書面問答類型 0:書面問答 1:紙本測驗 2:艺术评测
  614. /// </summary>
  615. //艺术评测
  616. if (log.path.Contains("art") ||log.path.Contains("aclassone/find-children-activity") ||log.path.Contains("aclassone/find-teacher-activity") ||log.path.Contains("aclassone/find-summary-activity") ||log.path.Contains("aclassone/upload-all") ||log.path.Contains("aclassone/delete"))
  617. {
  618. vist.client="art";
  619. }
  620. if (log.path.Contains("common/exam/upsert-record"))
  621. {
  622. JObject jobject = JObject.Parse(log.param.GetRawText());
  623. var jtokens = jobject.SelectTokens("$..artId");
  624. if (jtokens!=null && jtokens.Count()>0)
  625. {
  626. vist.client="art";
  627. vist.scope=Constant.ScopeStudent;
  628. }
  629. }
  630. if (log.path.Contains("habb"))
  631. {
  632. vist.client="habb";
  633. }
  634. //阅卷客户端
  635. if (log.path.Contains("hiscan"))
  636. {
  637. vist.client="hiscan";
  638. }
  639. if (log.path.Contains("hita"))
  640. {
  641. vist.client="hita";
  642. }
  643. if (log.path.Contains("hiteachcc"))
  644. {
  645. vist.client="hiteachcc";
  646. }
  647. if (log.path.Contains("sokrate"))
  648. {
  649. vist.client="sokrate";
  650. }
  651. if (log.path.Contains("sokrate") || log.path.Contains("score"))
  652. {
  653. vist.client="sokrate";
  654. }
  655. if (log.path.Contains("hiteach"))
  656. {
  657. vist.client="hiteach";
  658. }
  659. ///IES开放平台
  660. if (log.path.Contains("business") || log.path.Contains("biz") || log.path.Contains("openapi-config") || log.path.Contains("open-api"))
  661. {
  662. vist.client="open";
  663. }
  664. //从token的role 能否获取 开放平台
  665. //单点登录及第三方接口
  666. if (log.path.Contains("lepei") || log.path.Contains("sc/") || log.path.Contains("/sso") || log.path.Contains("sc-init")|| log.path.Contains("moofen") || log.path.Contains("data-push") || log.path.Contains("xkw")|| log.path.Contains("tianbo")
  667. || log.path.Contains("oauth/check-bind")|| log.path.Contains("dingding") || log.path.Contains("wechat")
  668. )
  669. {
  670. vist.client="sso-third";
  671. }
  672. }
  673. //处理IP转地区
  674. var region = await _ipSearcher.SearchIpAsync(vist.ip);
  675. if (string.IsNullOrWhiteSpace(region))
  676. {
  677. region="未知IP·未知IP·未知IP";
  678. }
  679. if (!string.IsNullOrWhiteSpace(region))
  680. {
  681. region= region.Replace("省·", "·").Replace("市·", "·").Replace("特别行政区·", "·").Replace("藏族羌族自治州·", "·");
  682. var regions = region.Split("·");
  683. if (regions.Length==4)
  684. {
  685. vist.area= regions[0];
  686. vist.province = regions[1];
  687. vist.city = regions[2];
  688. }
  689. if (regions.Length==3)
  690. {
  691. vist.area= regions[0];
  692. vist.province = regions[1];
  693. }
  694. if (regions.Length==2)
  695. {
  696. vist.area= regions[0];
  697. vist.province = regions[1];
  698. }
  699. if (regions.Length==1)
  700. {
  701. vist.area= regions[0];
  702. }
  703. }
  704. //处理地区转经纬度
  705. {
  706. IEnumerable<JToken> tokens = default;
  707. if (!string.IsNullOrWhiteSpace(vist.city) && !string.IsNullOrWhiteSpace(vist.province) && !string.IsNullOrWhiteSpace(vist.area))
  708. {
  709. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.province=~ /.*{vist.province}/i && @.city=~ /.*{vist.city}/i)]");
  710. if (!(tokens.Any() && tokens.Count()>0))
  711. {
  712. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.province=~ /.*{vist.city}/i && @.city=~ /.*{vist.province}/i)]");
  713. if (!(tokens.Any() && tokens.Count()>0))
  714. {
  715. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.province=~ /.*{vist.city}/i || @.city=~ /.*{vist.city}/i)]");
  716. }
  717. if (!(tokens.Any() && tokens.Count()>0))
  718. {
  719. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.province=~ /.*{vist.province}/i||@.city=~ /.*{vist.province}/i)]");
  720. }
  721. }
  722. }
  723. else if (string.IsNullOrWhiteSpace(vist.city) && !string.IsNullOrWhiteSpace(vist.province) && !string.IsNullOrWhiteSpace(vist.area))
  724. {
  725. if (vist.area.Equals("中国"))
  726. {
  727. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.province=~ /.*{vist.province}/i)]");
  728. if (!(tokens.Any() && tokens.Count()>0))
  729. {
  730. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.city=~ /.*{vist.province}/i)]");
  731. }
  732. }
  733. else
  734. {
  735. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.city=~ /.*{vist.province}/i || @.province=~ /.*{vist.province}/i)]");
  736. }
  737. }
  738. else if (!string.IsNullOrWhiteSpace(vist.city) && string.IsNullOrWhiteSpace(vist.province)&& !string.IsNullOrWhiteSpace(vist.area))
  739. {
  740. if (vist.area.Equals("中国"))
  741. {
  742. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.province=~ /.*{vist.city}/i)]");
  743. if (!(tokens.Any() && tokens.Count()>0))
  744. {
  745. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.city=~ /.*{vist.province}/i)]");
  746. }
  747. }
  748. else
  749. {
  750. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.city=~ /.*{vist.city}/i || @.city=~ /.*{vist.province}/i)]");
  751. }
  752. }
  753. else if (string.IsNullOrWhiteSpace(vist.city) && string.IsNullOrWhiteSpace(vist.province)&& !string.IsNullOrWhiteSpace(vist.area))
  754. {
  755. tokens= _longitudeLatitudeTranslator.regionJson.SelectTokens($"$..[?(@.country=~ /.*{vist.area}/i && @.m=='1')]");
  756. }
  757. if (tokens!=null && tokens.Any())
  758. {
  759. List<RegionLngLat> regionLngLats = new List<RegionLngLat>();
  760. foreach (JToken token in tokens)
  761. {
  762. regionLngLats.Add(token.ToString().ToObject<RegionLngLat>());
  763. }
  764. var points = regionLngLats.FindAll(x => string.IsNullOrWhiteSpace(x.area));
  765. if (!points.IsNotEmpty())
  766. {
  767. points= regionLngLats.FindAll(x => !string.IsNullOrWhiteSpace(x.m) && x.m.Equals("1"));
  768. }
  769. if (string.IsNullOrWhiteSpace(vist.city)) {
  770. vist.city=points?.FirstOrDefault()?.city;
  771. if (!string.IsNullOrWhiteSpace(vist.city) && vist.city.EndsWith("市")) {
  772. vist.city=vist.city.Replace("市","");
  773. }
  774. }
  775. vist.lat=points?.FirstOrDefault()?.lat;
  776. vist.lng=points?.FirstOrDefault()?.lng;
  777. }
  778. else
  779. {
  780. if (vist.area.Equals("内网IP"))
  781. {
  782. if (vist.host.Contains(".cn") || vist.host.Contains("localhost"))
  783. {
  784. vist.lat="30.655821878416408";
  785. vist.lng="104.08153351042463";
  786. vist.area="中国";
  787. vist.province="四川";
  788. vist.city="成都";
  789. }
  790. else
  791. {
  792. vist.lat="25.044332";
  793. vist.lng="121.509062";
  794. vist.area="中国";
  795. vist.province="台湾";
  796. vist.city="台湾";
  797. }
  798. }
  799. else
  800. {
  801. vist.lat="30.655821878416408";
  802. vist.lng="104.08153351042463";
  803. vist.area="中国";
  804. vist.province="四川";
  805. vist.city="成都";
  806. }
  807. }
  808. }
  809. uuidInfo.Add((uuid, log, useridMatch, schoolMatch));
  810. vists.Add(vist);
  811. }
  812. );
  813. List<(string tmd, bool exists, string scope)> tmdexists = new List<(string tmd, bool exists, string scope)>();
  814. List<(string sch, bool exists)> schexists = new List<(string sch, bool exists)>();
  815. var tmds = uuidInfo.SelectMany(x => x.tmdid).ToHashSet();
  816. if (tmds.Any())
  817. {
  818. foreach (var tmd in tmds)
  819. {
  820. var exists = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Blob:Catalog:{tmd}");
  821. if (exists)
  822. {
  823. tmdexists.Add((tmd, exists, "teacher"));
  824. }
  825. else
  826. {
  827. exists = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Login:School:hbcn:student:{tmd}");
  828. tmdexists.Add((tmd, exists, "student"));
  829. }
  830. }
  831. }
  832. var schs = uuidInfo.SelectMany(x => x.school).ToHashSet();
  833. if (schs.Any())
  834. {
  835. foreach (var sch in schs)
  836. {
  837. var exists = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Blob:Catalog:{sch}");
  838. schexists.Add((sch, exists));
  839. }
  840. }
  841. foreach (var item in uuidInfo)
  842. {
  843. foreach (var tmd in item.tmdid)
  844. {
  845. var tmdext = tmdexists.Find(x => x.tmd.Equals(tmd));
  846. if (tmdext.tmd!= null && tmdext.exists)
  847. {
  848. var vist = vists.Where(x => x.id.Equals(item.uuid));
  849. foreach (var vi in vist)
  850. {
  851. vi.userId=tmd;
  852. if (string.IsNullOrWhiteSpace(vi.scope))
  853. {
  854. vi.scope=tmdext.scope;
  855. }
  856. }
  857. break;
  858. }
  859. }
  860. foreach (var sch in item.school)
  861. {
  862. var schext = schexists.Find(x => x.sch.Equals(sch));
  863. if (schext.sch!= null && schext.exists)
  864. {
  865. var vist = vists.Where(x => x.id.Equals(item.uuid));
  866. foreach (var vi in vist)
  867. {
  868. vi.school=sch;
  869. }
  870. break;
  871. }
  872. }
  873. }
  874. return (vists, uuidInfo);
  875. }
  876. public class ApiVist
  877. {
  878. public string id { get; set; }
  879. public string path { get; set; }
  880. /// <summary>
  881. /// 细分
  882. /// ies5 ,hiteach,hita,cc,bi,contest,open,aclassone,sokrates,ability,art
  883. /// 产品端
  884. /// </summary>
  885. public string client { get; set; }
  886. /// <summary>
  887. /// 具体功能
  888. /// </summary>
  889. // public string func { get; set; }
  890. public string userId { get; set; }
  891. public string scope { get; set; }
  892. public string tname { get; set; }
  893. public string school { get; set; }
  894. public string ip { get; set; }
  895. //public string region { get; set; }
  896. public string area { get; set; }
  897. public string province { get; set; }
  898. public string city { get; set; } = "";
  899. public long time { get; set; }
  900. /// <summary>
  901. ///
  902. /// </summary>
  903. public string host { get; set; }
  904. public string hostName { get; set; } = "其他";
  905. /// <summary>
  906. /// tokenid
  907. /// </summary>
  908. public string tid { get; set; }
  909. public string year { get; set; }
  910. public string month { get; set; }
  911. public string day { get; set; }
  912. public string hour { get; set; }
  913. //public RegionLngLat point { get; set; }
  914. public string lat { get; set; }
  915. public string lng { get; set; }
  916. public string l { get; set; }
  917. }
  918. public class HttpLog
  919. {
  920. public string ip { get; set; }
  921. public long time { get; set; }
  922. public string host { get; set; }
  923. public string hostName = "其他";
  924. public string tid { get; set; }
  925. public string path { get; set; }
  926. public string client { get; set; }
  927. public JsonElement param { get; set; }
  928. public string id { get; set; }
  929. public string name { get; set; }
  930. public string school { get; set; }
  931. public string p { get; set; }
  932. // public string ua { get; set; }
  933. // public string referer { get; set; }
  934. public string scope { get; set; }
  935. public string year { get; set; }
  936. public string month { get; set; }
  937. public string day { get; set; }
  938. public string hour { get; set; }
  939. public string l { get; set; }
  940. }
  941. public record RegionLngLat
  942. {
  943. public string country { get; set; }
  944. public string province { get; set; }
  945. public string city { get; set; }
  946. public string lat { get; set; }
  947. public string lng { get; set; }
  948. public string area { get; set; }
  949. public string m { get; set; } = "0";
  950. }
  951. public class CountData
  952. {
  953. public string pk { get; set; } = "";
  954. public string sk { get; set; } = "";
  955. public string sp { get; set; } = "";
  956. public int count { get; set; }
  957. }
  958. public class VistStickiness {
  959. public string last { get; set; }
  960. /// <summary>
  961. /// 名字
  962. /// </summary>
  963. public string name { get; set; }
  964. /// <summary>
  965. /// 编码
  966. /// </summary>
  967. public string code { get; set; }
  968. //排名
  969. public int rank { get; set; }
  970. /// <summary>
  971. /// 排名上升下降
  972. /// </summary>
  973. public int updown { get; set; } = 0;
  974. #region tmd
  975. public double stickiness_tmd { get; set; }
  976. public double updown_stickiness_tmd { get; set; }
  977. public double rank_stickiness_tmd { get; set; }
  978. public double duration_tmd { get; set; }
  979. public double updown_duration_tmd { get; set; }
  980. public double rank_duration_tmd { get; set; }
  981. public double count_tmd { get; set; }
  982. public double updown_count_tmd { get; set;}
  983. public double rank_count_tmd { get; set; }
  984. #endregion
  985. #region hiteach
  986. public double stickiness_hiteach { get; set; }
  987. public double updown_stickiness_hiteach { get; set; }
  988. public double rank_stickiness_hiteach { get; set; }
  989. public double duration_hiteach { get; set; }
  990. public double updown_duration_hiteach { get; set; }
  991. public double rank_duration_hiteach { get; set; }
  992. public double count_hiteach { get; set; }
  993. public double updown_count_hiteach { get; set; }
  994. public double rank_count_hiteach { get; set; }
  995. public double lesson_hiteach { get; set; }
  996. public double updown_lesson_hiteach { get; set; }
  997. public double rank_lesson_hiteach { get; set; }
  998. #endregion
  999. #region hita
  1000. public double stickiness_hita { get; set; }
  1001. public double updown_stickiness_hita { get; set; }
  1002. public double rank_stickiness_hita { get; set; }
  1003. public double duration_hita { get; set; }
  1004. public double updown_duration_hita { get; set; }
  1005. public double rank_duration_hita { get; set; }
  1006. public double count_hita { get; set; }
  1007. public double updown_count_hita { get; set; }
  1008. public double rank_count_hita { get; set; }
  1009. #endregion
  1010. #region ies5
  1011. public double stickiness_ies5 { get; set; }
  1012. public double updown_stickiness_ies5 { get; set; }
  1013. public double rank_stickiness_ies5 { get; set; }
  1014. public double duration_ies5 { get; set; }
  1015. public double updown_duration_ies5 { get; set; }
  1016. public double rank_duration_ies5 { get; set; }
  1017. public double count_ies5 { get; set; }
  1018. public double updown_count_ies5 { get; set; }
  1019. public double rank_count_ies5 { get; set; }
  1020. #endregion
  1021. #region other
  1022. public double stickiness_other { get; set; }
  1023. public double updown_stickiness_other { get; set; }
  1024. public double rank_stickiness_other { get; set; }
  1025. public double duration_other { get; set; }
  1026. public double updown_duration_other { get; set; }
  1027. public double rank_duration_other { get; set; }
  1028. public double count_other { get; set; }
  1029. public double updown_count_other { get; set; }
  1030. public double rank_count_other { get; set; }
  1031. #endregion
  1032. }
  1033. }
  1034. }