⭐AI-driven public opinion & trend monitor with multi-platform aggregation, RSS, and smart alerts.🎯 告别信息过载,你的 AI 舆情监控助手与热点筛选工具!聚合多平台热点 + RSS 订阅,支持关键词精准筛选。AI 智能筛选新闻 + AI 翻译 + AI 分析简报直推手机,也支持接入 MCP 架构,赋能 AI 自然语言对话分析、情感洞察与趋势预测等。支持 Docker ,数据本地/云端自持。集成微信/飞书/钉钉/Telegram/邮件/ntfy/bark/slack 等渠道智能推送。
Python aibarkdata-analysisdockerhot-newsllmmailmcpmcp-servernewsntfypythonrsstrending-topicswechatwework
feat: 版本检查支持 CDN 多源回退,优化国内网络可访问性
sansan44607453d6b2
diff --git a/docs/assets/script.js b/docs/assets/script.jsindex f8c3ee861d..a4a574029b 100644--- a/docs/assets/script.js+++ b/docs/assets/script.js@@ -118,11 +118,55 @@ const STORAGE_KEY_CONFIG_TIME = 'trendradar_config_time';const STORAGE_KEY_FREQUENCY_TIME = 'trendradar_frequency_time';const STORAGE_KEY_TIMELINE_TIME = 'trendradar_timeline_time';-// 官网配置文件 URL-const REMOTE_CONFIG_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/config.yaml';-const REMOTE_FREQUENCY_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/frequency_words.txt';-const REMOTE_TIMELINE_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/timeline.yaml';-const REMOTE_VERSION_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version_configs';+// 官网配置文件 URL(GitHub 主源)+const GITHUB_RAW_BASE = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/';+const REMOTE_CONFIG_URL = GITHUB_RAW_BASE + 'config/config.yaml';+const REMOTE_FREQUENCY_URL = GITHUB_RAW_BASE + 'config/frequency_words.txt';+const REMOTE_TIMELINE_URL = GITHUB_RAW_BASE + 'config/timeline.yaml';+const REMOTE_VERSION_URL = GITHUB_RAW_BASE + 'version_configs';++// 所有源(GitHub 主源 + CDN 备用源),按优先级排列+const ALL_SOURCES = [+ GITHUB_RAW_BASE,+ 'https://fastly.jsdelivr.net/gh/sansan0/TrendRadar@master/',+ 'https://cdn.jsdelivr.net/gh/sansan0/TrendRadar@master/',+ 'https://gcore.jsdelivr.net/gh/sansan0/TrendRadar@master/',+];+let lastOkIndex = 0;++async function fetchWithTimeout(url, timeout = 5000) {+ const controller = new AbortController();+ const id = setTimeout(() => controller.abort(), timeout);+ try {+ const resp = await fetch(url, { signal: controller.signal });+ clearTimeout(id);+ return resp;+ } catch (e) {+ clearTimeout(id);+ throw e;+ }+}++async function fetchWithFallback(url, timeout = 5000) {+ const path = url.startsWith(GITHUB_RAW_BASE) ? url.slice(GITHUB_RAW_BASE.length) : null;+ if (!path) return fetch(url);++ const n = ALL_SOURCES.length;+ for (let offset = 0; offset < n; offset++) {+ const idx = (lastOkIndex + offset) % n;+ try {+ const resp = await fetchWithTimeout(ALL_SOURCES[idx] + path, timeout);+ if (resp.ok) {+ if (idx !== lastOkIndex) {+ console.log(`[CDN] 已切换到: ${ALL_SOURCES[idx].split('//')[1].split('/')[0]}`);+ }+ lastOkIndex = idx;+ return resp;+ }+ } catch {}+ }+ throw new Error('所有源均不可用,请检查网络连接');+}let currentYaml = "";let currentFrequency = "";@@ -569,13 +613,13 @@ window.confirmLoadConfig = async function() {}closeLoadConfigModal();- showToast('正在从 GitHub 加载...', 'info');+ showToast('正在加载最新配置...', 'info');try {const promises = [];- if (loadConfig) promises.push(fetch(REMOTE_CONFIG_URL).then(r => ({ type: 'config', res: r })));- if (loadFrequency) promises.push(fetch(REMOTE_FREQUENCY_URL).then(r => ({ type: 'frequency', res: r })));- if (loadTimeline) promises.push(fetch(REMOTE_TIMELINE_URL).then(r => ({ type: 'timeline', res: r })));+ if (loadConfig) promises.push(fetchWithFallback(REMOTE_CONFIG_URL).then(r => ({ type: 'config', res: r })));+ if (loadFrequency) promises.push(fetchWithFallback(REMOTE_FREQUENCY_URL).then(r => ({ type: 'frequency', res: r })));+ if (loadTimeline) promises.push(fetchWithFallback(REMOTE_TIMELINE_URL).then(r => ({ type: 'timeline', res: r })));const results = await Promise.all(promises);@@ -3245,7 +3289,7 @@ window.checkVersion = async function() {btn.disabled = true;try {- const versionRes = await fetch(REMOTE_VERSION_URL);+ const versionRes = await fetchWithFallback(REMOTE_VERSION_URL);if (!versionRes.ok) {throw new Error(`版本信息获取失败: ${versionRes.status}`);}@@ -3595,11 +3639,11 @@ window.updateToLatest = async function() {return;}- showToast('正在从 GitHub 加载最新版本...', 'info');+ showToast('正在加载最新版本...', 'info');try {const url = currentTab === 'config' ? REMOTE_CONFIG_URL : REMOTE_FREQUENCY_URL;- const res = await fetch(url);+ const res = await fetchWithFallback(url);if (!res.ok) {throw new Error(`加载失败: ${res.status}`);diff --git a/mcp_server/tools/system.py b/mcp_server/tools/system.pyindex 047f3f7c5c..fe0adb374f 100644--- a/mcp_server/tools/system.py+++ b/mcp_server/tools/system.py@@ -413,13 +413,21 @@ class SystemManagementTools:proxies: Optional[Dict],headers: Dict) -> Dict:- """检查单个组件的版本"""+ """检查单个组件的版本(支持 CDN 多源回退)"""try:- response = requests.get(- remote_url, proxies=proxies, headers=headers, timeout=10- )- response.raise_for_status()- remote_version = response.text.strip()+ from trendradar.core.cdn import fetch_with_fallback+ proxy_url = None+ if proxies:+ proxy_url = proxies.get("https") or proxies.get("http")+ remote_version = fetch_with_fallback(remote_url, proxy_url)++ if not remote_version:+ return {+ "success": False,+ "name": name,+ "current_version": local_version,+ "error": "所有版本检查源均不可用"+ }local_tuple = parse_version(local_version)remote_tuple = parse_version(remote_version)@@ -442,20 +450,6 @@ class SystemManagementTools:"remote_parsed": list(remote_tuple),"message": message}- except requests.exceptions.Timeout:- return {- "success": False,- "name": name,- "current_version": local_version,- "error": "获取远程版本超时"- }- except requests.exceptions.RequestException as e:- return {- "success": False,- "name": name,- "current_version": local_version,- "error": f"网络请求失败: {str(e)}"- }except Exception as e:return {"success": False,diff --git a/trendradar/__main__.py b/trendradar/__main__.pyindex 38a9f82d35..b23ec67bdb 100644--- a/trendradar/__main__.py+++ b/trendradar/__main__.py@@ -28,6 +28,7 @@ from trendradar.storage import convert_crawl_results_to_news_datafrom trendradar.utils.time import DEFAULT_TIMEZONE, is_within_days, calculate_days_oldfrom trendradar.ai import AIAnalyzer, AIAnalysisResultfrom trendradar.core.scheduler import ResolvedSchedule+from trendradar.core.cdn import fetch_with_fallbackdef _parse_version(version_str: str) -> Tuple[int, int, int]:@@ -55,24 +56,8 @@ def _compare_version(local: str, remote: str) -> str:def _fetch_remote_version(version_url: str, proxy_url: Optional[str] = None) -> Optional[str]:- """获取远程版本号"""- try:- proxies = None- if proxy_url:- proxies = {"http": proxy_url, "https": proxy_url}-- headers = {- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",- "Accept": "text/plain, */*",- "Cache-Control": "no-cache",- }-- response = requests.get(version_url, proxies=proxies, headers=headers, timeout=10)- response.raise_for_status()- return response.text.strip()- except Exception as e:- print(f"[版本检查] 获取远程版本失败: {e}")- return None+ """获取远程版本号(支持 CDN 多源回退)"""+ return fetch_with_fallback(version_url, proxy_url)def _parse_config_versions(content: str) -> Dict[str, str]:diff --git a/trendradar/core/cdn.py b/trendradar/core/cdn.pynew file mode 100644index 0000000000..eec80201dc--- /dev/null+++ b/trendradar/core/cdn.py@@ -0,0 +1,91 @@+# coding=utf-8+"""+CDN 回退模块++为版本检查等远程请求提供多源回退能力。+默认使用 GitHub 原始链接,失败后自动切换到 CDN 备用源。+同一会话中记住可用源的索引,后续请求从该源开始尝试。+"""++import re+import logging+from typing import Optional++import requests++logger = logging.getLogger(__name__)++_GITHUB_RAW_PATTERN = re.compile(+ r"^https://raw\.githubusercontent\.com/sansan0/TrendRadar/(?:refs/heads/)?master/(.+)$"+)++_ALL_SOURCES = [+ "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/",+ "https://fastly.jsdelivr.net/gh/sansan0/TrendRadar@master/",+ "https://cdn.jsdelivr.net/gh/sansan0/TrendRadar@master/",+ "https://gcore.jsdelivr.net/gh/sansan0/TrendRadar@master/",+]++_SOURCE_LABELS = {+ _ALL_SOURCES[0]: "GitHub",+ _ALL_SOURCES[1]: "fastly.jsdelivr.net",+ _ALL_SOURCES[2]: "cdn.jsdelivr.net",+ _ALL_SOURCES[3]: "gcore.jsdelivr.net",+}++_HEADERS = {+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",+ "Accept": "text/plain, */*",+ "Cache-Control": "no-cache",+}++_TIMEOUT = 5++_state = {"last_ok": 0}+++def _extract_path(url: str) -> Optional[str]:+ m = _GITHUB_RAW_PATTERN.match(url)+ return m.group(1) if m else None+++def _do_request(url: str, proxies: Optional[dict]) -> str:+ resp = requests.get(url, headers=_HEADERS, proxies=proxies, timeout=_TIMEOUT)+ resp.raise_for_status()+ return resp.text.strip()+++def fetch_with_fallback(+ url: str,+ proxy_url: Optional[str] = None,+) -> Optional[str]:+ """从上次成功的源开始轮转尝试,非 GitHub 链接直接请求。"""+ proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None++ path = _extract_path(url)+ if path is None:+ try:+ return _do_request(url, proxies)+ except Exception as e:+ logger.warning("[版本检查] 获取失败: %s", e)+ return None++ n = len(_ALL_SOURCES)+ start = _state["last_ok"]++ for offset in range(n):+ idx = (start + offset) % n+ source = _ALL_SOURCES[idx]+ try:+ content = _do_request(source + path, proxies)+ if idx != start:+ label = _SOURCE_LABELS.get(source, source)+ logger.info("[版本检查] 已切换到: %s", label)+ _state["last_ok"] = idx+ return content+ except Exception:+ label = _SOURCE_LABELS.get(source, source)+ logger.debug("[版本检查] %s 不可用,尝试下一个源", label)++ logger.warning("[版本检查] 所有源均不可用")+ return None