SystemController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using Masuit.MyBlogs.Core.Common;
  2. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  3. using Masuit.MyBlogs.Core.Hubs;
  4. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  5. using Masuit.MyBlogs.Core.Models.Entity;
  6. using Masuit.MyBlogs.Core.Models.Enum;
  7. using Masuit.Tools;
  8. using Masuit.Tools.Hardware;
  9. using Masuit.Tools.Logging;
  10. using Masuit.Tools.Models;
  11. using Masuit.Tools.Systems;
  12. using Microsoft.AspNetCore.Authorization;
  13. using Microsoft.AspNetCore.Mvc;
  14. using Newtonsoft.Json;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Text;
  20. namespace Masuit.MyBlogs.Core.Controllers
  21. {
  22. /// <summary>
  23. /// 系统设置
  24. /// </summary>
  25. public class SystemController : AdminController
  26. {
  27. /// <summary>
  28. /// 系统设置
  29. /// </summary>
  30. public ISystemSettingService SystemSettingService { get; set; }
  31. /// <summary>
  32. /// 获取硬件基本信息
  33. /// </summary>
  34. /// <returns></returns>
  35. public ActionResult GetBaseInfo()
  36. {
  37. List<CpuInfo> cpuInfo = SystemInfo.GetCpuInfo();
  38. RamInfo ramInfo = SystemInfo.GetRamInfo();
  39. string osVersion = SystemInfo.GetOsVersion();
  40. var total = new StringBuilder();
  41. var free = new StringBuilder();
  42. var usage = new StringBuilder();
  43. SystemInfo.DiskTotalSpace().ForEach(kv =>
  44. {
  45. total.Append(kv.Key + kv.Value + " | ");
  46. });
  47. SystemInfo.DiskFree().ForEach(kv => free.Append(kv.Key + kv.Value + " | "));
  48. SystemInfo.DiskUsage().ForEach(kv => usage.Append(kv.Key + kv.Value.ToString("P") + " | "));
  49. IList<string> mac = SystemInfo.GetMacAddress();
  50. IList<string> ips = SystemInfo.GetIPAddress();
  51. var span = DateTime.Now - CommonHelper.StartupTime;
  52. var boot = DateTime.Now - SystemInfo.BootTime();
  53. return Json(new
  54. {
  55. runningTime = $"{span.Days}天{span.Hours}小时{span.Minutes}分钟",
  56. bootTime = $"{boot.Days}天{boot.Hours}小时{boot.Minutes}分钟",
  57. cpuInfo,
  58. ramInfo,
  59. osVersion,
  60. diskInfo = new
  61. {
  62. total = total.ToString(),
  63. free = free.ToString(),
  64. usage = usage.ToString()
  65. },
  66. netInfo = new
  67. {
  68. mac,
  69. ips
  70. }
  71. });
  72. }
  73. /// <summary>
  74. /// 获取历史性能计数器
  75. /// </summary>
  76. /// <returns></returns>
  77. public ActionResult GetHistoryList()
  78. {
  79. return Json(new
  80. {
  81. cpu = MyHub.PerformanceCounter.Select(c => new[]
  82. {
  83. c.Time,
  84. c.CpuLoad
  85. }),
  86. mem = MyHub.PerformanceCounter.Select(c => new[]
  87. {
  88. c.Time,
  89. c.MemoryUsage
  90. }),
  91. temp = MyHub.PerformanceCounter.Select(c => new[]
  92. {
  93. c.Time,
  94. c.Temperature
  95. }),
  96. read = MyHub.PerformanceCounter.Select(c => new[]
  97. {
  98. c.Time,
  99. c.DiskRead
  100. }),
  101. write = MyHub.PerformanceCounter.Select(c => new[]
  102. {
  103. c.Time,
  104. c.DiskWrite
  105. }),
  106. down = MyHub.PerformanceCounter.Select(c => new[]
  107. {
  108. c.Time,
  109. c.Download
  110. }),
  111. up = MyHub.PerformanceCounter.Select(c => new[]
  112. {
  113. c.Time,
  114. c.Upload
  115. }),
  116. });
  117. }
  118. /// <summary>
  119. /// 获取设置信息
  120. /// </summary>
  121. /// <returns></returns>
  122. public ActionResult GetSettings()
  123. {
  124. var list = SystemSettingService.GetAll().Select(s => new
  125. {
  126. s.Name,
  127. s.Value
  128. }).ToList();
  129. return ResultData(list);
  130. }
  131. /// <summary>
  132. /// 获取设置项
  133. /// </summary>
  134. /// <param name="name"></param>
  135. /// <returns></returns>
  136. [AllowAnonymous]
  137. public ActionResult GetSetting(string name)
  138. {
  139. var entity = SystemSettingService.GetFirstEntity(s => s.Name.Equals(name));
  140. return ResultData(entity);
  141. }
  142. /// <summary>
  143. /// 保存设置
  144. /// </summary>
  145. /// <param name="sets"></param>
  146. /// <returns></returns>
  147. public ActionResult Save(string sets)
  148. {
  149. SystemSetting[] settings = JsonConvert.DeserializeObject<List<SystemSetting>>(sets).ToArray();
  150. foreach (var set in settings)
  151. {
  152. var entry = SystemSettingService.GetFirstEntity(s => s.Name.Equals(set.Name));
  153. if (entry is null)
  154. {
  155. SystemSettingService.AddEntity(set);
  156. }
  157. else
  158. {
  159. entry.Value = set.Value;
  160. SystemSettingService.UpdateEntity(entry);
  161. }
  162. }
  163. var b = SystemSettingService.SaveChanges() > 0;
  164. var dic = SystemSettingService.GetAll().ToDictionary(s => s.Name, s => s.Value); //同步设置
  165. foreach (var (key, value) in dic)
  166. {
  167. CommonHelper.SystemSettings.AddOrUpdate(key, value);
  168. }
  169. return ResultData(null, b, b ? "设置保存成功!" : "设置保存失败!");
  170. }
  171. /// <summary>
  172. /// 获取状态
  173. /// </summary>
  174. /// <returns></returns>
  175. public ActionResult GetStatus()
  176. {
  177. Array array = Enum.GetValues(typeof(Status));
  178. var list = new List<object>();
  179. foreach (Enum e in array)
  180. {
  181. list.Add(new
  182. {
  183. e,
  184. name = e.GetDisplay()
  185. });
  186. }
  187. return ResultData(list);
  188. }
  189. /// <summary>
  190. /// 邮件测试
  191. /// </summary>
  192. /// <param name="smtp"></param>
  193. /// <param name="user"></param>
  194. /// <param name="pwd"></param>
  195. /// <param name="port"></param>
  196. /// <param name="to"></param>
  197. /// <returns></returns>
  198. public ActionResult MailTest(string smtp, string user, string pwd, int port, string to)
  199. {
  200. try
  201. {
  202. new Email()
  203. {
  204. EnableSsl = true,
  205. Body = "发送成功,网站邮件配置正确!",
  206. SmtpServer = smtp,
  207. Username = user,
  208. Password = pwd,
  209. SmtpPort = port,
  210. Subject = "网站测试邮件",
  211. Tos = to
  212. }.Send();
  213. return ResultData(null, true, "测试邮件发送成功,网站邮件配置正确!");
  214. }
  215. catch (Exception e)
  216. {
  217. return ResultData(null, false, "邮件配置测试失败!错误信息:\r\n" + e.Message + "\r\n\r\n详细堆栈跟踪:\r\n" + e.StackTrace);
  218. }
  219. }
  220. /// <summary>
  221. /// 路径测试
  222. /// </summary>
  223. /// <param name="path"></param>
  224. /// <returns></returns>
  225. public ActionResult PathTest(string path)
  226. {
  227. if (!(path.EndsWith("/") || path.EndsWith("\\")))
  228. {
  229. return ResultData(null, false, "路径不存在");
  230. }
  231. if (path.Equals("/") || path.Equals("\\"))
  232. {
  233. return ResultData(null, true, "根路径正确");
  234. }
  235. try
  236. {
  237. bool b = Directory.Exists(path);
  238. return ResultData(null, b, b ? "根路径正确" : "路径不存在");
  239. }
  240. catch (Exception e)
  241. {
  242. LogManager.Error(GetType(), e);
  243. return ResultData(null, false, "路径格式不正确!错误信息:\r\n" + e.Message + "\r\n\r\n详细堆栈跟踪:\r\n" + e.StackTrace);
  244. }
  245. }
  246. /// <summary>
  247. /// 清空性能计数器缓存
  248. /// </summary>
  249. /// <returns></returns>
  250. public ActionResult ClearPerfCounter()
  251. {
  252. MyHub.PerformanceCounter.Clear();
  253. return Ok();
  254. }
  255. #region 网站防火墙
  256. /// <summary>
  257. /// 获取全局IP黑名单
  258. /// </summary>
  259. /// <returns></returns>
  260. public ActionResult IpBlackList()
  261. {
  262. return ResultData(CommonHelper.DenyIP);
  263. }
  264. /// <summary>
  265. /// 获取IP地址段黑名单
  266. /// </summary>
  267. /// <returns></returns>
  268. public ActionResult GetIPRangeBlackList()
  269. {
  270. return ResultData(System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "DenyIPRange.txt")));
  271. }
  272. /// <summary>
  273. /// 设置IP地址段黑名单
  274. /// </summary>
  275. /// <returns></returns>
  276. public ActionResult SetIPRangeBlackList(string content)
  277. {
  278. System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "DenyIPRange.txt"), content, Encoding.UTF8);
  279. CommonHelper.DenyIPRange.Clear();
  280. var lines = System.IO.File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "DenyIPRange.txt")).Where(s => s.Split(' ').Length > 2);
  281. foreach (var line in lines)
  282. {
  283. try
  284. {
  285. var strs = line.Split(' ');
  286. CommonHelper.DenyIPRange[strs[0]] = strs[1];
  287. }
  288. catch (IndexOutOfRangeException)
  289. {
  290. }
  291. }
  292. return ResultData(null);
  293. }
  294. /// <summary>
  295. /// 全局IP白名单
  296. /// </summary>
  297. /// <returns></returns>
  298. public ActionResult IpWhiteList()
  299. {
  300. return ResultData(System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "whitelist.txt")));
  301. }
  302. /// <summary>
  303. /// 设置IP黑名单
  304. /// </summary>
  305. /// <param name="content"></param>
  306. /// <returns></returns>
  307. public ActionResult SetIpBlackList(string content)
  308. {
  309. CommonHelper.DenyIP = content;
  310. System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "denyip.txt"), CommonHelper.DenyIP, Encoding.UTF8);
  311. return ResultData(null);
  312. }
  313. /// <summary>
  314. /// 设置IP白名单
  315. /// </summary>
  316. /// <param name="content"></param>
  317. /// <returns></returns>
  318. public ActionResult SetIpWhiteList(string content)
  319. {
  320. System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "whitelist.txt"), content, Encoding.UTF8);
  321. CommonHelper.IPWhiteList.Add(content);
  322. return ResultData(null);
  323. }
  324. /// <summary>
  325. /// 获取拦截日志
  326. /// </summary>
  327. /// <returns></returns>
  328. public ActionResult InterceptLog()
  329. {
  330. var list = RedisHelper.LRange<IpIntercepter>("intercept", 0, -1);
  331. return ResultData(new
  332. {
  333. interceptCount = RedisHelper.Get("interceptCount"),
  334. list
  335. });
  336. }
  337. /// <summary>
  338. /// 清除拦截日志
  339. /// </summary>
  340. /// <returns></returns>
  341. public ActionResult ClearInterceptLog()
  342. {
  343. bool b = RedisHelper.Del("intercept") > 0;
  344. return ResultData(null, b, b ? "拦截日志清除成功!" : "拦截日志清除失败!");
  345. }
  346. /// <summary>
  347. /// 将IP添加到白名单
  348. /// </summary>
  349. /// <param name="ip"></param>
  350. /// <returns></returns>
  351. public ActionResult AddToWhiteList(string ip)
  352. {
  353. if (!ip.MatchInetAddress())
  354. {
  355. return ResultData(null, false);
  356. }
  357. string ips = System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "whitelist.txt"));
  358. List<string> list = ips.Split(',').Where(s => !string.IsNullOrEmpty(s)).ToList();
  359. list.Add(ip);
  360. System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "whitelist.txt"), string.Join(",", list.Distinct()), Encoding.UTF8);
  361. CommonHelper.IPWhiteList = list;
  362. return ResultData(null);
  363. }
  364. /// <summary>
  365. /// 将IP添加到黑名单
  366. /// </summary>
  367. /// <param name="ip"></param>
  368. /// <returns></returns>
  369. public ActionResult AddToBlackList(string ip)
  370. {
  371. if (!ip.MatchInetAddress())
  372. {
  373. return ResultData(null, false);
  374. }
  375. CommonHelper.DenyIP += "," + ip;
  376. System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "denyip.txt"), CommonHelper.DenyIP, Encoding.UTF8);
  377. CommonHelper.IPWhiteList.Remove(ip);
  378. System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "whitelist.txt"), string.Join(",", CommonHelper.IPWhiteList.Distinct()), Encoding.UTF8);
  379. return ResultData(null);
  380. }
  381. #endregion
  382. }
  383. }