system.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. """
  2. 系统管理工具
  3. 实现系统状态查询和爬虫触发功能。
  4. """
  5. from pathlib import Path
  6. from typing import Dict, List, Optional
  7. from ..services.data_service import DataService
  8. from ..utils.validators import validate_platforms
  9. from ..utils.errors import MCPError, CrawlTaskError
  10. class SystemManagementTools:
  11. """系统管理工具类"""
  12. def __init__(self, project_root: str = None):
  13. """
  14. 初始化系统管理工具
  15. Args:
  16. project_root: 项目根目录
  17. """
  18. self.data_service = DataService(project_root)
  19. if project_root:
  20. self.project_root = Path(project_root)
  21. else:
  22. # 获取项目根目录
  23. current_file = Path(__file__)
  24. self.project_root = current_file.parent.parent.parent
  25. def get_system_status(self) -> Dict:
  26. """
  27. 获取系统运行状态和健康检查信息
  28. Returns:
  29. 系统状态字典
  30. Example:
  31. >>> tools = SystemManagementTools()
  32. >>> result = tools.get_system_status()
  33. >>> print(result['system']['version'])
  34. """
  35. try:
  36. # 获取系统状态
  37. status = self.data_service.get_system_status()
  38. return {
  39. "success": True,
  40. "summary": {
  41. "description": "系统运行状态和健康检查信息"
  42. },
  43. "data": status
  44. }
  45. except MCPError as e:
  46. return {
  47. "success": False,
  48. "error": e.to_dict()
  49. }
  50. except Exception as e:
  51. return {
  52. "success": False,
  53. "error": {
  54. "code": "INTERNAL_ERROR",
  55. "message": str(e)
  56. }
  57. }
  58. def trigger_crawl(self, platforms: Optional[List[str]] = None, save_to_local: bool = False, include_url: bool = False) -> Dict:
  59. """
  60. 手动触发一次临时爬取任务(可选持久化)
  61. Args:
  62. platforms: 指定平台列表,为空则爬取所有平台
  63. save_to_local: 是否保存到本地 output 目录,默认 False
  64. include_url: 是否包含URL链接,默认False(节省token)
  65. Returns:
  66. 爬取结果字典,包含新闻数据和保存路径(如果保存)
  67. Example:
  68. >>> tools = SystemManagementTools()
  69. >>> # 临时爬取,不保存
  70. >>> result = tools.trigger_crawl(platforms=['zhihu', 'weibo'])
  71. >>> print(result['data'])
  72. >>> # 爬取并保存到本地
  73. >>> result = tools.trigger_crawl(platforms=['zhihu'], save_to_local=True)
  74. >>> print(result['saved_files'])
  75. """
  76. try:
  77. import time
  78. import yaml
  79. from trendradar.crawler.fetcher import DataFetcher
  80. from trendradar.storage.local import LocalStorageBackend
  81. from trendradar.storage.base import convert_crawl_results_to_news_data
  82. from trendradar.utils.time import get_configured_time, format_date_folder, format_time_filename
  83. from ..services.cache_service import get_cache
  84. # 参数验证
  85. platforms = validate_platforms(platforms)
  86. # 加载配置文件
  87. config_path = self.project_root / "config" / "config.yaml"
  88. if not config_path.exists():
  89. raise CrawlTaskError(
  90. "配置文件不存在",
  91. suggestion=f"请确保配置文件存在: {config_path}"
  92. )
  93. # 读取配置
  94. with open(config_path, "r", encoding="utf-8") as f:
  95. config_data = yaml.safe_load(f)
  96. # 获取平台配置(嵌套结构:{enabled: bool, sources: [...]})
  97. platforms_config = config_data.get("platforms", {})
  98. if not platforms_config.get("enabled", True):
  99. raise CrawlTaskError(
  100. "热榜平台已禁用",
  101. suggestion="请检查 config/config.yaml 中的 platforms.enabled 配置"
  102. )
  103. all_platforms = platforms_config.get("sources", [])
  104. if not all_platforms:
  105. raise CrawlTaskError(
  106. "配置文件中没有平台配置",
  107. suggestion="请检查 config/config.yaml 中的 platforms.sources 配置"
  108. )
  109. # 过滤平台
  110. if platforms:
  111. target_platforms = [p for p in all_platforms if p["id"] in platforms]
  112. if not target_platforms:
  113. raise CrawlTaskError(
  114. f"指定的平台不存在: {platforms}",
  115. suggestion=f"可用平台: {[p['id'] for p in all_platforms]}"
  116. )
  117. else:
  118. target_platforms = all_platforms
  119. # 构建平台ID列表
  120. ids = []
  121. for platform in target_platforms:
  122. if "name" in platform:
  123. ids.append((platform["id"], platform["name"]))
  124. else:
  125. ids.append(platform["id"])
  126. print(f"开始临时爬取,平台: {[p.get('name', p['id']) for p in target_platforms]}")
  127. # 初始化数据获取器
  128. advanced = config_data.get("advanced", {})
  129. crawler_config = advanced.get("crawler", {})
  130. proxy_url = None
  131. if crawler_config.get("use_proxy"):
  132. proxy_url = crawler_config.get("default_proxy")
  133. fetcher = DataFetcher(proxy_url=proxy_url)
  134. request_interval = crawler_config.get("request_interval", 100)
  135. # 执行爬取
  136. results, id_to_name, failed_ids = fetcher.crawl_websites(
  137. ids_list=ids,
  138. request_interval=request_interval
  139. )
  140. # 获取当前时间(统一使用 trendradar 的时间工具)
  141. # 从配置中读取时区,默认为 Asia/Shanghai
  142. timezone = config_data.get("app", {}).get("timezone", "Asia/Shanghai")
  143. current_time = get_configured_time(timezone)
  144. crawl_date = format_date_folder(None, timezone)
  145. crawl_time_str = format_time_filename(timezone)
  146. # 转换为标准数据模型
  147. news_data = convert_crawl_results_to_news_data(
  148. results=results,
  149. id_to_name=id_to_name,
  150. failed_ids=failed_ids,
  151. crawl_time=crawl_time_str,
  152. crawl_date=crawl_date
  153. )
  154. # 初始化存储后端
  155. storage = LocalStorageBackend(
  156. data_dir=str(self.project_root / "output"),
  157. enable_txt=True,
  158. enable_html=True,
  159. timezone=timezone
  160. )
  161. # 尝试持久化数据
  162. save_success = False
  163. save_error_msg = ""
  164. saved_files = {}
  165. try:
  166. # 1. 保存到 SQLite (核心持久化)
  167. if storage.save_news_data(news_data):
  168. save_success = True
  169. # 2. 如果请求保存到本地,生成 TXT/HTML 快照
  170. if save_to_local:
  171. # 保存 TXT
  172. txt_path = storage.save_txt_snapshot(news_data)
  173. if txt_path:
  174. saved_files["txt"] = txt_path
  175. # 保存 HTML (使用简化版生成器)
  176. html_content = self._generate_simple_html(results, id_to_name, failed_ids, current_time)
  177. html_filename = f"{crawl_time_str}.html"
  178. html_path = storage.save_html_report(html_content, html_filename)
  179. if html_path:
  180. saved_files["html"] = html_path
  181. except Exception as e:
  182. # 捕获所有保存错误(特别是 Docker 只读卷导致的 PermissionError)
  183. print(f"[System] 数据保存失败: {e}")
  184. save_success = False
  185. save_error_msg = str(e)
  186. # 3. 清除缓存,确保下次查询获取最新数据
  187. # 即使保存失败,内存中的数据可能已经通过其他方式更新,或者是临时的
  188. get_cache().clear()
  189. print("[System] 缓存已清除")
  190. # 构建返回结果
  191. news_response_data = []
  192. for platform_id, titles_data in results.items():
  193. platform_name = id_to_name.get(platform_id, platform_id)
  194. for title, info in titles_data.items():
  195. news_item = {
  196. "platform_id": platform_id,
  197. "platform_name": platform_name,
  198. "title": title,
  199. "ranks": info.get("ranks", [])
  200. }
  201. if include_url:
  202. news_item["url"] = info.get("url", "")
  203. news_item["mobile_url"] = info.get("mobileUrl", "")
  204. news_response_data.append(news_item)
  205. result = {
  206. "success": True,
  207. "summary": {
  208. "description": "爬取任务执行结果",
  209. "task_id": f"crawl_{int(time.time())}",
  210. "status": "completed",
  211. "crawl_time": current_time.strftime("%Y-%m-%d %H:%M:%S"),
  212. "total_news": len(news_response_data),
  213. "platforms": list(results.keys()),
  214. "failed_platforms": failed_ids,
  215. "saved_to_local": save_success and save_to_local
  216. },
  217. "data": news_response_data
  218. }
  219. if save_success:
  220. if save_to_local:
  221. result["saved_files"] = saved_files
  222. result["note"] = "数据已保存到 SQLite 数据库及 output 文件夹"
  223. else:
  224. result["note"] = "数据已保存到 SQLite 数据库 (仅内存中返回结果,未生成TXT快照)"
  225. else:
  226. # 明确告知用户保存失败
  227. result["saved_to_local"] = False
  228. result["save_error"] = save_error_msg
  229. if "Read-only file system" in save_error_msg or "Permission denied" in save_error_msg:
  230. result["note"] = "爬取成功,但无法写入数据库(Docker只读模式)。数据仅在本次返回中有效。"
  231. else:
  232. result["note"] = f"爬取成功但保存失败: {save_error_msg}"
  233. # 清理资源
  234. storage.cleanup()
  235. return result
  236. except MCPError as e:
  237. return {
  238. "success": False,
  239. "error": e.to_dict()
  240. }
  241. except Exception as e:
  242. import traceback
  243. return {
  244. "success": False,
  245. "error": {
  246. "code": "INTERNAL_ERROR",
  247. "message": str(e),
  248. "traceback": traceback.format_exc()
  249. }
  250. }
  251. def _generate_simple_html(self, results: Dict, id_to_name: Dict, failed_ids: List, now) -> str:
  252. """生成简化的 HTML 报告"""
  253. html = """<!DOCTYPE html>
  254. <html>
  255. <head>
  256. <meta charset="UTF-8">
  257. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  258. <title>MCP 爬取结果</title>
  259. <style>
  260. body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
  261. .container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
  262. h1 { color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }
  263. .platform { margin-bottom: 30px; }
  264. .platform-name { background: #4CAF50; color: white; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
  265. .news-item { padding: 8px; border-bottom: 1px solid #eee; }
  266. .rank { color: #666; font-weight: bold; margin-right: 10px; }
  267. .title { color: #333; }
  268. .link { color: #1976D2; text-decoration: none; margin-left: 10px; font-size: 0.9em; }
  269. .link:hover { text-decoration: underline; }
  270. .failed { background: #ffebee; padding: 10px; border-radius: 5px; margin-top: 20px; }
  271. .failed h3 { color: #c62828; margin-top: 0; }
  272. .timestamp { color: #666; font-size: 0.9em; text-align: right; margin-top: 20px; }
  273. </style>
  274. </head>
  275. <body>
  276. <div class="container">
  277. <h1>MCP 爬取结果</h1>
  278. """
  279. # 添加时间戳
  280. html += f' <p class="timestamp">爬取时间: {now.strftime("%Y-%m-%d %H:%M:%S")}</p>\n\n'
  281. # 遍历每个平台
  282. for platform_id, titles_data in results.items():
  283. platform_name = id_to_name.get(platform_id, platform_id)
  284. html += f' <div class="platform">\n'
  285. html += f' <div class="platform-name">{platform_name}</div>\n'
  286. # 排序标题
  287. sorted_items = []
  288. for title, info in titles_data.items():
  289. ranks = info.get("ranks", [])
  290. url = info.get("url", "")
  291. mobile_url = info.get("mobileUrl", "")
  292. rank = ranks[0] if ranks else 999
  293. sorted_items.append((rank, title, url, mobile_url))
  294. sorted_items.sort(key=lambda x: x[0])
  295. # 显示新闻
  296. for rank, title, url, mobile_url in sorted_items:
  297. html += f' <div class="news-item">\n'
  298. html += f' <span class="rank">{rank}.</span>\n'
  299. html += f' <span class="title">{self._html_escape(title)}</span>\n'
  300. if url:
  301. html += f' <a class="link" href="{self._html_escape(url)}" target="_blank">链接</a>\n'
  302. if mobile_url and mobile_url != url:
  303. html += f' <a class="link" href="{self._html_escape(mobile_url)}" target="_blank">移动版</a>\n'
  304. html += ' </div>\n'
  305. html += ' </div>\n\n'
  306. # 失败的平台
  307. if failed_ids:
  308. html += ' <div class="failed">\n'
  309. html += ' <h3>请求失败的平台</h3>\n'
  310. html += ' <ul>\n'
  311. for platform_id in failed_ids:
  312. html += f' <li>{self._html_escape(platform_id)}</li>\n'
  313. html += ' </ul>\n'
  314. html += ' </div>\n'
  315. html += """ </div>
  316. </body>
  317. </html>"""
  318. return html
  319. def _html_escape(self, text: str) -> str:
  320. """HTML 转义"""
  321. if not isinstance(text, str):
  322. text = str(text)
  323. return (
  324. text.replace("&", "&amp;")
  325. .replace("<", "&lt;")
  326. .replace(">", "&gt;")
  327. .replace('"', "&quot;")
  328. .replace("'", "&#x27;")
  329. )
  330. def check_version(self, proxy_url: Optional[str] = None) -> Dict:
  331. """
  332. 检查版本更新
  333. 同时检查 TrendRadar 和 MCP Server 两个组件的版本更新。
  334. 远程版本 URL 从 config.yaml 获取:
  335. - version_check_url: TrendRadar 版本
  336. - mcp_version_check_url: MCP Server 版本
  337. Args:
  338. proxy_url: 可选的代理URL,用于访问远程版本
  339. Returns:
  340. 版本检查结果字典,包含:
  341. - success: 是否成功
  342. - trendradar: TrendRadar 版本检查结果
  343. - mcp: MCP Server 版本检查结果
  344. - any_update: 是否有任何组件需要更新
  345. Example:
  346. >>> tools = SystemManagementTools()
  347. >>> result = tools.check_version()
  348. >>> print(result['data']['any_update'])
  349. """
  350. import yaml
  351. import requests
  352. def parse_version(version_str: str):
  353. """将版本号字符串解析为元组"""
  354. try:
  355. parts = version_str.strip().split(".")
  356. if len(parts) != 3:
  357. raise ValueError("版本号格式不正确")
  358. return int(parts[0]), int(parts[1]), int(parts[2])
  359. except:
  360. return 0, 0, 0
  361. def check_single_version(
  362. name: str,
  363. local_version: str,
  364. remote_url: str,
  365. proxies: Optional[Dict],
  366. headers: Dict
  367. ) -> Dict:
  368. """检查单个组件的版本"""
  369. try:
  370. response = requests.get(
  371. remote_url, proxies=proxies, headers=headers, timeout=10
  372. )
  373. response.raise_for_status()
  374. remote_version = response.text.strip()
  375. local_tuple = parse_version(local_version)
  376. remote_tuple = parse_version(remote_version)
  377. need_update = local_tuple < remote_tuple
  378. if need_update:
  379. message = f"发现新版本 {remote_version},当前版本 {local_version},建议更新"
  380. elif local_tuple > remote_tuple:
  381. message = f"当前版本 {local_version} 高于远程版本 {remote_version}(可能是开发版本)"
  382. else:
  383. message = f"当前版本 {local_version} 已是最新版本"
  384. return {
  385. "success": True,
  386. "name": name,
  387. "current_version": local_version,
  388. "remote_version": remote_version,
  389. "need_update": need_update,
  390. "current_parsed": list(local_tuple),
  391. "remote_parsed": list(remote_tuple),
  392. "message": message
  393. }
  394. except requests.exceptions.Timeout:
  395. return {
  396. "success": False,
  397. "name": name,
  398. "current_version": local_version,
  399. "error": "获取远程版本超时"
  400. }
  401. except requests.exceptions.RequestException as e:
  402. return {
  403. "success": False,
  404. "name": name,
  405. "current_version": local_version,
  406. "error": f"网络请求失败: {str(e)}"
  407. }
  408. except Exception as e:
  409. return {
  410. "success": False,
  411. "name": name,
  412. "current_version": local_version,
  413. "error": str(e)
  414. }
  415. try:
  416. # 导入本地版本
  417. from trendradar import __version__ as trendradar_version
  418. from mcp_server import __version__ as mcp_version
  419. # 从配置文件获取远程版本 URL
  420. config_path = self.project_root / "config" / "config.yaml"
  421. if not config_path.exists():
  422. return {
  423. "success": False,
  424. "error": {
  425. "code": "CONFIG_NOT_FOUND",
  426. "message": f"配置文件不存在: {config_path}"
  427. }
  428. }
  429. with open(config_path, "r", encoding="utf-8") as f:
  430. config_data = yaml.safe_load(f)
  431. advanced_config = config_data.get("advanced", {})
  432. trendradar_url = advanced_config.get(
  433. "version_check_url",
  434. "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version"
  435. )
  436. mcp_url = advanced_config.get(
  437. "mcp_version_check_url",
  438. "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version_mcp"
  439. )
  440. # 配置代理
  441. proxies = None
  442. if proxy_url:
  443. proxies = {"http": proxy_url, "https": proxy_url}
  444. # 请求头
  445. headers = {
  446. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  447. "Accept": "text/plain, */*",
  448. "Cache-Control": "no-cache",
  449. }
  450. # 检查两个版本
  451. trendradar_result = check_single_version(
  452. "TrendRadar", trendradar_version, trendradar_url, proxies, headers
  453. )
  454. mcp_result = check_single_version(
  455. "MCP Server", mcp_version, mcp_url, proxies, headers
  456. )
  457. # 判断是否有任何更新
  458. any_update = (
  459. (trendradar_result.get("success") and trendradar_result.get("need_update", False)) or
  460. (mcp_result.get("success") and mcp_result.get("need_update", False))
  461. )
  462. return {
  463. "success": True,
  464. "summary": {
  465. "description": "版本检查结果(TrendRadar + MCP Server)",
  466. "any_update": any_update
  467. },
  468. "data": {
  469. "trendradar": trendradar_result,
  470. "mcp": mcp_result,
  471. "any_update": any_update
  472. }
  473. }
  474. except ImportError as e:
  475. return {
  476. "success": False,
  477. "error": {
  478. "code": "IMPORT_ERROR",
  479. "message": f"无法导入版本信息: {str(e)}"
  480. }
  481. }
  482. except Exception as e:
  483. return {
  484. "success": False,
  485. "error": {
  486. "code": "INTERNAL_ERROR",
  487. "message": str(e)
  488. }
  489. }