__main__.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. # coding=utf-8
  2. """
  3. TrendRadar 主程序
  4. 热点新闻聚合与分析工具
  5. 支持: python -m trendradar
  6. """
  7. import os
  8. import webbrowser
  9. from pathlib import Path
  10. from typing import Dict, List, Tuple, Optional
  11. import requests
  12. from trendradar.context import AppContext
  13. from trendradar import __version__
  14. from trendradar.core import load_config
  15. from trendradar.crawler import DataFetcher
  16. from trendradar.storage import convert_crawl_results_to_news_data
  17. from trendradar.utils.time import is_within_days
  18. def check_version_update(
  19. current_version: str, version_url: str, proxy_url: Optional[str] = None
  20. ) -> Tuple[bool, Optional[str]]:
  21. """检查版本更新"""
  22. try:
  23. proxies = None
  24. if proxy_url:
  25. proxies = {"http": proxy_url, "https": proxy_url}
  26. headers = {
  27. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  28. "Accept": "text/plain, */*",
  29. "Cache-Control": "no-cache",
  30. }
  31. response = requests.get(
  32. version_url, proxies=proxies, headers=headers, timeout=10
  33. )
  34. response.raise_for_status()
  35. remote_version = response.text.strip()
  36. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  37. # 比较版本
  38. def parse_version(version_str):
  39. try:
  40. parts = version_str.strip().split(".")
  41. if len(parts) != 3:
  42. raise ValueError("版本号格式不正确")
  43. return int(parts[0]), int(parts[1]), int(parts[2])
  44. except:
  45. return 0, 0, 0
  46. current_tuple = parse_version(current_version)
  47. remote_tuple = parse_version(remote_version)
  48. need_update = current_tuple < remote_tuple
  49. return need_update, remote_version if need_update else None
  50. except Exception as e:
  51. print(f"版本检查失败: {e}")
  52. return False, None
  53. # === 主分析器 ===
  54. class NewsAnalyzer:
  55. """新闻分析器"""
  56. # 模式策略定义
  57. MODE_STRATEGIES = {
  58. "incremental": {
  59. "mode_name": "增量模式",
  60. "description": "增量模式(只关注新增新闻,无新增时不推送)",
  61. "realtime_report_type": "实时增量",
  62. "summary_report_type": "当日汇总",
  63. "should_send_realtime": True,
  64. "should_generate_summary": True,
  65. "summary_mode": "daily",
  66. },
  67. "current": {
  68. "mode_name": "当前榜单模式",
  69. "description": "当前榜单模式(当前榜单匹配新闻 + 新增新闻区域 + 按时推送)",
  70. "realtime_report_type": "实时当前榜单",
  71. "summary_report_type": "当前榜单汇总",
  72. "should_send_realtime": True,
  73. "should_generate_summary": True,
  74. "summary_mode": "current",
  75. },
  76. "daily": {
  77. "mode_name": "当日汇总模式",
  78. "description": "当日汇总模式(所有匹配新闻 + 新增新闻区域 + 按时推送)",
  79. "realtime_report_type": "",
  80. "summary_report_type": "当日汇总",
  81. "should_send_realtime": False,
  82. "should_generate_summary": True,
  83. "summary_mode": "daily",
  84. },
  85. }
  86. def __init__(self):
  87. # 加载配置
  88. print("正在加载配置...")
  89. config = load_config()
  90. print(f"TrendRadar v{__version__} 配置加载完成")
  91. print(f"监控平台数量: {len(config['PLATFORMS'])}")
  92. print(f"时区: {config.get('TIMEZONE', 'Asia/Shanghai')}")
  93. # 创建应用上下文
  94. self.ctx = AppContext(config)
  95. self.request_interval = self.ctx.config["REQUEST_INTERVAL"]
  96. self.report_mode = self.ctx.config["REPORT_MODE"]
  97. self.rank_threshold = self.ctx.rank_threshold
  98. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  99. self.is_docker_container = self._detect_docker_environment()
  100. self.update_info = None
  101. self.proxy_url = None
  102. self._setup_proxy()
  103. self.data_fetcher = DataFetcher(self.proxy_url)
  104. # 初始化存储管理器(使用 AppContext)
  105. self._init_storage_manager()
  106. if self.is_github_actions:
  107. self._check_version_update()
  108. def _init_storage_manager(self) -> None:
  109. """初始化存储管理器(使用 AppContext)"""
  110. # 获取数据保留天数(支持环境变量覆盖)
  111. env_retention = os.environ.get("STORAGE_RETENTION_DAYS", "").strip()
  112. if env_retention:
  113. # 环境变量覆盖配置
  114. self.ctx.config["STORAGE"]["RETENTION_DAYS"] = int(env_retention)
  115. self.storage_manager = self.ctx.get_storage_manager()
  116. print(f"存储后端: {self.storage_manager.backend_name}")
  117. retention_days = self.ctx.config.get("STORAGE", {}).get("RETENTION_DAYS", 0)
  118. if retention_days > 0:
  119. print(f"数据保留天数: {retention_days} 天")
  120. def _detect_docker_environment(self) -> bool:
  121. """检测是否运行在 Docker 容器中"""
  122. try:
  123. if os.environ.get("DOCKER_CONTAINER") == "true":
  124. return True
  125. if os.path.exists("/.dockerenv"):
  126. return True
  127. return False
  128. except Exception:
  129. return False
  130. def _should_open_browser(self) -> bool:
  131. """判断是否应该打开浏览器"""
  132. return not self.is_github_actions and not self.is_docker_container
  133. def _setup_proxy(self) -> None:
  134. """设置代理配置"""
  135. if not self.is_github_actions and self.ctx.config["USE_PROXY"]:
  136. self.proxy_url = self.ctx.config["DEFAULT_PROXY"]
  137. print("本地环境,使用代理")
  138. elif not self.is_github_actions and not self.ctx.config["USE_PROXY"]:
  139. print("本地环境,未启用代理")
  140. else:
  141. print("GitHub Actions环境,不使用代理")
  142. def _check_version_update(self) -> None:
  143. """检查版本更新"""
  144. try:
  145. need_update, remote_version = check_version_update(
  146. __version__, self.ctx.config["VERSION_CHECK_URL"], self.proxy_url
  147. )
  148. if need_update and remote_version:
  149. self.update_info = {
  150. "current_version": __version__,
  151. "remote_version": remote_version,
  152. }
  153. print(f"发现新版本: {remote_version} (当前: {__version__})")
  154. else:
  155. print("版本检查完成,当前为最新版本")
  156. except Exception as e:
  157. print(f"版本检查出错: {e}")
  158. def _get_mode_strategy(self) -> Dict:
  159. """获取当前模式的策略配置"""
  160. return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"])
  161. def _has_notification_configured(self) -> bool:
  162. """检查是否配置了任何通知渠道"""
  163. cfg = self.ctx.config
  164. return any(
  165. [
  166. cfg["FEISHU_WEBHOOK_URL"],
  167. cfg["DINGTALK_WEBHOOK_URL"],
  168. cfg["WEWORK_WEBHOOK_URL"],
  169. (cfg["TELEGRAM_BOT_TOKEN"] and cfg["TELEGRAM_CHAT_ID"]),
  170. (
  171. cfg["EMAIL_FROM"]
  172. and cfg["EMAIL_PASSWORD"]
  173. and cfg["EMAIL_TO"]
  174. ),
  175. (cfg["NTFY_SERVER_URL"] and cfg["NTFY_TOPIC"]),
  176. cfg["BARK_URL"],
  177. cfg["SLACK_WEBHOOK_URL"],
  178. ]
  179. )
  180. def _has_valid_content(
  181. self, stats: List[Dict], new_titles: Optional[Dict] = None
  182. ) -> bool:
  183. """检查是否有有效的新闻内容"""
  184. if self.report_mode == "incremental":
  185. # 增量模式:必须有新增标题且匹配了关键词才推送
  186. has_new_titles = bool(
  187. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  188. )
  189. has_matched_news = any(stat["count"] > 0 for stat in stats)
  190. return has_new_titles and has_matched_news
  191. elif self.report_mode == "current":
  192. # current模式:只要stats有内容就说明有匹配的新闻
  193. return any(stat["count"] > 0 for stat in stats)
  194. else:
  195. # 当日汇总模式下,检查是否有匹配的频率词新闻或新增新闻
  196. has_matched_news = any(stat["count"] > 0 for stat in stats)
  197. has_new_news = bool(
  198. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  199. )
  200. return has_matched_news or has_new_news
  201. def _load_analysis_data(
  202. self,
  203. quiet: bool = False,
  204. ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]:
  205. """统一的数据加载和预处理,使用当前监控平台列表过滤历史数据"""
  206. try:
  207. # 获取当前配置的监控平台ID列表
  208. current_platform_ids = self.ctx.platform_ids
  209. if not quiet:
  210. print(f"当前监控平台: {current_platform_ids}")
  211. all_results, id_to_name, title_info = self.ctx.read_today_titles(
  212. current_platform_ids, quiet=quiet
  213. )
  214. if not all_results:
  215. print("没有找到当天的数据")
  216. return None
  217. total_titles = sum(len(titles) for titles in all_results.values())
  218. if not quiet:
  219. print(f"读取到 {total_titles} 个标题(已按当前监控平台过滤)")
  220. new_titles = self.ctx.detect_new_titles(current_platform_ids, quiet=quiet)
  221. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  222. return (
  223. all_results,
  224. id_to_name,
  225. title_info,
  226. new_titles,
  227. word_groups,
  228. filter_words,
  229. global_filters,
  230. )
  231. except Exception as e:
  232. print(f"数据加载失败: {e}")
  233. return None
  234. def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict:
  235. """从当前抓取结果构建标题信息"""
  236. title_info = {}
  237. for source_id, titles_data in results.items():
  238. title_info[source_id] = {}
  239. for title, title_data in titles_data.items():
  240. ranks = title_data.get("ranks", [])
  241. url = title_data.get("url", "")
  242. mobile_url = title_data.get("mobileUrl", "")
  243. title_info[source_id][title] = {
  244. "first_time": time_info,
  245. "last_time": time_info,
  246. "count": 1,
  247. "ranks": ranks,
  248. "url": url,
  249. "mobileUrl": mobile_url,
  250. }
  251. return title_info
  252. def _run_analysis_pipeline(
  253. self,
  254. data_source: Dict,
  255. mode: str,
  256. title_info: Dict,
  257. new_titles: Dict,
  258. word_groups: List[Dict],
  259. filter_words: List[str],
  260. id_to_name: Dict,
  261. failed_ids: Optional[List] = None,
  262. is_daily_summary: bool = False,
  263. global_filters: Optional[List[str]] = None,
  264. quiet: bool = False,
  265. ) -> Tuple[List[Dict], Optional[str]]:
  266. """统一的分析流水线:数据处理 → 统计计算 → HTML生成"""
  267. # 统计计算(使用 AppContext)
  268. stats, total_titles = self.ctx.count_frequency(
  269. data_source,
  270. word_groups,
  271. filter_words,
  272. id_to_name,
  273. title_info,
  274. new_titles,
  275. mode=mode,
  276. global_filters=global_filters,
  277. quiet=quiet,
  278. )
  279. # HTML生成(如果启用)
  280. html_file = None
  281. if self.ctx.config["STORAGE"]["FORMATS"]["HTML"]:
  282. html_file = self.ctx.generate_html(
  283. stats,
  284. total_titles,
  285. failed_ids=failed_ids,
  286. new_titles=new_titles,
  287. id_to_name=id_to_name,
  288. mode=mode,
  289. is_daily_summary=is_daily_summary,
  290. update_info=self.update_info if self.ctx.config["SHOW_VERSION_UPDATE"] else None,
  291. )
  292. return stats, html_file
  293. def _send_notification_if_needed(
  294. self,
  295. stats: List[Dict],
  296. report_type: str,
  297. mode: str,
  298. failed_ids: Optional[List] = None,
  299. new_titles: Optional[Dict] = None,
  300. id_to_name: Optional[Dict] = None,
  301. html_file_path: Optional[str] = None,
  302. rss_items: Optional[List[Dict]] = None,
  303. rss_new_items: Optional[List[Dict]] = None,
  304. ) -> bool:
  305. """统一的通知发送逻辑,包含所有判断条件,支持热榜+RSS合并推送"""
  306. has_notification = self._has_notification_configured()
  307. cfg = self.ctx.config
  308. # 检查是否有有效内容(热榜或RSS)
  309. has_news_content = self._has_valid_content(stats, new_titles)
  310. has_rss_content = bool(rss_items and len(rss_items) > 0)
  311. has_any_content = has_news_content or has_rss_content
  312. # 计算热榜匹配条数
  313. news_count = sum(len(stat.get("titles", [])) for stat in stats) if stats else 0
  314. rss_count = len(rss_items) if rss_items else 0
  315. if (
  316. cfg["ENABLE_NOTIFICATION"]
  317. and has_notification
  318. and has_any_content
  319. ):
  320. # 输出推送内容统计
  321. content_parts = []
  322. if news_count > 0:
  323. content_parts.append(f"热榜 {news_count} 条")
  324. if rss_count > 0:
  325. content_parts.append(f"RSS {rss_count} 条")
  326. total_count = news_count + rss_count
  327. print(f"[推送] 准备发送:{' + '.join(content_parts)},合计 {total_count} 条")
  328. # 推送窗口控制
  329. if cfg["PUSH_WINDOW"]["ENABLED"]:
  330. push_manager = self.ctx.create_push_manager()
  331. time_range_start = cfg["PUSH_WINDOW"]["TIME_RANGE"]["START"]
  332. time_range_end = cfg["PUSH_WINDOW"]["TIME_RANGE"]["END"]
  333. if not push_manager.is_in_time_range(time_range_start, time_range_end):
  334. now = self.ctx.get_time()
  335. print(
  336. f"推送窗口控制:当前时间 {now.strftime('%H:%M')} 不在推送时间窗口 {time_range_start}-{time_range_end} 内,跳过推送"
  337. )
  338. return False
  339. if cfg["PUSH_WINDOW"]["ONCE_PER_DAY"]:
  340. if push_manager.has_pushed_today():
  341. print(f"推送窗口控制:今天已推送过,跳过本次推送")
  342. return False
  343. else:
  344. print(f"推送窗口控制:今天首次推送")
  345. # 准备报告数据
  346. report_data = self.ctx.prepare_report(stats, failed_ids, new_titles, id_to_name, mode)
  347. # 是否发送版本更新信息
  348. update_info_to_send = self.update_info if cfg["SHOW_VERSION_UPDATE"] else None
  349. # 使用 NotificationDispatcher 发送到所有渠道(合并热榜+RSS)
  350. dispatcher = self.ctx.create_notification_dispatcher()
  351. results = dispatcher.dispatch_all(
  352. report_data=report_data,
  353. report_type=report_type,
  354. update_info=update_info_to_send,
  355. proxy_url=self.proxy_url,
  356. mode=mode,
  357. html_file_path=html_file_path,
  358. rss_items=rss_items,
  359. rss_new_items=rss_new_items,
  360. )
  361. if not results:
  362. print("未配置任何通知渠道,跳过通知发送")
  363. return False
  364. # 如果成功发送了任何通知,且启用了每天只推一次,则记录推送
  365. if (
  366. cfg["PUSH_WINDOW"]["ENABLED"]
  367. and cfg["PUSH_WINDOW"]["ONCE_PER_DAY"]
  368. and any(results.values())
  369. ):
  370. push_manager = self.ctx.create_push_manager()
  371. push_manager.record_push(report_type)
  372. return True
  373. elif cfg["ENABLE_NOTIFICATION"] and not has_notification:
  374. print("⚠️ 警告:通知功能已启用但未配置任何通知渠道,将跳过通知发送")
  375. elif not cfg["ENABLE_NOTIFICATION"]:
  376. print(f"跳过{report_type}通知:通知功能已禁用")
  377. elif (
  378. cfg["ENABLE_NOTIFICATION"]
  379. and has_notification
  380. and not has_any_content
  381. ):
  382. mode_strategy = self._get_mode_strategy()
  383. if "实时" in report_type:
  384. if self.report_mode == "incremental":
  385. has_new = bool(
  386. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  387. )
  388. if not has_new and not has_rss_content:
  389. print("跳过实时推送通知:增量模式下未检测到新增的新闻和RSS")
  390. elif not has_new:
  391. print("跳过实时推送通知:增量模式下新增新闻未匹配到关键词")
  392. else:
  393. print(
  394. f"跳过实时推送通知:{mode_strategy['mode_name']}下未检测到匹配的新闻"
  395. )
  396. else:
  397. print(
  398. f"跳过{mode_strategy['summary_report_type']}通知:未匹配到有效的新闻内容"
  399. )
  400. return False
  401. def _generate_summary_report(
  402. self,
  403. mode_strategy: Dict,
  404. rss_items: Optional[List[Dict]] = None,
  405. rss_new_items: Optional[List[Dict]] = None,
  406. ) -> Optional[str]:
  407. """生成汇总报告(带通知,支持RSS合并)"""
  408. summary_type = (
  409. "当前榜单汇总" if mode_strategy["summary_mode"] == "current" else "当日汇总"
  410. )
  411. print(f"生成{summary_type}报告...")
  412. # 加载分析数据
  413. analysis_data = self._load_analysis_data()
  414. if not analysis_data:
  415. return None
  416. all_results, id_to_name, title_info, new_titles, word_groups, filter_words, global_filters = (
  417. analysis_data
  418. )
  419. # 运行分析流水线
  420. stats, html_file = self._run_analysis_pipeline(
  421. all_results,
  422. mode_strategy["summary_mode"],
  423. title_info,
  424. new_titles,
  425. word_groups,
  426. filter_words,
  427. id_to_name,
  428. is_daily_summary=True,
  429. global_filters=global_filters,
  430. )
  431. if html_file:
  432. print(f"{summary_type}报告已生成: {html_file}")
  433. # 发送通知(合并RSS)
  434. self._send_notification_if_needed(
  435. stats,
  436. mode_strategy["summary_report_type"],
  437. mode_strategy["summary_mode"],
  438. failed_ids=[],
  439. new_titles=new_titles,
  440. id_to_name=id_to_name,
  441. html_file_path=html_file,
  442. rss_items=rss_items,
  443. rss_new_items=rss_new_items,
  444. )
  445. return html_file
  446. def _generate_summary_html(self, mode: str = "daily") -> Optional[str]:
  447. """生成汇总HTML"""
  448. summary_type = "当前榜单汇总" if mode == "current" else "当日汇总"
  449. print(f"生成{summary_type}HTML...")
  450. # 加载分析数据(静默模式,避免重复输出日志)
  451. analysis_data = self._load_analysis_data(quiet=True)
  452. if not analysis_data:
  453. return None
  454. all_results, id_to_name, title_info, new_titles, word_groups, filter_words, global_filters = (
  455. analysis_data
  456. )
  457. # 运行分析流水线(静默模式,避免重复输出日志)
  458. _, html_file = self._run_analysis_pipeline(
  459. all_results,
  460. mode,
  461. title_info,
  462. new_titles,
  463. word_groups,
  464. filter_words,
  465. id_to_name,
  466. is_daily_summary=True,
  467. global_filters=global_filters,
  468. quiet=True,
  469. )
  470. if html_file:
  471. print(f"{summary_type}HTML已生成: {html_file}")
  472. return html_file
  473. def _initialize_and_check_config(self) -> None:
  474. """通用初始化和配置检查"""
  475. now = self.ctx.get_time()
  476. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  477. if not self.ctx.config["ENABLE_CRAWLER"]:
  478. print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出")
  479. return
  480. has_notification = self._has_notification_configured()
  481. if not self.ctx.config["ENABLE_NOTIFICATION"]:
  482. print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取")
  483. elif not has_notification:
  484. print("未配置任何通知渠道,将只进行数据抓取,不发送通知")
  485. else:
  486. print("通知功能已启用,将发送通知")
  487. mode_strategy = self._get_mode_strategy()
  488. print(f"报告模式: {self.report_mode}")
  489. print(f"运行模式: {mode_strategy['description']}")
  490. def _crawl_data(self) -> Tuple[Dict, Dict, List]:
  491. """执行数据爬取"""
  492. ids = []
  493. for platform in self.ctx.platforms:
  494. if "name" in platform:
  495. ids.append((platform["id"], platform["name"]))
  496. else:
  497. ids.append(platform["id"])
  498. print(
  499. f"配置的监控平台: {[p.get('name', p['id']) for p in self.ctx.platforms]}"
  500. )
  501. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  502. Path("output").mkdir(parents=True, exist_ok=True)
  503. results, id_to_name, failed_ids = self.data_fetcher.crawl_websites(
  504. ids, self.request_interval
  505. )
  506. # 转换为 NewsData 格式并保存到存储后端
  507. crawl_time = self.ctx.format_time()
  508. crawl_date = self.ctx.format_date()
  509. news_data = convert_crawl_results_to_news_data(
  510. results, id_to_name, failed_ids, crawl_time, crawl_date
  511. )
  512. # 保存到存储后端(SQLite)
  513. if self.storage_manager.save_news_data(news_data):
  514. print(f"数据已保存到存储后端: {self.storage_manager.backend_name}")
  515. # 保存 TXT 快照(如果启用)
  516. txt_file = self.storage_manager.save_txt_snapshot(news_data)
  517. if txt_file:
  518. print(f"TXT 快照已保存: {txt_file}")
  519. # 兼容:同时保存到原有 TXT 格式(确保向后兼容)
  520. if self.ctx.config["STORAGE"]["FORMATS"]["TXT"]:
  521. title_file = self.ctx.save_titles(results, id_to_name, failed_ids)
  522. print(f"标题已保存到: {title_file}")
  523. return results, id_to_name, failed_ids
  524. def _crawl_rss_data(self) -> Tuple[Optional[List[Dict]], Optional[List[Dict]]]:
  525. """
  526. 执行 RSS 数据抓取
  527. Returns:
  528. (rss_items, rss_new_items) 元组:
  529. - rss_items: 统计条目列表(按模式处理,用于统计区块)
  530. - rss_new_items: 新增条目列表(用于新增区块)
  531. 如果未启用或失败返回 (None, None)
  532. """
  533. if not self.ctx.rss_enabled:
  534. return None, None
  535. rss_feeds = self.ctx.rss_feeds
  536. if not rss_feeds:
  537. print("[RSS] 未配置任何 RSS 源")
  538. return None, None
  539. try:
  540. from trendradar.crawler.rss import RSSFetcher, RSSFeedConfig
  541. # 构建 RSS 源配置
  542. feeds = []
  543. for feed_config in rss_feeds:
  544. # 读取并验证单个 feed 的 max_age_days(可选)
  545. max_age_days_raw = feed_config.get("max_age_days")
  546. max_age_days = None
  547. if max_age_days_raw is not None:
  548. try:
  549. max_age_days = int(max_age_days_raw)
  550. if max_age_days < 0:
  551. feed_id = feed_config.get("id", "unknown")
  552. print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 为负数,将使用全局默认值")
  553. max_age_days = None
  554. except (ValueError, TypeError):
  555. feed_id = feed_config.get("id", "unknown")
  556. print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 格式错误:{max_age_days_raw}")
  557. max_age_days = None
  558. feed = RSSFeedConfig(
  559. id=feed_config.get("id", ""),
  560. name=feed_config.get("name", ""),
  561. url=feed_config.get("url", ""),
  562. max_items=feed_config.get("max_items", 50),
  563. enabled=feed_config.get("enabled", True),
  564. max_age_days=max_age_days, # None=使用全局,0=禁用,>0=覆盖
  565. )
  566. if feed.id and feed.url and feed.enabled:
  567. feeds.append(feed)
  568. if not feeds:
  569. print("[RSS] 没有启用的 RSS 源")
  570. return None, None
  571. # 创建抓取器
  572. rss_config = self.ctx.rss_config
  573. # RSS 代理:优先使用 RSS 专属代理,否则使用爬虫默认代理
  574. rss_proxy_url = rss_config.get("PROXY_URL", "") or self.proxy_url or ""
  575. # 获取配置的时区
  576. timezone = self.ctx.config.get("TIMEZONE", "Asia/Shanghai")
  577. # 获取新鲜度过滤配置
  578. freshness_config = rss_config.get("FRESHNESS_FILTER", {})
  579. freshness_enabled = freshness_config.get("ENABLED", True)
  580. default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3)
  581. fetcher = RSSFetcher(
  582. feeds=feeds,
  583. request_interval=rss_config.get("REQUEST_INTERVAL", 2000),
  584. timeout=rss_config.get("TIMEOUT", 15),
  585. use_proxy=rss_config.get("USE_PROXY", False),
  586. proxy_url=rss_proxy_url,
  587. timezone=timezone,
  588. freshness_enabled=freshness_enabled,
  589. default_max_age_days=default_max_age_days,
  590. )
  591. # 抓取数据
  592. rss_data = fetcher.fetch_all()
  593. # 保存到存储后端
  594. if self.storage_manager.save_rss_data(rss_data):
  595. print(f"[RSS] 数据已保存到存储后端")
  596. # 处理 RSS 数据(按模式过滤)并返回用于合并推送
  597. return self._process_rss_data_by_mode(rss_data)
  598. else:
  599. print(f"[RSS] 数据保存失败")
  600. return None, None
  601. except ImportError as e:
  602. print(f"[RSS] 缺少依赖: {e}")
  603. print("[RSS] 请安装 feedparser: pip install feedparser")
  604. return None, None
  605. except Exception as e:
  606. print(f"[RSS] 抓取失败: {e}")
  607. return None, None
  608. def _process_rss_data_by_mode(self, rss_data) -> Tuple[Optional[List[Dict]], Optional[List[Dict]]]:
  609. """
  610. 按报告模式处理 RSS 数据,返回与热榜相同格式的统计结构
  611. 三种模式:
  612. - daily: 当日汇总,统计=当天所有条目,新增=本次新增条目
  613. - current: 当前榜单,统计=当前榜单条目,新增=本次新增条目
  614. - incremental: 增量模式,统计=新增条目,新增=无
  615. Args:
  616. rss_data: 当前抓取的 RSSData 对象
  617. Returns:
  618. (rss_stats, rss_new_stats) 元组:
  619. - rss_stats: RSS 关键词统计列表(与热榜 stats 格式一致)
  620. - rss_new_stats: RSS 新增关键词统计列表(与热榜 stats 格式一致)
  621. """
  622. from trendradar.core.analyzer import count_rss_frequency
  623. rss_config = self.ctx.rss_config
  624. # 检查是否启用 RSS 通知
  625. if not rss_config.get("NOTIFICATION", {}).get("ENABLED", False):
  626. return None, None
  627. # 加载关键词配置
  628. try:
  629. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  630. except FileNotFoundError:
  631. word_groups, filter_words, global_filters = [], [], []
  632. timezone = self.ctx.timezone
  633. max_news_per_keyword = self.ctx.config.get("MAX_NEWS_PER_KEYWORD", 0)
  634. sort_by_position_first = self.ctx.config.get("SORT_BY_POSITION_FIRST", False)
  635. rss_stats = None
  636. rss_new_stats = None
  637. # 1. 首先获取新增条目(所有模式都需要)
  638. new_items_dict = self.storage_manager.detect_new_rss_items(rss_data)
  639. new_items_list = None
  640. if new_items_dict:
  641. new_items_list = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name)
  642. if new_items_list:
  643. print(f"[RSS] 检测到 {len(new_items_list)} 条新增")
  644. # 2. 根据模式获取统计条目
  645. if self.report_mode == "incremental":
  646. # 增量模式:统计条目就是新增条目
  647. if not new_items_list:
  648. print("[RSS] 增量模式:没有新增 RSS 条目")
  649. return None, None
  650. rss_stats, total = count_rss_frequency(
  651. rss_items=new_items_list,
  652. word_groups=word_groups,
  653. filter_words=filter_words,
  654. global_filters=global_filters,
  655. new_items=new_items_list, # 增量模式所有都是新增
  656. max_news_per_keyword=max_news_per_keyword,
  657. sort_by_position_first=sort_by_position_first,
  658. timezone=timezone,
  659. rank_threshold=self.rank_threshold,
  660. quiet=False,
  661. )
  662. if not rss_stats:
  663. print("[RSS] 增量模式:关键词匹配后没有内容")
  664. return None, None
  665. elif self.report_mode == "current":
  666. # 当前榜单模式:统计=当前榜单所有条目
  667. latest_data = self.storage_manager.get_latest_rss_data(rss_data.date)
  668. if not latest_data:
  669. print("[RSS] 当前榜单模式:没有 RSS 数据")
  670. return None, None
  671. all_items_list = self._convert_rss_items_to_list(latest_data.items, latest_data.id_to_name)
  672. rss_stats, total = count_rss_frequency(
  673. rss_items=all_items_list,
  674. word_groups=word_groups,
  675. filter_words=filter_words,
  676. global_filters=global_filters,
  677. new_items=new_items_list, # 标记新增
  678. max_news_per_keyword=max_news_per_keyword,
  679. sort_by_position_first=sort_by_position_first,
  680. timezone=timezone,
  681. rank_threshold=self.rank_threshold,
  682. quiet=False,
  683. )
  684. if not rss_stats:
  685. print("[RSS] 当前榜单模式:关键词匹配后没有内容")
  686. return None, None
  687. # 生成新增统计
  688. if new_items_list:
  689. rss_new_stats, _ = count_rss_frequency(
  690. rss_items=new_items_list,
  691. word_groups=word_groups,
  692. filter_words=filter_words,
  693. global_filters=global_filters,
  694. new_items=new_items_list,
  695. max_news_per_keyword=max_news_per_keyword,
  696. sort_by_position_first=sort_by_position_first,
  697. timezone=timezone,
  698. rank_threshold=self.rank_threshold,
  699. quiet=True,
  700. )
  701. else:
  702. # daily 模式:统计=当天所有条目
  703. all_data = self.storage_manager.get_rss_data(rss_data.date)
  704. if not all_data:
  705. print("[RSS] 当日汇总模式:没有 RSS 数据")
  706. return None, None
  707. all_items_list = self._convert_rss_items_to_list(all_data.items, all_data.id_to_name)
  708. rss_stats, total = count_rss_frequency(
  709. rss_items=all_items_list,
  710. word_groups=word_groups,
  711. filter_words=filter_words,
  712. global_filters=global_filters,
  713. new_items=new_items_list, # 标记新增
  714. max_news_per_keyword=max_news_per_keyword,
  715. sort_by_position_first=sort_by_position_first,
  716. timezone=timezone,
  717. rank_threshold=self.rank_threshold,
  718. quiet=False,
  719. )
  720. if not rss_stats:
  721. print("[RSS] 当日汇总模式:关键词匹配后没有内容")
  722. return None, None
  723. # 生成新增统计
  724. if new_items_list:
  725. rss_new_stats, _ = count_rss_frequency(
  726. rss_items=new_items_list,
  727. word_groups=word_groups,
  728. filter_words=filter_words,
  729. global_filters=global_filters,
  730. new_items=new_items_list,
  731. max_news_per_keyword=max_news_per_keyword,
  732. sort_by_position_first=sort_by_position_first,
  733. timezone=timezone,
  734. rank_threshold=self.rank_threshold,
  735. quiet=True,
  736. )
  737. return rss_stats, rss_new_stats
  738. def _convert_rss_items_to_list(self, items_dict: Dict, id_to_name: Dict) -> List[Dict]:
  739. """将 RSS 条目字典转换为列表格式,并应用新鲜度过滤(用于推送)"""
  740. rss_items = []
  741. filtered_count = 0
  742. # 获取新鲜度过滤配置
  743. rss_config = self.ctx.rss_config
  744. freshness_config = rss_config.get("FRESHNESS_FILTER", {})
  745. freshness_enabled = freshness_config.get("ENABLED", True)
  746. default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3)
  747. timezone = self.ctx.config.get("TIMEZONE", "Asia/Shanghai")
  748. # 构建 feed_id -> max_age_days 的映射
  749. feed_max_age_map = {}
  750. for feed_cfg in self.ctx.rss_feeds:
  751. feed_id = feed_cfg.get("id", "")
  752. max_age = feed_cfg.get("max_age_days")
  753. if max_age is not None:
  754. try:
  755. feed_max_age_map[feed_id] = int(max_age)
  756. except (ValueError, TypeError):
  757. pass
  758. for feed_id, items in items_dict.items():
  759. # 确定此 feed 的 max_age_days
  760. max_days = feed_max_age_map.get(feed_id)
  761. if max_days is None:
  762. max_days = default_max_age_days
  763. for item in items:
  764. # 应用新鲜度过滤(仅在启用时)
  765. if freshness_enabled and max_days > 0:
  766. if item.published_at and not is_within_days(item.published_at, max_days, timezone):
  767. filtered_count += 1
  768. continue # 跳过超过指定天数的文章
  769. rss_items.append({
  770. "title": item.title,
  771. "feed_id": feed_id,
  772. "feed_name": id_to_name.get(feed_id, feed_id),
  773. "url": item.url,
  774. "published_at": item.published_at,
  775. "summary": item.summary,
  776. "author": item.author,
  777. })
  778. # 输出过滤统计
  779. if filtered_count > 0:
  780. print(f"[RSS] 新鲜度过滤:跳过 {filtered_count} 篇超过指定天数的旧文章(仍保留在数据库中)")
  781. return rss_items
  782. def _filter_rss_by_keywords(self, rss_items: List[Dict]) -> List[Dict]:
  783. """使用 frequency_words.txt 过滤 RSS 条目"""
  784. try:
  785. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  786. if word_groups or filter_words or global_filters:
  787. from trendradar.core.frequency import matches_word_groups
  788. filtered_items = []
  789. for item in rss_items:
  790. title = item.get("title", "")
  791. if matches_word_groups(title, word_groups, filter_words, global_filters):
  792. filtered_items.append(item)
  793. original_count = len(rss_items)
  794. rss_items = filtered_items
  795. print(f"[RSS] 关键词过滤后剩余 {len(rss_items)}/{original_count} 条")
  796. if not rss_items:
  797. print("[RSS] 关键词过滤后没有匹配内容")
  798. return []
  799. except FileNotFoundError:
  800. # frequency_words.txt 不存在时跳过过滤
  801. pass
  802. return rss_items
  803. def _process_rss_report_and_notification(self, rss_data) -> None:
  804. """处理 RSS 报告生成和通知发送(独立推送,已废弃)"""
  805. # 此方法保留用于向后兼容,但不再使用
  806. # RSS 现在与热榜合并推送
  807. pass
  808. def _generate_rss_html_report(self, rss_items: list, feeds_info: dict) -> str:
  809. """生成 RSS HTML 报告"""
  810. try:
  811. from trendradar.report.rss_html import render_rss_html_content
  812. from pathlib import Path
  813. html_content = render_rss_html_content(
  814. rss_items=rss_items,
  815. total_count=len(rss_items),
  816. feeds_info=feeds_info,
  817. get_time_func=self.ctx.get_time,
  818. )
  819. # 保存 HTML 文件
  820. date_folder = self.ctx.format_date()
  821. time_filename = self.ctx.format_time()
  822. output_dir = Path("output") / date_folder / "html"
  823. output_dir.mkdir(parents=True, exist_ok=True)
  824. file_path = output_dir / f"rss_{time_filename}.html"
  825. with open(file_path, "w", encoding="utf-8") as f:
  826. f.write(html_content)
  827. print(f"[RSS] HTML 报告已生成: {file_path}")
  828. return str(file_path)
  829. except Exception as e:
  830. print(f"[RSS] 生成 HTML 报告失败: {e}")
  831. return None
  832. def _execute_mode_strategy(
  833. self, mode_strategy: Dict, results: Dict, id_to_name: Dict, failed_ids: List,
  834. rss_items: Optional[List[Dict]] = None,
  835. rss_new_items: Optional[List[Dict]] = None,
  836. ) -> Optional[str]:
  837. """执行模式特定逻辑,支持热榜+RSS合并推送"""
  838. # 获取当前监控平台ID列表
  839. current_platform_ids = self.ctx.platform_ids
  840. new_titles = self.ctx.detect_new_titles(current_platform_ids)
  841. time_info = self.ctx.format_time()
  842. if self.ctx.config["STORAGE"]["FORMATS"]["TXT"]:
  843. self.ctx.save_titles(results, id_to_name, failed_ids)
  844. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  845. # current模式下,实时推送需要使用完整的历史数据来保证统计信息的完整性
  846. if self.report_mode == "current":
  847. # 加载完整的历史数据(已按当前平台过滤)
  848. analysis_data = self._load_analysis_data()
  849. if analysis_data:
  850. (
  851. all_results,
  852. historical_id_to_name,
  853. historical_title_info,
  854. historical_new_titles,
  855. _,
  856. _,
  857. _,
  858. ) = analysis_data
  859. print(
  860. f"current模式:使用过滤后的历史数据,包含平台:{list(all_results.keys())}"
  861. )
  862. stats, html_file = self._run_analysis_pipeline(
  863. all_results,
  864. self.report_mode,
  865. historical_title_info,
  866. historical_new_titles,
  867. word_groups,
  868. filter_words,
  869. historical_id_to_name,
  870. failed_ids=failed_ids,
  871. global_filters=global_filters,
  872. )
  873. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  874. if html_file:
  875. print(f"HTML报告已生成: {html_file}")
  876. # 发送实时通知(使用完整历史数据的统计结果,合并RSS)
  877. summary_html = None
  878. if mode_strategy["should_send_realtime"]:
  879. self._send_notification_if_needed(
  880. stats,
  881. mode_strategy["realtime_report_type"],
  882. self.report_mode,
  883. failed_ids=failed_ids,
  884. new_titles=historical_new_titles,
  885. id_to_name=combined_id_to_name,
  886. html_file_path=html_file,
  887. rss_items=rss_items,
  888. rss_new_items=rss_new_items,
  889. )
  890. else:
  891. print("❌ 严重错误:无法读取刚保存的数据文件")
  892. raise RuntimeError("数据一致性检查失败:保存后立即读取失败")
  893. else:
  894. title_info = self._prepare_current_title_info(results, time_info)
  895. stats, html_file = self._run_analysis_pipeline(
  896. results,
  897. self.report_mode,
  898. title_info,
  899. new_titles,
  900. word_groups,
  901. filter_words,
  902. id_to_name,
  903. failed_ids=failed_ids,
  904. global_filters=global_filters,
  905. )
  906. if html_file:
  907. print(f"HTML报告已生成: {html_file}")
  908. # 发送实时通知(如果需要,合并RSS)
  909. summary_html = None
  910. if mode_strategy["should_send_realtime"]:
  911. self._send_notification_if_needed(
  912. stats,
  913. mode_strategy["realtime_report_type"],
  914. self.report_mode,
  915. failed_ids=failed_ids,
  916. new_titles=new_titles,
  917. id_to_name=id_to_name,
  918. html_file_path=html_file,
  919. rss_items=rss_items,
  920. rss_new_items=rss_new_items,
  921. )
  922. # 生成汇总报告(如果需要)
  923. summary_html = None
  924. if mode_strategy["should_generate_summary"]:
  925. if mode_strategy["should_send_realtime"]:
  926. # 如果已经发送了实时通知,汇总只生成HTML不发送通知
  927. summary_html = self._generate_summary_html(
  928. mode_strategy["summary_mode"]
  929. )
  930. else:
  931. # daily模式:直接生成汇总报告并发送通知(合并RSS)
  932. summary_html = self._generate_summary_report(
  933. mode_strategy, rss_items=rss_items, rss_new_items=rss_new_items
  934. )
  935. # 打开浏览器(仅在非容器环境)
  936. if self._should_open_browser() and html_file:
  937. if summary_html:
  938. summary_url = "file://" + str(Path(summary_html).resolve())
  939. print(f"正在打开汇总报告: {summary_url}")
  940. webbrowser.open(summary_url)
  941. else:
  942. file_url = "file://" + str(Path(html_file).resolve())
  943. print(f"正在打开HTML报告: {file_url}")
  944. webbrowser.open(file_url)
  945. elif self.is_docker_container and html_file:
  946. if summary_html:
  947. print(f"汇总报告已生成(Docker环境): {summary_html}")
  948. else:
  949. print(f"HTML报告已生成(Docker环境): {html_file}")
  950. return summary_html
  951. def run(self) -> None:
  952. """执行分析流程"""
  953. try:
  954. self._initialize_and_check_config()
  955. mode_strategy = self._get_mode_strategy()
  956. # 抓取热榜数据
  957. results, id_to_name, failed_ids = self._crawl_data()
  958. # 抓取 RSS 数据(如果启用),返回统计条目和新增条目用于合并推送
  959. rss_items, rss_new_items = self._crawl_rss_data()
  960. # 执行模式策略,传递 RSS 数据用于合并推送
  961. self._execute_mode_strategy(
  962. mode_strategy, results, id_to_name, failed_ids,
  963. rss_items=rss_items, rss_new_items=rss_new_items
  964. )
  965. except Exception as e:
  966. print(f"分析流程执行出错: {e}")
  967. raise
  968. finally:
  969. # 清理资源(包括过期数据清理和数据库连接关闭)
  970. self.ctx.cleanup()
  971. def main():
  972. """主程序入口"""
  973. try:
  974. analyzer = NewsAnalyzer()
  975. analyzer.run()
  976. except FileNotFoundError as e:
  977. print(f"❌ 配置文件错误: {e}")
  978. print("\n请确保以下文件存在:")
  979. print(" • config/config.yaml")
  980. print(" • config/frequency_words.txt")
  981. print("\n参考项目文档进行正确配置")
  982. except Exception as e:
  983. print(f"❌ 程序运行错误: {e}")
  984. raise
  985. if __name__ == "__main__":
  986. main()