loader.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # coding=utf-8
  2. """
  3. 配置加载模块
  4. 负责从 YAML 配置文件和环境变量加载配置。
  5. """
  6. import os
  7. from pathlib import Path
  8. from typing import Dict, Any, Optional
  9. import yaml
  10. from .config import parse_multi_account_config, validate_paired_configs
  11. def _get_env_bool(key: str, default: bool = False) -> Optional[bool]:
  12. """从环境变量获取布尔值,如果未设置返回 None"""
  13. value = os.environ.get(key, "").strip().lower()
  14. if not value:
  15. return None
  16. return value in ("true", "1")
  17. def _get_env_int(key: str, default: int = 0) -> int:
  18. """从环境变量获取整数值"""
  19. value = os.environ.get(key, "").strip()
  20. if not value:
  21. return default
  22. try:
  23. return int(value)
  24. except ValueError:
  25. return default
  26. def _get_env_str(key: str, default: str = "") -> str:
  27. """从环境变量获取字符串值"""
  28. return os.environ.get(key, "").strip() or default
  29. def _load_app_config(config_data: Dict) -> Dict:
  30. """加载应用配置"""
  31. app_config = config_data.get("app", {})
  32. advanced = config_data.get("advanced", {})
  33. return {
  34. "VERSION_CHECK_URL": advanced.get("version_check_url", ""),
  35. "SHOW_VERSION_UPDATE": app_config.get("show_version_update", True),
  36. "TIMEZONE": _get_env_str("TIMEZONE") or app_config.get("timezone", "Asia/Shanghai"),
  37. }
  38. def _load_crawler_config(config_data: Dict) -> Dict:
  39. """加载爬虫配置"""
  40. advanced = config_data.get("advanced", {})
  41. crawler_config = advanced.get("crawler", {})
  42. enable_crawler_env = _get_env_bool("ENABLE_CRAWLER")
  43. return {
  44. "REQUEST_INTERVAL": crawler_config.get("request_interval", 100),
  45. "USE_PROXY": crawler_config.get("use_proxy", False),
  46. "DEFAULT_PROXY": crawler_config.get("default_proxy", ""),
  47. "ENABLE_CRAWLER": enable_crawler_env if enable_crawler_env is not None else crawler_config.get("enabled", True),
  48. }
  49. def _load_report_config(config_data: Dict) -> Dict:
  50. """加载报告配置"""
  51. report_config = config_data.get("report", {})
  52. # 环境变量覆盖
  53. sort_by_position_env = _get_env_bool("SORT_BY_POSITION_FIRST")
  54. reverse_content_env = _get_env_bool("REVERSE_CONTENT_ORDER")
  55. max_news_env = _get_env_int("MAX_NEWS_PER_KEYWORD")
  56. display_mode_env = _get_env_str("DISPLAY_MODE")
  57. return {
  58. "REPORT_MODE": _get_env_str("REPORT_MODE") or report_config.get("mode", "daily"),
  59. "DISPLAY_MODE": display_mode_env or report_config.get("display_mode", "keyword"),
  60. "RANK_THRESHOLD": report_config.get("rank_threshold", 10),
  61. "SORT_BY_POSITION_FIRST": sort_by_position_env if sort_by_position_env is not None else report_config.get("sort_by_position_first", False),
  62. "MAX_NEWS_PER_KEYWORD": max_news_env or report_config.get("max_news_per_keyword", 0),
  63. "REVERSE_CONTENT_ORDER": reverse_content_env if reverse_content_env is not None else report_config.get("reverse_content_order", False),
  64. }
  65. def _load_notification_config(config_data: Dict) -> Dict:
  66. """加载通知配置"""
  67. notification = config_data.get("notification", {})
  68. advanced = config_data.get("advanced", {})
  69. batch_size = advanced.get("batch_size", {})
  70. enable_notification_env = _get_env_bool("ENABLE_NOTIFICATION")
  71. return {
  72. "ENABLE_NOTIFICATION": enable_notification_env if enable_notification_env is not None else notification.get("enabled", True),
  73. "MESSAGE_BATCH_SIZE": batch_size.get("default", 4000),
  74. "DINGTALK_BATCH_SIZE": batch_size.get("dingtalk", 20000),
  75. "FEISHU_BATCH_SIZE": batch_size.get("feishu", 29000),
  76. "BARK_BATCH_SIZE": batch_size.get("bark", 3600),
  77. "SLACK_BATCH_SIZE": batch_size.get("slack", 4000),
  78. "BATCH_SEND_INTERVAL": advanced.get("batch_send_interval", 1.0),
  79. "FEISHU_MESSAGE_SEPARATOR": advanced.get("feishu_message_separator", "---"),
  80. "MAX_ACCOUNTS_PER_CHANNEL": _get_env_int("MAX_ACCOUNTS_PER_CHANNEL") or advanced.get("max_accounts_per_channel", 3),
  81. }
  82. def _load_push_window_config(config_data: Dict) -> Dict:
  83. """加载推送窗口配置"""
  84. notification = config_data.get("notification", {})
  85. push_window = notification.get("push_window", {})
  86. enabled_env = _get_env_bool("PUSH_WINDOW_ENABLED")
  87. once_per_day_env = _get_env_bool("PUSH_WINDOW_ONCE_PER_DAY")
  88. return {
  89. "ENABLED": enabled_env if enabled_env is not None else push_window.get("enabled", False),
  90. "TIME_RANGE": {
  91. "START": _get_env_str("PUSH_WINDOW_START") or push_window.get("start", "08:00"),
  92. "END": _get_env_str("PUSH_WINDOW_END") or push_window.get("end", "22:00"),
  93. },
  94. "ONCE_PER_DAY": once_per_day_env if once_per_day_env is not None else push_window.get("once_per_day", True),
  95. }
  96. def _load_weight_config(config_data: Dict) -> Dict:
  97. """加载权重配置"""
  98. advanced = config_data.get("advanced", {})
  99. weight = advanced.get("weight", {})
  100. return {
  101. "RANK_WEIGHT": weight.get("rank", 0.6),
  102. "FREQUENCY_WEIGHT": weight.get("frequency", 0.3),
  103. "HOTNESS_WEIGHT": weight.get("hotness", 0.1),
  104. }
  105. def _load_rss_config(config_data: Dict) -> Dict:
  106. """加载 RSS 配置"""
  107. rss = config_data.get("rss", {})
  108. advanced = config_data.get("advanced", {})
  109. advanced_rss = advanced.get("rss", {})
  110. advanced_crawler = advanced.get("crawler", {})
  111. # RSS 代理配置:优先使用 RSS 专属代理,否则复用 crawler 的 default_proxy
  112. rss_proxy_url = advanced_rss.get("proxy_url", "") or advanced_crawler.get("default_proxy", "")
  113. # 新鲜度过滤配置
  114. freshness_filter = rss.get("freshness_filter", {})
  115. # 验证并设置 max_age_days 默认值
  116. raw_max_age = freshness_filter.get("max_age_days", 3)
  117. try:
  118. max_age_days = int(raw_max_age)
  119. if max_age_days < 0:
  120. print(f"[警告] RSS freshness_filter.max_age_days 为负数 ({max_age_days}),使用默认值 3")
  121. max_age_days = 3
  122. except (ValueError, TypeError):
  123. print(f"[警告] RSS freshness_filter.max_age_days 格式错误 ({raw_max_age}),使用默认值 3")
  124. max_age_days = 3
  125. # RSS 配置直接从 config.yaml 读取,不再支持环境变量
  126. return {
  127. "ENABLED": rss.get("enabled", False),
  128. "REQUEST_INTERVAL": advanced_rss.get("request_interval", 2000),
  129. "TIMEOUT": advanced_rss.get("timeout", 15),
  130. "USE_PROXY": advanced_rss.get("use_proxy", False),
  131. "PROXY_URL": rss_proxy_url,
  132. "FEEDS": rss.get("feeds", []),
  133. "FRESHNESS_FILTER": {
  134. "ENABLED": freshness_filter.get("enabled", True), # 默认启用
  135. "MAX_AGE_DAYS": max_age_days,
  136. },
  137. "NOTIFICATION": {
  138. "ENABLED": advanced_rss.get("notification_enabled", False),
  139. },
  140. }
  141. def _load_storage_config(config_data: Dict) -> Dict:
  142. """加载存储配置"""
  143. storage = config_data.get("storage", {})
  144. formats = storage.get("formats", {})
  145. local = storage.get("local", {})
  146. remote = storage.get("remote", {})
  147. pull = storage.get("pull", {})
  148. txt_enabled_env = _get_env_bool("STORAGE_TXT_ENABLED")
  149. html_enabled_env = _get_env_bool("STORAGE_HTML_ENABLED")
  150. pull_enabled_env = _get_env_bool("PULL_ENABLED")
  151. return {
  152. "BACKEND": _get_env_str("STORAGE_BACKEND") or storage.get("backend", "auto"),
  153. "FORMATS": {
  154. "SQLITE": formats.get("sqlite", True),
  155. "TXT": txt_enabled_env if txt_enabled_env is not None else formats.get("txt", True),
  156. "HTML": html_enabled_env if html_enabled_env is not None else formats.get("html", True),
  157. },
  158. "LOCAL": {
  159. "DATA_DIR": local.get("data_dir", "output"),
  160. "RETENTION_DAYS": _get_env_int("LOCAL_RETENTION_DAYS") or local.get("retention_days", 0),
  161. },
  162. "REMOTE": {
  163. "ENDPOINT_URL": _get_env_str("S3_ENDPOINT_URL") or remote.get("endpoint_url", ""),
  164. "BUCKET_NAME": _get_env_str("S3_BUCKET_NAME") or remote.get("bucket_name", ""),
  165. "ACCESS_KEY_ID": _get_env_str("S3_ACCESS_KEY_ID") or remote.get("access_key_id", ""),
  166. "SECRET_ACCESS_KEY": _get_env_str("S3_SECRET_ACCESS_KEY") or remote.get("secret_access_key", ""),
  167. "REGION": _get_env_str("S3_REGION") or remote.get("region", ""),
  168. "RETENTION_DAYS": _get_env_int("REMOTE_RETENTION_DAYS") or remote.get("retention_days", 0),
  169. },
  170. "PULL": {
  171. "ENABLED": pull_enabled_env if pull_enabled_env is not None else pull.get("enabled", False),
  172. "DAYS": _get_env_int("PULL_DAYS") or pull.get("days", 7),
  173. },
  174. }
  175. def _load_webhook_config(config_data: Dict) -> Dict:
  176. """加载 Webhook 配置"""
  177. notification = config_data.get("notification", {})
  178. channels = notification.get("channels", {})
  179. # 各渠道配置
  180. feishu = channels.get("feishu", {})
  181. dingtalk = channels.get("dingtalk", {})
  182. wework = channels.get("wework", {})
  183. telegram = channels.get("telegram", {})
  184. email = channels.get("email", {})
  185. ntfy = channels.get("ntfy", {})
  186. bark = channels.get("bark", {})
  187. slack = channels.get("slack", {})
  188. return {
  189. # 飞书
  190. "FEISHU_WEBHOOK_URL": _get_env_str("FEISHU_WEBHOOK_URL") or feishu.get("webhook_url", ""),
  191. # 钉钉
  192. "DINGTALK_WEBHOOK_URL": _get_env_str("DINGTALK_WEBHOOK_URL") or dingtalk.get("webhook_url", ""),
  193. # 企业微信
  194. "WEWORK_WEBHOOK_URL": _get_env_str("WEWORK_WEBHOOK_URL") or wework.get("webhook_url", ""),
  195. "WEWORK_MSG_TYPE": _get_env_str("WEWORK_MSG_TYPE") or wework.get("msg_type", "markdown"),
  196. # Telegram
  197. "TELEGRAM_BOT_TOKEN": _get_env_str("TELEGRAM_BOT_TOKEN") or telegram.get("bot_token", ""),
  198. "TELEGRAM_CHAT_ID": _get_env_str("TELEGRAM_CHAT_ID") or telegram.get("chat_id", ""),
  199. # 邮件
  200. "EMAIL_FROM": _get_env_str("EMAIL_FROM") or email.get("from", ""),
  201. "EMAIL_PASSWORD": _get_env_str("EMAIL_PASSWORD") or email.get("password", ""),
  202. "EMAIL_TO": _get_env_str("EMAIL_TO") or email.get("to", ""),
  203. "EMAIL_SMTP_SERVER": _get_env_str("EMAIL_SMTP_SERVER") or email.get("smtp_server", ""),
  204. "EMAIL_SMTP_PORT": _get_env_str("EMAIL_SMTP_PORT") or email.get("smtp_port", ""),
  205. # ntfy
  206. "NTFY_SERVER_URL": _get_env_str("NTFY_SERVER_URL") or ntfy.get("server_url") or "https://ntfy.sh",
  207. "NTFY_TOPIC": _get_env_str("NTFY_TOPIC") or ntfy.get("topic", ""),
  208. "NTFY_TOKEN": _get_env_str("NTFY_TOKEN") or ntfy.get("token", ""),
  209. # Bark
  210. "BARK_URL": _get_env_str("BARK_URL") or bark.get("url", ""),
  211. # Slack
  212. "SLACK_WEBHOOK_URL": _get_env_str("SLACK_WEBHOOK_URL") or slack.get("webhook_url", ""),
  213. }
  214. def _print_notification_sources(config: Dict) -> None:
  215. """打印通知渠道配置来源信息"""
  216. notification_sources = []
  217. max_accounts = config["MAX_ACCOUNTS_PER_CHANNEL"]
  218. if config["FEISHU_WEBHOOK_URL"]:
  219. accounts = parse_multi_account_config(config["FEISHU_WEBHOOK_URL"])
  220. count = min(len(accounts), max_accounts)
  221. source = "环境变量" if os.environ.get("FEISHU_WEBHOOK_URL") else "配置文件"
  222. notification_sources.append(f"飞书({source}, {count}个账号)")
  223. if config["DINGTALK_WEBHOOK_URL"]:
  224. accounts = parse_multi_account_config(config["DINGTALK_WEBHOOK_URL"])
  225. count = min(len(accounts), max_accounts)
  226. source = "环境变量" if os.environ.get("DINGTALK_WEBHOOK_URL") else "配置文件"
  227. notification_sources.append(f"钉钉({source}, {count}个账号)")
  228. if config["WEWORK_WEBHOOK_URL"]:
  229. accounts = parse_multi_account_config(config["WEWORK_WEBHOOK_URL"])
  230. count = min(len(accounts), max_accounts)
  231. source = "环境变量" if os.environ.get("WEWORK_WEBHOOK_URL") else "配置文件"
  232. notification_sources.append(f"企业微信({source}, {count}个账号)")
  233. if config["TELEGRAM_BOT_TOKEN"] and config["TELEGRAM_CHAT_ID"]:
  234. tokens = parse_multi_account_config(config["TELEGRAM_BOT_TOKEN"])
  235. chat_ids = parse_multi_account_config(config["TELEGRAM_CHAT_ID"])
  236. valid, count = validate_paired_configs(
  237. {"bot_token": tokens, "chat_id": chat_ids},
  238. "Telegram",
  239. required_keys=["bot_token", "chat_id"]
  240. )
  241. if valid and count > 0:
  242. count = min(count, max_accounts)
  243. token_source = "环境变量" if os.environ.get("TELEGRAM_BOT_TOKEN") else "配置文件"
  244. notification_sources.append(f"Telegram({token_source}, {count}个账号)")
  245. if config["EMAIL_FROM"] and config["EMAIL_PASSWORD"] and config["EMAIL_TO"]:
  246. from_source = "环境变量" if os.environ.get("EMAIL_FROM") else "配置文件"
  247. notification_sources.append(f"邮件({from_source})")
  248. if config["NTFY_SERVER_URL"] and config["NTFY_TOPIC"]:
  249. topics = parse_multi_account_config(config["NTFY_TOPIC"])
  250. tokens = parse_multi_account_config(config["NTFY_TOKEN"])
  251. if tokens:
  252. valid, count = validate_paired_configs(
  253. {"topic": topics, "token": tokens},
  254. "ntfy"
  255. )
  256. if valid and count > 0:
  257. count = min(count, max_accounts)
  258. server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件"
  259. notification_sources.append(f"ntfy({server_source}, {count}个账号)")
  260. else:
  261. count = min(len(topics), max_accounts)
  262. server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件"
  263. notification_sources.append(f"ntfy({server_source}, {count}个账号)")
  264. if config["BARK_URL"]:
  265. accounts = parse_multi_account_config(config["BARK_URL"])
  266. count = min(len(accounts), max_accounts)
  267. bark_source = "环境变量" if os.environ.get("BARK_URL") else "配置文件"
  268. notification_sources.append(f"Bark({bark_source}, {count}个账号)")
  269. if config["SLACK_WEBHOOK_URL"]:
  270. accounts = parse_multi_account_config(config["SLACK_WEBHOOK_URL"])
  271. count = min(len(accounts), max_accounts)
  272. slack_source = "环境变量" if os.environ.get("SLACK_WEBHOOK_URL") else "配置文件"
  273. notification_sources.append(f"Slack({slack_source}, {count}个账号)")
  274. if notification_sources:
  275. print(f"通知渠道配置来源: {', '.join(notification_sources)}")
  276. print(f"每个渠道最大账号数: {max_accounts}")
  277. else:
  278. print("未配置任何通知渠道")
  279. def load_config(config_path: Optional[str] = None) -> Dict[str, Any]:
  280. """
  281. 加载配置文件
  282. Args:
  283. config_path: 配置文件路径,默认从环境变量 CONFIG_PATH 获取或使用 config/config.yaml
  284. Returns:
  285. 包含所有配置的字典
  286. Raises:
  287. FileNotFoundError: 配置文件不存在
  288. """
  289. if config_path is None:
  290. config_path = os.environ.get("CONFIG_PATH", "config/config.yaml")
  291. if not Path(config_path).exists():
  292. raise FileNotFoundError(f"配置文件 {config_path} 不存在")
  293. with open(config_path, "r", encoding="utf-8") as f:
  294. config_data = yaml.safe_load(f)
  295. print(f"配置文件加载成功: {config_path}")
  296. # 合并所有配置
  297. config = {}
  298. # 应用配置
  299. config.update(_load_app_config(config_data))
  300. # 爬虫配置
  301. config.update(_load_crawler_config(config_data))
  302. # 报告配置
  303. config.update(_load_report_config(config_data))
  304. # 通知配置
  305. config.update(_load_notification_config(config_data))
  306. # 推送窗口配置
  307. config["PUSH_WINDOW"] = _load_push_window_config(config_data)
  308. # 权重配置
  309. config["WEIGHT_CONFIG"] = _load_weight_config(config_data)
  310. # 平台配置
  311. config["PLATFORMS"] = config_data.get("platforms", [])
  312. # RSS 配置
  313. config["RSS"] = _load_rss_config(config_data)
  314. # 存储配置
  315. config["STORAGE"] = _load_storage_config(config_data)
  316. # Webhook 配置
  317. config.update(_load_webhook_config(config_data))
  318. # 打印通知渠道配置来源
  319. _print_notification_sources(config)
  320. return config