Files
tangzhuan-yu/app/hub_report.py
T
jinghui b3377dccd6 feat: 躺赚鱼 v3.6.2 —— xianyu-auto-reply 深度定制版首发
新增: 实时热卖榜(11分类/想要人数排序/热门搜索词热度)、价格监控(目标价通知/卖家信用筛选/销量下限/AI精准监控)、
一键转卖(收藏自动加载/改价直发/详情直达)、AI回复免费token(ai.88531.cn)、API密钥掩码、
推理模型兼容修复、商品本地编辑、授权系统接入(在线人数/版本/公告)、品牌更名躺赚鱼。

README 重写为项目介绍(改动清单/优势/真实截图/两种安装方式/体验地址 tzy.88531.cn/使用引导),
原版 README 完整保留为 README.upstream.md。
2026-11-16 01:00:59 +08:00

297 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""授权系统接入:在线心跳(在线人数统计)+ 版本检查(版本推送)。
公告推送已在 app/announcement.py 接入授权系统,这里补齐另外两样能力:
- heartbeat:每 HUB_HEARTBEAT_INTERVAL 秒向授权系统上报一次,
授权系统据此统计在线人数(管理后台「在线统计」页)。
- check-update:前端「检查更新」时调用,返回授权系统下发的最新版本,
版本行由授权系统管理后台的「项目版本」发布。
密钥 HUB_API_KEY 从项目根 .env 读取(该文件已被 .gitignore 忽略,不进包),
不烤进镜像、不写进 global_config.yml(那个文件会随源码分发)。
本模块任何失败都只记日志,绝不影响面板主功能。
"""
import asyncio
import os
import uuid
from pathlib import Path
from typing import Any, Dict, Optional
from loguru import logger
PROJECT_ROOT = Path(__file__).resolve().parent.parent
# 授权系统地址与项目号。公告侧见 app/announcement.py 的 HUB_* 常量,
# 两处必须保持一致(同一个项目)。
HUB_BASE_URL = 'https://auth.88531.cn'
HUB_PROJECT_ID = 13
# 心跳间隔(秒)。授权系统「在线统计」按最近 5 分钟内的心跳数算在线,
# 这里取 5 分钟一次,既够判定在线又不会打满对方 60 次/分钟的限流。
HUB_HEARTBEAT_INTERVAL = 300
# 单次请求超时(秒)。超时绝不能拖住面板,宁可丢一次心跳下次再报。
HUB_TIMEOUT = 10
_env_loaded = False
def _load_env_file() -> None:
"""把项目根 .env 里的 HUB_* 键补进 os.environ(不覆盖已有值)。
容器是 docker run 起的、没有 env_file,重启容器会丢 -e 传的变量,
所以密钥放挂载进容器的源码目录 .env,重建容器也不受影响。
"""
global _env_loaded
if _env_loaded:
return
_env_loaded = True
env_path = PROJECT_ROOT / '.env'
if not env_path.exists():
return
try:
for line in env_path.read_text(encoding='utf-8').splitlines():
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, _, value = line.partition('=')
key = key.strip()
# 只关心授权系统相关键,且不覆盖容器已显式设置的值
if key.startswith('HUB_') and key not in os.environ:
os.environ[key] = value.strip().strip('"').strip("'")
except Exception as exc:
logger.warning(f'读取 .env 失败(不影响主功能): {exc}')
def _hub_url(path: str) -> str:
_load_env_file()
base = os.environ.get('HUB_BASE_URL', HUB_BASE_URL).rstrip('/')
return f'{base}{path}'
def get_api_key() -> str:
"""授权系统为本项目签发的 API Key(缺省为空=未配置,调用方应跳过上报)。"""
_load_env_file()
return os.environ.get('HUB_API_KEY', '').strip()
def get_project_id() -> int:
_load_env_file()
try:
return int(os.environ.get('HUB_PROJECT_ID', HUB_PROJECT_ID))
except (TypeError, ValueError):
return HUB_PROJECT_ID
def get_machine_id() -> str:
"""本部署的稳定机器码。
授权系统靠它区分「一台机器反复上报」与「多台机器同时在线」——
每次重启都换新码会把一台机器算成多台在线人数,所以必须持久化。
写在 data/ 目录(挂载到宿主,容器重建不丢)。
"""
_load_env_file()
# 允许部署方显式指定固定机器码
forced = os.environ.get('HUB_MACHINE_ID', '').strip()
if forced:
return forced
data_dir = PROJECT_ROOT / 'data'
id_file = data_dir / 'hub_machine_id'
try:
if id_file.exists():
existing = id_file.read_text(encoding='utf-8').strip()
if existing:
return existing
machine_id = f'xybutler-{uuid.uuid4().hex[:24]}'
data_dir.mkdir(parents=True, exist_ok=True)
# 0600:机器码虽不算秘密,但不给同机其他用户可读
id_file.write_text(machine_id, encoding='utf-8')
try:
os.chmod(id_file, 0o600)
except OSError:
pass
return machine_id
except Exception as exc:
# 文件写不了就退回进程内随机码:在线人数会因此按重启拆分,
# 但绝不能因为拿不到机器码就让心跳整个停摆。
logger.warning(f'机器码持久化失败,改用临时码: {exc}')
return f'xybutler-{uuid.uuid4().hex[:24]}'
def _client_version() -> str:
"""当前面板版本号。复用公告模块的 APP_VERSION,避免两处版本号漂移。"""
try:
from app.announcement import get_local_version
return get_local_version()
except Exception:
return '0.0.0'
def _device_info() -> str:
"""设备描述,只带必要信息,不采集任何用户数据。"""
try:
import platform
return f'{platform.system()} {platform.machine()}'
except Exception:
return ''
async def send_heartbeat() -> Optional[Dict[str, Any]]:
"""上报一次在线心跳。成功返回接口 data,失败返回 None(只记日志)。"""
key = get_api_key()
if not key:
# 未配置密钥=尚未接入,静默跳过,避免每次启动刷一堆错误
logger.debug('HUB_API_KEY 未配置,跳过在线心跳')
return None
import aiohttp
body = {
'machine_id': get_machine_id(),
'client_version': _client_version(),
'device_info': _device_info(),
}
# IP 不由客户端上报:客户端看到的是出口 NAT 地址,没有参考价值,
# 授权系统自己按连接来源记。
try:
timeout = aiohttp.ClientTimeout(total=HUB_TIMEOUT)
headers = {'X-Api-Key': key, 'Content-Type': 'application/json'}
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(
_hub_url('/api/public/installations/heartbeat'),
json=body, headers=headers,
) as resp:
if resp.status != 200:
text = (await resp.text())[:200]
logger.warning(f'在线心跳返回 HTTP {resp.status}: {text}')
return None
payload = await resp.json(content_type=None)
data = payload.get('data') if isinstance(payload, dict) else None
logger.debug(f'在线心跳已上报: install_id={data and data.get("install_id")}')
return data if isinstance(data, dict) else {}
except asyncio.TimeoutError:
logger.warning(f'在线心跳超时({HUB_TIMEOUT}s)')
except Exception as exc:
logger.warning(f'在线心跳失败: {exc}')
return None
async def check_update() -> Optional[Dict[str, Any]]:
"""向授权系统查最新版本。成功返回规范化结果,失败返回 None。
返回结构(与授权系统 check-update 接口对齐,缺字段一律给空值):
update_available / update_required / current_version / latest_version
download_url / changelog / file_size / checksum / min_client_version
"""
key = get_api_key()
if not key:
logger.debug('HUB_API_KEY 未配置,跳过版本检查')
return None
import aiohttp
body = {
'machine_id': get_machine_id(),
'client_version': _client_version(),
}
try:
timeout = aiohttp.ClientTimeout(total=HUB_TIMEOUT)
headers = {'X-Api-Key': key, 'Content-Type': 'application/json'}
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(
_hub_url('/api/public/installations/check-update'),
json=body, headers=headers,
) as resp:
if resp.status != 200:
text = (await resp.text())[:200]
logger.warning(f'版本检查返回 HTTP {resp.status}: {text}')
return None
payload = await resp.json(content_type=None)
raw = payload.get('data') if isinstance(payload, dict) else None
if not isinstance(raw, dict):
return None
current = _client_version()
latest = str(raw.get('latest_version') or '').strip()
return {
# 接口没给 update_available 时按版本号自己判,前端不用再比一次
'update_available': bool(raw.get('update_available')) or bool(latest and latest != current),
'update_required': bool(raw.get('update_required')),
'is_force': bool(raw.get('is_force')),
'current_version': current,
'latest_version': latest,
'download_url': str(raw.get('download_url') or '').strip(),
'changelog': raw.get('changelog') or '',
'file_size': int(raw.get('file_size') or 0),
'checksum': str(raw.get('checksum') or '').strip(),
'min_client_version': str(raw.get('min_client_version') or '').strip(),
}
except asyncio.TimeoutError:
logger.warning(f'版本检查超时({HUB_TIMEOUT}s)')
except Exception as exc:
logger.warning(f'版本检查失败: {exc}')
return None
# ---------------------------------------------------------------------------
# 后台心跳循环
# ---------------------------------------------------------------------------
_heartbeat_task: Optional[asyncio.Task] = None
async def _heartbeat_loop() -> None:
"""周期心跳。首次立即上报(让刚启动的面板马上出现在在线列表)。
循环本身永不抛出:授权系统临时挂了也要继续重试,不能让任务静默死掉。
"""
interval = HUB_HEARTBEAT_INTERVAL
_load_env_file()
try:
interval = int(os.environ.get('HUB_HEARTBEAT_INTERVAL', HUB_HEARTBEAT_INTERVAL))
except (TypeError, ValueError):
interval = HUB_HEARTBEAT_INTERVAL
interval = max(60, interval) # 低于 60 秒会撞对方按分钟的限流
while True:
try:
await send_heartbeat()
except Exception as exc:
logger.warning(f'心跳循环异常(继续运行): {exc}')
try:
await asyncio.sleep(interval)
except asyncio.CancelledError:
break
def start_heartbeat_scheduler() -> None:
"""启动心跳后台任务(在 FastAPI startup 事件里调用)。"""
global _heartbeat_task
if not get_api_key():
logger.info('授权系统心跳未启用(HUB_API_KEY 未配置)')
return
if _heartbeat_task is not None and not _heartbeat_task.done():
return
try:
_heartbeat_task = asyncio.get_event_loop().create_task(_heartbeat_loop())
logger.info(
f'授权系统心跳已启动: project={get_project_id()} '
f'interval={HUB_HEARTBEAT_INTERVAL}s'
)
except Exception as exc:
logger.error(f'授权系统心跳启动失败: {exc}')
def stop_heartbeat_scheduler() -> None:
"""停止心跳(shutdown 时调用,避免任务在事件循环关闭后被强杀)。"""
global _heartbeat_task
if _heartbeat_task is not None and not _heartbeat_task.done():
_heartbeat_task.cancel()
_heartbeat_task = None