v1.1.0: AI回复max_tokens调优 + 商品编辑(标题/价格/描述) + API密钥掩码

- ai_reply_engine.py: 意图识别max_tokens=100, 回复生成max_tokens=2048
  (deepseek-v4-flash推理模型思考吃光token导致回复为空)
- 商品管理弹窗新增标题/价格/描述编辑, 写入本地item_info
  (闲鱼网页版不支持改真实商品, 界面已注明)
- GET ai-reply-settings密钥掩码 sk-4****27QK, PUT含****保留原值
- 新增自定义Dockerfile固化max_tokens补丁
- 新增.gitignore排除.env/data/logs/db, 仓库不含密钥
This commit is contained in:
jinghui committed 2026-10-22 12:07:09 +08:00
commit 198ccd3976
63 files changed
+46452

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
# Git相关
.git
.gitignore
.gitattributes
# Python相关
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# 虚拟环境
venv/
env/
ENV/
env.bak/
venv.bak/
# IDE相关
.vscode/
.idea/
*.swp
*.swo
*~
# 操作系统相关
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# 日志文件
logs/*.log
*.log
# 数据库文件(构建时不包含,运行时挂载)
*.db
*.sqlite
*.sqlite3
# 临时文件
*.tmp
*.temp
temp/
tmp/
# 测试文件
test_*.py
*_test.py
tests/
# 文档
*.md
docs/
# Docker相关(保留必要的构建文件)
.dockerignore.bak
docker-compose.override.yml
# 配置文件(运行时挂载)
# global_config.yml
# 环境变量文件
.env
.env.*
!.env.example
*.local.yml
*.dev.yml
*.test.yml
config.*.yml
!global_config.yml
# 前端相关
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
package-lock.json
yarn.lock
# 数据目录(运行时挂载)
data/
backups/
logs/
realtime.log
# 上传文件
static/uploads/*
!static/uploads/.gitkeep
!static/uploads/images/
static/uploads/images/*
!static/uploads/images/.gitkeep
# Excel和数据文件
*.xlsx
*.xls
*.csv
keywords_*.xlsx
export_*.csv
export_*.json
export_*.xlsx
# 压缩文件
*.zip
*.tar.gz
*.rar
*.7z
# 备份文件
*.bak
*.backup
*.old
# 密钥和证书
*.key
*.pem
*.crt
*.cert
*.p12
*.pfx
ssl/
secrets/
credentials/
# 运行时文件
*.pid
*.sock
*.lock
*.port
# 性能分析文件
*.prof
*.profile
*.pstats
# 缓存文件
.cache/
cache/
*.cache
# 浏览器相关
.playwright/
playwright-report/
test-results/
# 示例和演示文件
example_*.py
*_example.py
demo_*.py
*_demo.py
# AI模型文件
*.model
*.weights
*.h5
*.pb
# 大文件
*.iso
*.dmg
*.img
# 监控和审计
monitoring/
*.access.log
*.error.log
*.audit.log
# 本地开发文件
local/
.local/
debug.log
*.debug
+32
View File
@@ -0,0 +1,32 @@
# 运行时数据与密钥 —— 永不提交
.env
.env.*
*.env
data/
logs/
backups/
*.log
realtime.log
# 数据库
*.db
*.db-journal
*.db-wal
*.db-shm
# 运行时上传目录(与容器共享)
static/uploads/images/
# Python 缓存
__pycache__/
*.py[cod]
*.pyo
.pytest_cache/
.venv/
venv/
# 编辑器 / 系统
.vscode/
.idea/
.DS_Store
*.swp
+40
View File
@@ -0,0 +1,40 @@
# 更新日志
本项目基于闲鱼自动回复系统二次开发,记录本地改动。
---
## 2026-10-22 · v1.1.0
### ✨ 新功能
- **商品管理支持编辑标题 / 价格 / 描述**
- 后台「商品管理 → 编辑」弹窗新增 **商品标题、商品价格、商品描述** 三个输入框。
- 保存后写入本地数据库(`item_info` 表),供 AI 关键词匹配与回复参考。
- `db_manager.py` 新增 `update_item_fields()`,支持多字段动态更新。
- `reply_server.py` 的 `PUT /items/{cookie_id}/{item_id}` 接收新字段。
- 弹窗内提示:**闲鱼网页版不支持修改真实商品**,本地改动仅用于回复参考,真实商品请在闲鱼 APP 中编辑。
- **API 密钥掩码显示(安全加固)**
- `GET /ai-reply-settings/{cookie_id}` 返回的 `api_key` 掩码为 `sk-4****27QK`,不再明文暴露。
- `PUT` 保存时,若密钥仍含 `****` 则**保留原值**,避免掩码覆盖真实密钥。
- 前端密钥输入框改为密码框,带 👁 显隐切换按钮;提示「密钥已掩码显示,如不修改则保持原值」。
### 🐛 修复
- **AI 回复无内容(reasoning 模型耗尽 token)**
- 根因:`deepseek-v4-flash` 为推理模型,思考阶段吃光 `max_tokens`,输出为空。
- `ai_reply_engine.py`:意图识别 `max_tokens` 设为 `100`;回复生成 `max_tokens` 提升至 `2048`。
- 修复后回复链路正常(实测 reasoning≈740 tokens 仍能产出正文)。
### 🔧 工程
- 新增**自定义 `Dockerfile`**:在官方镜像基础上用 `sed` 打 `max_tokens` 补丁,`docker compose build` 后改动不丢失。
- 新增 `.gitignore`:排除 `.env`、`data/`、`logs/`、`*.db`、`uploads`、`__pycache__`,仓库不含任何运行时数据与密钥。
---
## 初始版本
- 基于 `registry.cn-shanghai.aliyuncs.com/zhinian-software/xianyu-auto-reply:1.0` 镜像源码。
- 功能:闲鱼自动回复、AI 大模型回复、关键词匹配、自动确认发货、免拼发货、商品与订单管理。
+107
View File
@@ -0,0 +1,107 @@
# 使用Python 3.11作为基础镜像
FROM python:3.11-slim-bookworm
# 设置标签信息
LABEL maintainer="zhinianboke"
LABEL version="2.1.0"
LABEL description="闲鱼自动回复系统 - 企业级多用户版本,支持自动发货和免拼发货"
LABEL repository="https://github.com/zhinianboke/xianyu-auto-reply"
LABEL license="仅供学习使用,禁止商业用途"
LABEL author="zhinianboke"
# 设置工作目录
WORKDIR /app
# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV TZ=Asia/Shanghai
ENV DOCKER_ENV=true
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
# 安装系统依赖(包括Playwright浏览器依赖)
RUN apt-get update && \
apt-get install -y --no-install-recommends \
# 基础工具
nodejs \
npm \
tzdata \
curl \
ca-certificates \
# 图像处理依赖
libjpeg-dev \
libpng-dev \
libfreetype6-dev \
fonts-dejavu-core \
fonts-liberation \
# Playwright浏览器依赖
libnss3 \
libnspr4 \
libatk-bridge2.0-0 \
libdrm2 \
libxkbcommon0 \
libxcomposite1 \
libxdamage1 \
libxrandr2 \
libgbm1 \
libxss1 \
libasound2 \
libatspi2.0-0 \
libgtk-3-0 \
libgdk-pixbuf2.0-0 \
libxcursor1 \
libxi6 \
libxrender1 \
libxext6 \
libx11-6 \
libxft2 \
libxinerama1 \
libxtst6 \
libappindicator3-1 \
libx11-xcb1 \
libxfixes3 \
xdg-utils \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& rm -rf /tmp/* \
&& rm -rf /var/tmp/*
# 设置时区
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 验证Node.js安装并设置环境变量
RUN node --version && npm --version
ENV NODE_PATH=/usr/lib/node_modules
# 复制requirements.txt并安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
# 复制项目文件
COPY . .
# 安装Playwright浏览器(必须在复制项目文件之后)
RUN playwright install chromium && \
playwright install-deps chromium
# 创建必要的目录并设置权限
RUN mkdir -p /app/logs /app/data /app/backups /app/static/uploads/images && \
chmod 777 /app/logs /app/data /app/backups /app/static/uploads /app/static/uploads/images
# 注意: 为了简化权限问题,使用root用户运行
# 在生产环境中,建议配置适当的用户映射
# 暴露端口
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# 复制启动脚本
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# 启动命令
CMD ["/app/entrypoint.sh"]
+110
View File
@@ -0,0 +1,110 @@
# 使用Python 3.11作为基础镜像
FROM python:3.11-slim-bookworm
# 设置标签信息
LABEL maintainer="zhinianboke"
LABEL version="2.1.0"
LABEL description="闲鱼自动回复系统 - 企业级多用户版本,支持自动发货和免拼发货"
LABEL repository="https://github.com/zhinianboke/xianyu-auto-reply"
LABEL license="仅供学习使用,禁止商业用途"
LABEL author="zhinianboke"
# 设置工作目录
WORKDIR /app
# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV TZ=Asia/Shanghai
ENV DOCKER_ENV=true
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
#更换中科大源
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list.d/debian.sources
# 安装系统依赖(包括Playwright浏览器依赖)
RUN apt-get update && \
apt-get install -y --no-install-recommends \
# 基础工具
nodejs \
npm \
tzdata \
curl \
ca-certificates \
# 图像处理依赖
libjpeg-dev \
libpng-dev \
libfreetype6-dev \
fonts-dejavu-core \
fonts-liberation \
# Playwright浏览器依赖
libnss3 \
libnspr4 \
libatk-bridge2.0-0 \
libdrm2 \
libxkbcommon0 \
libxcomposite1 \
libxdamage1 \
libxrandr2 \
libgbm1 \
libxss1 \
libasound2 \
libatspi2.0-0 \
libgtk-3-0 \
libgdk-pixbuf2.0-0 \
libxcursor1 \
libxi6 \
libxrender1 \
libxext6 \
libx11-6 \
libxft2 \
libxinerama1 \
libxtst6 \
libappindicator3-1 \
libx11-xcb1 \
libxfixes3 \
xdg-utils \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& rm -rf /tmp/* \
&& rm -rf /var/tmp/*
# 设置时区
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 验证Node.js安装并设置环境变量
RUN node --version && npm --version
ENV NODE_PATH=/usr/lib/node_modules
# 复制requirements.txt并安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple&& \
pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# 复制项目文件
COPY . .
# 安装Playwright浏览器(必须在复制项目文件之后)
RUN playwright install chromium && \
playwright install-deps chromium
# 创建必要的目录并设置权限
RUN mkdir -p /app/logs /app/data /app/backups /app/static/uploads/images && \
chmod 777 /app/logs /app/data /app/backups /app/static/uploads /app/static/uploads/images
# 注意: 为了简化权限问题,使用root用户运行
# 在生产环境中,建议配置适当的用户映射
# 暴露端口
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# 复制启动脚本
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# 启动命令
CMD ["/app/entrypoint.sh"]
+142
View File
@@ -0,0 +1,142 @@
"""项目启动入口:
1. 创建 CookieManager,按配置文件 / 环境变量初始化账号任务
2. 在后台线程启动 FastAPI (reply_server) 提供管理与自动回复接口
3. 主协程保持运行
"""
import os
import asyncio
import threading
import uvicorn
from urllib.parse import urlparse
from pathlib import Path
from loguru import logger
from config import AUTO_REPLY, COOKIES_LIST
import cookie_manager as cm
from db_manager import db_manager
from file_log_collector import setup_file_logging
def _start_api_server():
"""后台线程启动 FastAPI 服务"""
api_conf = AUTO_REPLY.get('api', {})
# 优先使用环境变量配置
host = os.getenv('API_HOST', '0.0.0.0') # 默认绑定所有接口
port = int(os.getenv('API_PORT', '8080')) # 默认端口8080
# 如果配置文件中有特定配置,则使用配置文件
if 'host' in api_conf:
host = api_conf['host']
if 'port' in api_conf:
port = api_conf['port']
# 兼容旧的URL配置方式
if 'url' in api_conf and 'host' not in api_conf and 'port' not in api_conf:
url = api_conf.get('url', 'http://0.0.0.0:8080/xianyu/reply')
parsed = urlparse(url)
if parsed.hostname and parsed.hostname != 'localhost':
host = parsed.hostname
port = parsed.port or 8080
logger.info(f"启动Web服务器: http://{host}:{port}")
uvicorn.run("reply_server:app", host=host, port=port, log_level="info")
def load_keywords_file(path: str):
"""从文件读取关键字 -> [(keyword, reply)]"""
kw_list = []
p = Path(path)
if not p.exists():
return kw_list
with p.open('r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '\t' in line:
k, r = line.split('\t', 1)
elif ' ' in line:
k, r = line.split(' ', 1)
elif ':' in line:
k, r = line.split(':', 1)
else:
continue
kw_list.append((k.strip(), r.strip()))
return kw_list
async def main():
print("开始启动主程序...")
# 初始化文件日志收集器
print("初始化文件日志收集器...")
setup_file_logging()
logger.info("文件日志收集器已启动,开始收集实时日志")
loop = asyncio.get_running_loop()
# 创建 CookieManager 并在全局暴露
print("创建 CookieManager...")
cm.manager = cm.CookieManager(loop)
manager = cm.manager
print("CookieManager 创建完成")
# 1) 从数据库加载的 Cookie 已经在 CookieManager 初始化时完成
# 为每个启用的 Cookie 启动任务
for cid, val in manager.cookies.items():
# 检查账号是否启用
if not manager.get_cookie_status(cid):
logger.info(f"跳过禁用的 Cookie: {cid}")
continue
try:
# 直接启动任务,不重新保存到数据库
from db_manager import db_manager
logger.info(f"正在获取Cookie详细信息: {cid}")
cookie_info = db_manager.get_cookie_details(cid)
user_id = cookie_info.get('user_id') if cookie_info else None
logger.info(f"Cookie详细信息获取成功: {cid}, user_id: {user_id}")
logger.info(f"正在创建异步任务: {cid}")
task = loop.create_task(manager._run_xianyu(cid, val, user_id))
manager.tasks[cid] = task
logger.info(f"启动数据库中的 Cookie 任务: {cid} (用户ID: {user_id})")
logger.info(f"任务已添加到管理器,当前任务数: {len(manager.tasks)}")
except Exception as e:
logger.error(f"启动 Cookie 任务失败: {cid}, {e}")
import traceback
logger.error(f"详细错误信息: {traceback.format_exc()}")
# 2) 如果配置文件中有新的 Cookie,也加载它们
for entry in COOKIES_LIST:
cid = entry.get('id')
val = entry.get('value')
if not cid or not val or cid in manager.cookies:
continue
kw_file = entry.get('keywords_file')
kw_list = load_keywords_file(kw_file) if kw_file else None
manager.add_cookie(cid, val, kw_list)
logger.info(f"从配置文件加载 Cookie: {cid}")
# 3) 若老环境变量仍提供单账号 Cookie,则作为 default 账号
env_cookie = os.getenv('COOKIES_STR')
if env_cookie and 'default' not in manager.list_cookies():
manager.add_cookie('default', env_cookie)
logger.info("从环境变量加载 default Cookie")
# 启动 API 服务线程
print("启动 API 服务线程...")
threading.Thread(target=_start_api_server, daemon=True).start()
print("API 服务线程已启动")
# 阻塞保持运行
print("主程序启动完成,保持运行...")
await asyncio.Event().wait()
if __name__ == '__main__':
asyncio.run(main())
+4360
View File
File diff suppressed because it is too large. Load diff
+370
View File
@@ -0,0 +1,370 @@
"""
AI回复引擎模块
集成XianyuAutoAgent的AI回复功能到现有项目中
"""
import os
import json
import time
import hashlib
import sqlite3
from typing import List, Dict, Optional
from loguru import logger
from openai import OpenAI
from db_manager import db_manager
class AIReplyEngine:
"""AI回复引擎"""
def __init__(self):
self.clients = {} # 存储不同账号的OpenAI客户端
self.agents = {} # 存储不同账号的Agent实例
self._cache = {} # AI回复缓存 {cache_key: (reply, expiry)}
self._intent_cache = {} # 意图缓存 {cache_key: (intent, expiry)}
self._cache_ttl = 3600 # 缓存有效期1小时
self._init_default_prompts()
def _make_cache_key(self, cookie_id: str, chat_id: str, message: str) -> str:
"""生成缓存键"""
raw = f"{cookie_id}|{chat_id}|{message}"
return hashlib.md5(raw.encode()).hexdigest()
def _get_cached_reply(self, cookie_id: str, chat_id: str, message: str) -> Optional[str]:
"""获取缓存的AI回复"""
key = self._make_cache_key(cookie_id, chat_id, message)
cached = self._cache.get(key)
if cached and time.time() < cached[1]:
logger.info(f"命中AI回复缓存 (账号: {cookie_id})")
return cached[0]
if cached:
del self._cache[key]
return None
def _set_cached_reply(self, cookie_id: str, chat_id: str, message: str, reply: str):
"""设置AI回复缓存"""
key = self._make_cache_key(cookie_id, chat_id, message)
self._cache[key] = (reply, time.time() + self._cache_ttl)
def _get_cached_intent(self, cookie_id: str, message: str) -> Optional[str]:
"""获取缓存的意图"""
key = self._make_cache_key(cookie_id, "", message)
cached = self._intent_cache.get(key)
if cached and time.time() < cached[1]:
return cached[0]
if cached:
del self._intent_cache[key]
return None
def _set_cached_intent(self, cookie_id: str, message: str, intent: str):
"""设置意图缓存"""
key = self._make_cache_key(cookie_id, "", message)
self._intent_cache[key] = (intent, time.time() + self._cache_ttl)
def _init_default_prompts(self):
"""初始化默认提示词"""
self.default_prompts = {
'classify': '''你是一个意图分类专家,需要判断用户消息的意图类型。
请根据用户消息内容,返回以下意图之一:
- price: 价格相关(议价、优惠、降价等)
- tech: 技术相关(产品参数、使用方法、故障等)
- refund: 退款相关(申请退款、退货、投诉等)
- default: 其他一般咨询
只返回意图类型,不要其他内容。''',
'price': '''你是一位经验丰富的销售专家,擅长议价。
语言要求:简短直接,每句≤10字,总字数≤40字。
议价策略:
1. 根据议价次数递减优惠:第1次小幅优惠,第2次中等优惠,第3次最大优惠
2. 接近最大议价轮数时要坚持底线,强调商品价值
3. 优惠不能超过设定的最大百分比和金额
4. 语气要友好但坚定,突出商品优势
注意:结合商品信息、对话历史和议价设置,给出合适的回复。''',
'tech': '''你是一位技术专家,专业解答产品相关问题。
语言要求:简短专业,每句≤10字,总字数≤40字。
回答重点:产品功能、使用方法、注意事项。
注意:基于商品信息回答,避免过度承诺。''',
'refund': '''你是一位售后客服,处理用户的退款退货请求。
语言要求:礼貌耐心,语气温和,每句≤15字,总字数≤60字。
注意:请严格遵循【退款策略】指示。''',
'default': '''你是一位资深电商卖家,提供优质客服。
语言要求:简短友好,每句≤10字,总字数≤40字。
回答重点:商品介绍、物流、售后等常见问题。
注意:结合商品信息,给出实用建议。'''
}
def get_client(self, cookie_id: str) -> Optional[OpenAI]:
"""获取指定账号的OpenAI客户端"""
if cookie_id not in self.clients:
settings = db_manager.get_ai_reply_settings(cookie_id)
if not settings['ai_enabled']:
logger.warning(f"AI回复未启用 (账号: {cookie_id})")
return None
if not settings['api_key']:
logger.warning(f"AI回复的 API Key 未配置 (账号: {cookie_id})")
return None
try:
self.clients[cookie_id] = OpenAI(
api_key=settings['api_key'],
base_url=settings['base_url'],
timeout=60
)
logger.info(f"为账号 {cookie_id} 创建OpenAI客户端")
except Exception as e:
logger.error(f"创建OpenAI客户端失败 {cookie_id}: {e}")
return None
return self.clients[cookie_id]
def is_ai_enabled(self, cookie_id: str) -> bool:
"""检查指定账号是否启用AI回复"""
settings = db_manager.get_ai_reply_settings(cookie_id)
return settings['ai_enabled']
def detect_intent(self, message: str, cookie_id: str) -> str:
"""检测用户消息意图(带缓存)"""
cached = self._get_cached_intent(cookie_id, message)
if cached:
return cached
client = self.get_client(cookie_id)
if not client:
return 'default'
try:
settings = db_manager.get_ai_reply_settings(cookie_id)
custom_prompts = json.loads(settings['custom_prompts']) if settings['custom_prompts'] else {}
classify_prompt = custom_prompts.get('classify', self.default_prompts['classify'])
response = client.chat.completions.create(
model=settings['model_name'],
messages=[
{"role": "system", "content": classify_prompt},
{"role": "user", "content": message}
],
max_tokens=100,
temperature=0.1
)
raw_content = response.choices[0].message.content
intent = raw_content.strip().lower() if raw_content else 'default'
if intent not in ['price', 'tech', 'refund', 'default']:
intent = 'default'
self._set_cached_intent(cookie_id, message, intent)
return intent
except Exception as e:
logger.error(f"意图检测失败 {cookie_id}: {e}")
return 'default'
def generate_reply(self, message: str, item_info: dict, chat_id: str,
cookie_id: str, user_id: str, item_id: str) -> Optional[str]:
"""生成AI回复(带缓存,带重试)"""
if not self.is_ai_enabled(cookie_id):
return None
# 检查缓存
cached_reply = self._get_cached_reply(cookie_id, chat_id, message)
if cached_reply:
return cached_reply
client = self.get_client(cookie_id)
if not client:
logger.warning(f"生成AI回复失败: 无法获取 OpenAI 客户端 (账号: {cookie_id})")
return None
# 获取设置(重试参数也放在 settings 里)
try:
settings = db_manager.get_ai_reply_settings(cookie_id)
except Exception as e:
logger.error(f"获取AI回复设置失败 {cookie_id}: {e}")
return None
# 读取重试配置
max_retry = 3
retry_interval = 5
# 检测意图
intent = self.detect_intent(message, cookie_id)
logger.info(f"检测到意图: {intent} (账号: {cookie_id})")
# 获取对话历史和议价信息(在重试循环外,只做一次)
context = self.get_conversation_context(chat_id, cookie_id)
bargain_count = self.get_bargain_count(chat_id, cookie_id)
refund_policy = settings.get('refund_policy', 'allow')
# 检查议价轮数限制
if intent == "price":
max_bargain_rounds = settings.get('max_bargain_rounds', 3)
if bargain_count >= max_bargain_rounds:
logger.info(f"议价次数已达上限 ({bargain_count}/{max_bargain_rounds}),拒绝继续议价")
refuse_reply = "抱歉,这个价格已经是最优惠的了,不能再便宜了哦!"
self.save_conversation(chat_id, cookie_id, user_id, item_id, "user", message, intent)
self.save_conversation(chat_id, cookie_id, user_id, item_id, "assistant", refuse_reply, intent)
return refuse_reply
# 构建提示词相关(在重试循环外,只做一次)
custom_prompts = json.loads(settings['custom_prompts']) if settings.get('custom_prompts') else {}
system_prompt = custom_prompts.get(intent, self.default_prompts[intent])
item_desc = f"商品标题: {item_info.get('title', '未知')}\n"
item_desc += f"商品价格: {item_info.get('price', '未知')}元\n"
item_desc += f"商品描述: {item_info.get('desc', '无')}"
context_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in context[-10:]])
max_bargain_rounds = settings.get('max_bargain_rounds', 3)
max_discount_percent = settings.get('max_discount_percent', 10)
max_discount_amount = settings.get('max_discount_amount', 100)
refund_instruction = "" if intent != "refund" else (
"【退款策略】该商品支持退款,请引导用户通过平台申请退款,告知流程和预计时间。"
if refund_policy == "allow"
else "【退款策略】该商品不支持退款,请礼貌说明原因(虚拟商品/已发货/特殊商品等),并表示歉意。"
)
user_prompt = f"""商品信息:
{item_desc}
对话历史:
{context_str}
议价设置:
- 当前议价次数:{bargain_count}
- 最大议价轮数:{max_bargain_rounds}
- 最大优惠百分比:{max_discount_percent}%
- 最大优惠金额:{max_discount_amount}元
{refund_instruction}
用户消息:{message}
请根据以上信息生成回复:"""
# === 带重试的 API 调用 ===
last_error = None
for attempt in range(max_retry):
try:
response = client.chat.completions.create(
model=settings['model_name'],
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
max_tokens=2048,
temperature=0.7
)
raw_reply = response.choices[0].message.content
if not raw_reply:
raise ValueError("AI 返回内容为空")
reply = raw_reply.strip()
# 保存对话记录
self.save_conversation(chat_id, cookie_id, user_id, item_id, "user", message, intent)
self.save_conversation(chat_id, cookie_id, user_id, item_id, "assistant", reply, intent)
# 更新议价次数
if intent == "price":
self.increment_bargain_count(chat_id, cookie_id)
# 写入缓存
self._set_cached_reply(cookie_id, chat_id, message, reply)
logger.info(f"AI回复生成成功 (账号: {cookie_id}): {reply}")
return reply
except Exception as e:
last_error = e
if attempt < max_retry - 1:
logger.warning(f"AI回复生成失败 (第{attempt + 1}/{max_retry}次重试) {cookie_id}: {e}")
time.sleep(retry_interval)
else:
logger.error(f"AI回复生成失败 (已重试{max_retry}次) {cookie_id}: {e}")
return None
def get_conversation_context(self, chat_id: str, cookie_id: str, limit: int = 20) -> List[Dict]:
"""获取对话上下文"""
try:
with db_manager.lock:
cursor = db_manager.conn.cursor()
cursor.execute('''
SELECT role, content FROM ai_conversations
WHERE chat_id = ? AND cookie_id = ?
ORDER BY created_at DESC LIMIT ?
''', (chat_id, cookie_id, limit))
results = cursor.fetchall()
# 反转顺序,使其按时间正序
context = [{"role": row[0], "content": row[1]} for row in reversed(results)]
return context
except Exception as e:
logger.error(f"获取对话上下文失败: {e}")
return []
def save_conversation(self, chat_id: str, cookie_id: str, user_id: str,
item_id: str, role: str, content: str, intent: str = None):
"""保存对话记录"""
try:
with db_manager.lock:
cursor = db_manager.conn.cursor()
cursor.execute('''
INSERT INTO ai_conversations
(cookie_id, chat_id, user_id, item_id, role, content, intent)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (cookie_id, chat_id, user_id, item_id, role, content, intent))
db_manager.conn.commit()
except Exception as e:
logger.error(f"保存对话记录失败: {e}")
def get_bargain_count(self, chat_id: str, cookie_id: str) -> int:
"""获取议价次数"""
try:
with db_manager.lock:
cursor = db_manager.conn.cursor()
cursor.execute('''
SELECT COUNT(*) FROM ai_conversations
WHERE chat_id = ? AND cookie_id = ? AND intent = 'price' AND role = 'user'
''', (chat_id, cookie_id))
result = cursor.fetchone()
return result[0] if result else 0
except Exception as e:
logger.error(f"获取议价次数失败: {e}")
return 0
def increment_bargain_count(self, chat_id: str, cookie_id: str):
"""增加议价次数(通过保存记录自动增加)"""
# 议价次数通过查询price意图的用户消息数量来计算,无需单独操作
pass
def clear_cache(self, cookie_id: str = None):
"""清理AI回复和意图缓存"""
if cookie_id:
prefix = hashlib.md5(f"{cookie_id}|".encode()).hexdigest()[:8]
self._cache = {k: v for k, v in self._cache.items() if not k.startswith(prefix)}
self._intent_cache = {k: v for k, v in self._intent_cache.items() if not k.startswith(prefix)}
logger.info(f"清理账号 {cookie_id} 的AI回复缓存")
else:
self._cache.clear()
self._intent_cache.clear()
logger.info("清理所有AI回复缓存")
def clear_client_cache(self, cookie_id: str = None):
"""清理客户端缓存"""
if cookie_id:
self.clients.pop(cookie_id, None)
logger.info(f"清理账号 {cookie_id} 的客户端缓存")
else:
self.clients.clear()
logger.info("清理所有客户端缓存")
# 全局AI回复引擎实例
ai_reply_engine = AIReplyEngine()
+122
View File
@@ -0,0 +1,122 @@
import os
import yaml
from typing import Dict, Any
class Config:
"""配置管理类
用于加载和管理全局配置文件(global_config.yml)。
支持配置的读取、修改和保存。
"""
_instance = None
_config = {}
def __new__(cls):
if cls._instance is None:
cls._instance = super(Config, cls).__new__(cls)
cls._instance._load_config()
return cls._instance
def _load_config(self):
"""加载配置文件
从global_config.yml文件中加载配置信息。
如果文件不存在则抛出FileNotFoundError异常。
"""
config_path = os.path.join(os.path.dirname(__file__), 'global_config.yml')
if not os.path.exists(config_path):
raise FileNotFoundError(f"配置文件不存在: {config_path}")
with open(config_path, 'r', encoding='utf-8') as f:
self._config = yaml.safe_load(f)
def get(self, key: str, default: Any = None) -> Any:
"""获取配置项
Args:
key: 配置项的键,支持点号分隔的多级键
default: 当配置项不存在时返回的默认值
Returns:
配置项的值或默认值
"""
keys = key.split('.')
value = self._config
for k in keys:
if isinstance(value, dict):
value = value.get(k)
else:
return default
if value is None:
return default
return value
def set(self, key: str, value: Any) -> None:
"""设置配置项
Args:
key: 配置项的键,支持点号分隔的多级键
value: 要设置的值
"""
keys = key.split('.')
config = self._config
for k in keys[:-1]:
if k not in config:
config[k] = {}
config = config[k]
config[keys[-1]] = value
def save(self) -> None:
"""保存配置到文件
将当前配置保存回global_config.yml文件
"""
config_path = os.path.join(os.path.dirname(__file__), 'global_config.yml')
with open(config_path, 'w', encoding='utf-8') as f:
yaml.safe_dump(self._config, f, allow_unicode=True, default_flow_style=False)
@property
def config(self) -> Dict[str, Any]:
"""获取完整配置
Returns:
包含所有配置项的字典
"""
return self._config
# 创建全局配置实例
config = Config()
# 导出常用配置项
COOKIES_STR = config.get('COOKIES.value', '')
COOKIES_LAST_UPDATE = config.get('COOKIES.last_update_time', '')
WEBSOCKET_URL = config.get('WEBSOCKET_URL', 'wss://wss-goofish.dingtalk.com/')
HEARTBEAT_INTERVAL = config.get('HEARTBEAT_INTERVAL', 15)
HEARTBEAT_TIMEOUT = config.get('HEARTBEAT_TIMEOUT', 5)
TOKEN_REFRESH_INTERVAL = config.get('TOKEN_REFRESH_INTERVAL', 36000)
TOKEN_RETRY_INTERVAL = config.get('TOKEN_RETRY_INTERVAL', 1800)
COOKIE_KEEPALIVE_INTERVAL = config.get('COOKIE_KEEPALIVE_INTERVAL', 7200)
MESSAGE_EXPIRE_TIME = config.get('MESSAGE_EXPIRE_TIME', 300000)
API_ENDPOINTS = config.get('API_ENDPOINTS', {})
DEFAULT_HEADERS = config.get('DEFAULT_HEADERS', {})
WEBSOCKET_HEADERS = config.get('WEBSOCKET_HEADERS', {})
APP_CONFIG = config.get('APP_CONFIG', {})
AUTO_REPLY = config.get('AUTO_REPLY', {
'enabled': True,
'default_message': '亲爱的"{send_user_name}" 老板你好!所有宝贝都可以拍,秒发货的哈~不满意的话可以直接申请退款哈~',
'api': {
'enabled': False,
'url': 'http://localhost:8080/xianyu/reply',
'timeout': 10
}
})
MANUAL_MODE = config.get('MANUAL_MODE', {})
LOG_CONFIG = config.get('LOG_CONFIG', {})
_cookies_raw = config.get('COOKIES', [])
if isinstance(_cookies_raw, list):
COOKIES_LIST = _cookies_raw
else:
# 兼容旧格式,仅有 value 字段
val = _cookies_raw.get('value') if isinstance(_cookies_raw, dict) else None
COOKIES_LIST = [{'id': 'default', 'value': val}] if val else []
+325
View File
@@ -0,0 +1,325 @@
from __future__ import annotations
import asyncio
from typing import Dict, List, Tuple, Optional
from loguru import logger
from db_manager import db_manager
__all__ = ["CookieManager", "manager"]
class CookieManager:
"""管理多账号 Cookie 及其对应的 XianyuLive 任务和关键字"""
def __init__(self, loop: asyncio.AbstractEventLoop):
self.loop = loop
self.cookies: Dict[str, str] = {}
self.tasks: Dict[str, asyncio.Task] = {}
self.keywords: Dict[str, List[Tuple[str, str]]] = {}
self.cookie_status: Dict[str, bool] = {} # 账号启用状态
self.auto_confirm_settings: Dict[str, bool] = {} # 自动确认发货设置
self.online_status: Dict[str, bool] = {} # WebSocket 真实在线状态
self.xianyu_instances: Dict[str, object] = {} # XianyuLive 实例缓存
self._load_from_db()
def _load_from_db(self):
"""从数据库加载所有Cookie、关键字和状态"""
try:
# 加载所有Cookie
self.cookies = db_manager.get_all_cookies()
# 加载所有关键字
self.keywords = db_manager.get_all_keywords()
# 加载所有Cookie状态(默认启用)
self.cookie_status = db_manager.get_all_cookie_status()
# 加载所有auto_confirm设置
self.auto_confirm_settings = {}
for cookie_id in self.cookies.keys():
# 为没有状态记录的Cookie设置默认启用状态
if cookie_id not in self.cookie_status:
self.cookie_status[cookie_id] = True
# 加载auto_confirm设置
self.auto_confirm_settings[cookie_id] = db_manager.get_auto_confirm(cookie_id)
# 初始化在线状态为False
self.online_status[cookie_id] = False
logger.info(f"从数据库加载了 {len(self.cookies)} 个Cookie、{len(self.keywords)} 组关键字、{len(self.cookie_status)} 个状态记录和 {len(self.auto_confirm_settings)} 个自动确认设置")
except Exception as e:
logger.error(f"从数据库加载数据失败: {e}")
def reload_from_db(self):
"""重新从数据库加载所有数据(用于备份导入后刷新)"""
logger.info("重新从数据库加载数据...")
old_cookies_count = len(self.cookies)
old_keywords_count = len(self.keywords)
# 重新加载数据
self._load_from_db()
new_cookies_count = len(self.cookies)
new_keywords_count = len(self.keywords)
logger.info(f"数据重新加载完成: Cookie {old_cookies_count} -> {new_cookies_count}, 关键字组 {old_keywords_count} -> {new_keywords_count}")
return True
# ------------------------ 内部协程 ------------------------
async def _run_xianyu(self, cookie_id: str, cookie_value: str, user_id: int = None):
"""在事件循环中启动 XianyuLive.main"""
logger.info(f"【{cookie_id}】_run_xianyu方法开始执行...")
try:
logger.info(f"【{cookie_id}】正在导入XianyuLive...")
from XianyuAutoAsync import XianyuLive # 延迟导入,避免循环
logger.info(f"【{cookie_id}】XianyuLive导入成功")
logger.info(f"【{cookie_id}】开始创建XianyuLive实例...")
logger.info(f"【{cookie_id}】Cookie值长度: {len(cookie_value)}")
live = XianyuLive(cookie_value, cookie_id=cookie_id, user_id=user_id)
self.xianyu_instances[cookie_id] = live
logger.info(f"【{cookie_id}】XianyuLive实例创建成功,开始调用main()...")
await live.main()
except asyncio.CancelledError:
logger.info(f"XianyuLive 任务已取消: {cookie_id}")
except Exception as e:
logger.error(f"XianyuLive 任务异常({cookie_id}): {e}")
import traceback
logger.error(f"详细错误信息: {traceback.format_exc()}")
async def _add_cookie_async(self, cookie_id: str, cookie_value: str, user_id: int = None):
if cookie_id in self.tasks:
raise ValueError("Cookie ID already exists")
self.cookies[cookie_id] = cookie_value
# 数据库操作放到线程池,避免阻塞事件循环导致其他账号心跳超时离线
await asyncio.to_thread(db_manager.save_cookie, cookie_id, cookie_value, user_id)
# 获取实际保存的user_id(如果没有指定,数据库会返回实际的user_id)
actual_user_id = user_id
if actual_user_id is None:
cookie_info = await asyncio.to_thread(db_manager.get_cookie_details, cookie_id)
if cookie_info:
actual_user_id = cookie_info.get('user_id')
task = self.loop.create_task(self._run_xianyu(cookie_id, cookie_value, actual_user_id))
self.tasks[cookie_id] = task
logger.info(f"已启动账号任务: {cookie_id} (用户ID: {actual_user_id})")
async def _remove_cookie_async(self, cookie_id: str):
task = self.tasks.pop(cookie_id, None)
if task:
task.cancel()
self.cookies.pop(cookie_id, None)
self.keywords.pop(cookie_id, None)
self.xianyu_instances.pop(cookie_id, None)
# 数据库操作放到线程池,避免阻塞事件循环
await asyncio.to_thread(db_manager.delete_cookie, cookie_id)
logger.info(f"已移除账号: {cookie_id}")
# ------------------------ 对外线程安全接口 ------------------------
def add_cookie(self, cookie_id: str, cookie_value: str, kw_list: Optional[List[Tuple[str, str]]] = None, user_id: int = None):
"""线程安全新增 Cookie 并启动任务"""
if kw_list is not None:
self.keywords[cookie_id] = kw_list
else:
self.keywords.setdefault(cookie_id, [])
try:
current_loop = asyncio.get_running_loop()
except RuntimeError:
current_loop = None
if current_loop and current_loop == self.loop:
# 同一事件循环中,直接调度
return self.loop.create_task(self._add_cookie_async(cookie_id, cookie_value, user_id))
else:
fut = asyncio.run_coroutine_threadsafe(self._add_cookie_async(cookie_id, cookie_value, user_id), self.loop)
return fut.result()
def remove_cookie(self, cookie_id: str):
try:
current_loop = asyncio.get_running_loop()
except RuntimeError:
current_loop = None
if current_loop and current_loop == self.loop:
return self.loop.create_task(self._remove_cookie_async(cookie_id))
else:
fut = asyncio.run_coroutine_threadsafe(self._remove_cookie_async(cookie_id), self.loop)
return fut.result()
# 更新 Cookie 值
def update_cookie(self, cookie_id: str, new_value: str):
"""替换指定账号的 Cookie 并重启任务"""
async def _update():
# 获取原有的user_id和关键词
original_user_id = None
original_keywords = []
original_status = True
cookie_info = await asyncio.to_thread(db_manager.get_cookie_details, cookie_id)
if cookie_info:
original_user_id = cookie_info.get('user_id')
# 保存原有的关键词和状态
if cookie_id in self.keywords:
original_keywords = self.keywords[cookie_id].copy()
if cookie_id in self.cookie_status:
original_status = self.cookie_status[cookie_id]
# 先移除任务(但不删除数据库记录)
task = self.tasks.pop(cookie_id, None)
if task:
task.cancel()
# 更新Cookie值(保持原有user_id,不删除关键词)
self.cookies[cookie_id] = new_value
await asyncio.to_thread(db_manager.save_cookie, cookie_id, new_value, original_user_id)
# 恢复关键词和状态
self.keywords[cookie_id] = original_keywords
self.cookie_status[cookie_id] = original_status
# 重新启动任务
task = self.loop.create_task(self._run_xianyu(cookie_id, new_value, original_user_id))
self.tasks[cookie_id] = task
logger.info(f"已更新Cookie并重启任务: {cookie_id} (用户ID: {original_user_id}, 关键词: {len(original_keywords)}条)")
try:
current_loop = asyncio.get_running_loop()
except RuntimeError:
current_loop = None
if current_loop and current_loop == self.loop:
return self.loop.create_task(_update())
else:
fut = asyncio.run_coroutine_threadsafe(_update(), self.loop)
return fut.result()
def update_keywords(self, cookie_id: str, kw_list: List[Tuple[str, str]]):
"""线程安全更新关键字"""
self.keywords[cookie_id] = kw_list
# 保存到数据库
db_manager.save_keywords(cookie_id, kw_list)
logger.info(f"更新关键字: {cookie_id} -> {len(kw_list)} 条")
# 查询接口
def list_cookies(self):
return list(self.cookies.keys())
def get_keywords(self, cookie_id: str) -> List[Tuple[str, str]]:
return self.keywords.get(cookie_id, [])
def update_cookie_status(self, cookie_id: str, enabled: bool):
"""更新Cookie的启用/禁用状态"""
if cookie_id not in self.cookies:
raise ValueError(f"Cookie ID {cookie_id} 不存在")
old_status = self.cookie_status.get(cookie_id, True)
self.cookie_status[cookie_id] = enabled
# 保存到数据库
db_manager.save_cookie_status(cookie_id, enabled)
logger.info(f"更新Cookie状态: {cookie_id} -> {'启用' if enabled else '禁用'}")
# 如果状态发生变化,需要启动或停止任务
if old_status != enabled:
if enabled:
# 启用账号:启动任务
self._start_cookie_task(cookie_id)
else:
# 禁用账号:停止任务
self._stop_cookie_task(cookie_id)
def get_cookie_status(self, cookie_id: str) -> bool:
"""获取Cookie的启用状态"""
return self.cookie_status.get(cookie_id, True) # 默认启用
def get_enabled_cookies(self) -> Dict[str, str]:
"""获取所有启用的Cookie"""
return {cid: value for cid, value in self.cookies.items()
if self.cookie_status.get(cid, True)}
def _start_cookie_task(self, cookie_id: str):
"""启动指定Cookie的任务"""
if cookie_id in self.tasks:
logger.warning(f"Cookie任务已存在,跳过启动: {cookie_id}")
return
cookie_value = self.cookies.get(cookie_id)
if not cookie_value:
logger.error(f"Cookie值不存在,无法启动任务: {cookie_id}")
return
try:
# 获取Cookie对应的user_id
cookie_info = db_manager.get_cookie_details(cookie_id)
user_id = cookie_info.get('user_id') if cookie_info else None
# 使用异步方式启动任务(直接调用_run_xianyu,跳过重复的数据库操作)
async def _start():
task = self.loop.create_task(self._run_xianyu(cookie_id, cookie_value, user_id))
self.tasks[cookie_id] = task
if hasattr(self.loop, 'is_running') and self.loop.is_running():
fut = asyncio.run_coroutine_threadsafe(_start(), self.loop)
fut.result(timeout=5)
else:
task = self.loop.create_task(self._run_xianyu(cookie_id, cookie_value, user_id))
self.tasks[cookie_id] = task
logger.info(f"成功启动Cookie任务: {cookie_id}")
except Exception as e:
logger.error(f"启动Cookie任务失败: {cookie_id}, {e}")
def _stop_cookie_task(self, cookie_id: str):
"""停止指定Cookie的任务"""
if cookie_id not in self.tasks:
logger.warning(f"Cookie任务不存在,跳过停止: {cookie_id}")
return
try:
task = self.tasks[cookie_id]
if not task.done():
task.cancel()
logger.info(f"已取消Cookie任务: {cookie_id}")
del self.tasks[cookie_id]
logger.info(f"成功停止Cookie任务: {cookie_id}")
except Exception as e:
logger.error(f"停止Cookie任务失败: {cookie_id}, {e}")
def update_auto_confirm_setting(self, cookie_id: str, auto_confirm: bool):
"""实时更新账号的自动确认发货设置"""
try:
# 更新内存中的设置
self.auto_confirm_settings[cookie_id] = auto_confirm
logger.info(f"更新账号 {cookie_id} 自动确认发货设置: {'开启' if auto_confirm else '关闭'}")
# 如果账号正在运行,通知XianyuLive实例更新设置
if cookie_id in self.tasks and not self.tasks[cookie_id].done():
# 这里可以通过某种方式通知正在运行的XianyuLive实例
# 由于XianyuLive会从数据库读取设置,所以数据库已经更新就足够了
logger.info(f"账号 {cookie_id} 正在运行,自动确认发货设置已实时生效")
except Exception as e:
logger.error(f"更新自动确认发货设置失败: {cookie_id}, {e}")
def update_online_status(self, cookie_id: str, is_online: bool):
"""更新指定Cookie的WebSocket在线状态(由XianyuLive调用)"""
self.online_status[cookie_id] = is_online
status_text = "在线" if is_online else "离线"
logger.debug(f"更新在线状态: {cookie_id} -> {status_text}")
def get_online_status(self, cookie_id: str) -> Optional[bool]:
"""获取指定Cookie的在线状态,None表示未知"""
return self.online_status.get(cookie_id)
def get_all_online_status(self) -> Dict[str, bool]:
"""获取所有Cookie的在线状态"""
return dict(self.online_status)
def get_auto_confirm_setting(self, cookie_id: str) -> bool:
"""获取账号的自动确认发货设置"""
return self.auto_confirm_settings.get(cookie_id, True) # 默认开启
def get_xianyu(self, cookie_id: str):
"""获取指定账号的XianyuLive实例"""
return self.xianyu_instances.get(cookie_id)
# 在 Start.py 中会把此变量赋值为具体实例
manager: Optional[CookieManager] = None
+5202
View File
File diff suppressed because it is too large. Load diff
+105
View File
@@ -0,0 +1,105 @@
services:
xianyu-app:
build:
context: .
dockerfile: Dockerfile-cn
image: xianyu-auto-reply:latest
container_name: xianyu-auto-reply
restart: unless-stopped
# 使用root用户避免权限问题
user: "0:0"
ports:
- "${WEB_PORT:-8080}:8080"
volumes:
# 数据持久化
- ./data:/app/data:rw
- ./logs:/app/logs:rw
- ./global_config.yml:/app/global_config.yml:ro
# 可选:如果需要自定义配置
# - ./custom_config.yml:/app/global_config.yml:ro
# 可选:备份目录
- ./backups:/app/backups:rw
environment:
- PYTHONUNBUFFERED=${PYTHONUNBUFFERED:-1}
- PYTHONDONTWRITEBYTECODE=${PYTHONDONTWRITEBYTECODE:-1}
- TZ=${TZ:-Asia/Shanghai}
- DB_PATH=${DB_PATH:-/app/data/xianyu_data.db}
- LOG_LEVEL=${LOG_LEVEL:-INFO}
- DEBUG=${DEBUG:-false}
- RELOAD=${RELOAD:-false}
# SQL日志配置(默认启用,可通过环境变量覆盖)
- SQL_LOG_ENABLED=${SQL_LOG_ENABLED:-true}
- SQL_LOG_LEVEL=${SQL_LOG_LEVEL:-INFO}
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin123}
- JWT_SECRET_KEY=${JWT_SECRET_KEY:-default-secret-key}
- SESSION_TIMEOUT=${SESSION_TIMEOUT:-3600}
# 多用户系统配置
- MULTIUSER_ENABLED=${MULTIUSER_ENABLED:-true}
- USER_REGISTRATION_ENABLED=${USER_REGISTRATION_ENABLED:-true}
- EMAIL_VERIFICATION_ENABLED=${EMAIL_VERIFICATION_ENABLED:-true}
- CAPTCHA_ENABLED=${CAPTCHA_ENABLED:-true}
- TOKEN_EXPIRE_TIME=${TOKEN_EXPIRE_TIME:-86400}
- AUTO_REPLY_ENABLED=${AUTO_REPLY_ENABLED:-true}
- AUTO_DELIVERY_ENABLED=${AUTO_DELIVERY_ENABLED:-true}
- AUTO_DELIVERY_TIMEOUT=${AUTO_DELIVERY_TIMEOUT:-30}
- API_CARD_TIMEOUT=${API_CARD_TIMEOUT:-10}
- BATCH_DATA_LOCK_TIMEOUT=${BATCH_DATA_LOCK_TIMEOUT:-5}
# AI回复相关配置
- AI_REPLY_ENABLED=${AI_REPLY_ENABLED:-false}
- DEFAULT_AI_MODEL=${DEFAULT_AI_MODEL:-qwen-plus}
- DEFAULT_AI_BASE_URL=${DEFAULT_AI_BASE_URL:-https://dashscope.aliyuncs.com/compatible-mode/v1}
- AI_REQUEST_TIMEOUT=${AI_REQUEST_TIMEOUT:-30}
- AI_MAX_TOKENS=${AI_MAX_TOKENS:-100}
- WEBSOCKET_URL=${WEBSOCKET_URL:-wss://wss-goofish.dingtalk.com/}
- HEARTBEAT_INTERVAL=${HEARTBEAT_INTERVAL:-15}
- HEARTBEAT_TIMEOUT=${HEARTBEAT_TIMEOUT:-5}
- TOKEN_REFRESH_INTERVAL=${TOKEN_REFRESH_INTERVAL:-3600}
- TOKEN_RETRY_INTERVAL=${TOKEN_RETRY_INTERVAL:-300}
- MESSAGE_EXPIRE_TIME=${MESSAGE_EXPIRE_TIME:-300000}
networks:
- xianyu-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# 资源限制
deploy:
resources:
limits:
memory: ${MEMORY_LIMIT:-512}M
cpus: '${CPU_LIMIT:-0.5}'
reservations:
memory: ${MEMORY_RESERVATION:-256}M
cpus: '${CPU_RESERVATION:-0.25}'
# 可选:添加Nginx反向代理
nginx:
image: nginx:alpine
container_name: xianyu-nginx
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
depends_on:
- xianyu-app
networks:
- xianyu-network
profiles:
- with-nginx
networks:
xianyu-network:
driver: bridge
volumes:
xianyu-data:
driver: local
xianyu-logs:
driver: local
+105
View File
@@ -0,0 +1,105 @@
services:
xianyu-app:
build:
context: .
dockerfile: Dockerfile
image: xianyu-auto-reply:latest
container_name: xianyu-auto-reply
restart: unless-stopped
# 使用root用户避免权限问题
user: "0:0"
ports:
- "${WEB_PORT:-8080}:8080"
volumes:
# 数据持久化
- ./data:/app/data:rw
- ./logs:/app/logs:rw
- ./global_config.yml:/app/global_config.yml:ro
# 可选:如果需要自定义配置
# - ./custom_config.yml:/app/global_config.yml:ro
# 可选:备份目录
- ./backups:/app/backups:rw
environment:
- PYTHONUNBUFFERED=${PYTHONUNBUFFERED:-1}
- PYTHONDONTWRITEBYTECODE=${PYTHONDONTWRITEBYTECODE:-1}
- TZ=${TZ:-Asia/Shanghai}
- DB_PATH=${DB_PATH:-/app/data/xianyu_data.db}
- LOG_LEVEL=${LOG_LEVEL:-INFO}
- DEBUG=${DEBUG:-false}
- RELOAD=${RELOAD:-false}
# SQL日志配置(默认启用,可通过环境变量覆盖)
- SQL_LOG_ENABLED=${SQL_LOG_ENABLED:-true}
- SQL_LOG_LEVEL=${SQL_LOG_LEVEL:-INFO}
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin123}
- JWT_SECRET_KEY=${JWT_SECRET_KEY:-default-secret-key}
- SESSION_TIMEOUT=${SESSION_TIMEOUT:-3600}
# 多用户系统配置
- MULTIUSER_ENABLED=${MULTIUSER_ENABLED:-true}
- USER_REGISTRATION_ENABLED=${USER_REGISTRATION_ENABLED:-true}
- EMAIL_VERIFICATION_ENABLED=${EMAIL_VERIFICATION_ENABLED:-true}
- CAPTCHA_ENABLED=${CAPTCHA_ENABLED:-true}
- TOKEN_EXPIRE_TIME=${TOKEN_EXPIRE_TIME:-86400}
- AUTO_REPLY_ENABLED=${AUTO_REPLY_ENABLED:-true}
- AUTO_DELIVERY_ENABLED=${AUTO_DELIVERY_ENABLED:-true}
- AUTO_DELIVERY_TIMEOUT=${AUTO_DELIVERY_TIMEOUT:-30}
- API_CARD_TIMEOUT=${API_CARD_TIMEOUT:-10}
- BATCH_DATA_LOCK_TIMEOUT=${BATCH_DATA_LOCK_TIMEOUT:-5}
# AI回复相关配置
- AI_REPLY_ENABLED=${AI_REPLY_ENABLED:-false}
- DEFAULT_AI_MODEL=${DEFAULT_AI_MODEL:-qwen-plus}
- DEFAULT_AI_BASE_URL=${DEFAULT_AI_BASE_URL:-https://dashscope.aliyuncs.com/compatible-mode/v1}
- AI_REQUEST_TIMEOUT=${AI_REQUEST_TIMEOUT:-30}
- AI_MAX_TOKENS=${AI_MAX_TOKENS:-100}
- WEBSOCKET_URL=${WEBSOCKET_URL:-wss://wss-goofish.dingtalk.com/}
- HEARTBEAT_INTERVAL=${HEARTBEAT_INTERVAL:-15}
- HEARTBEAT_TIMEOUT=${HEARTBEAT_TIMEOUT:-5}
- TOKEN_REFRESH_INTERVAL=${TOKEN_REFRESH_INTERVAL:-3600}
- TOKEN_RETRY_INTERVAL=${TOKEN_RETRY_INTERVAL:-300}
- MESSAGE_EXPIRE_TIME=${MESSAGE_EXPIRE_TIME:-300000}
networks:
- xianyu-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# 资源限制
deploy:
resources:
limits:
memory: ${MEMORY_LIMIT:-512}M
cpus: '${CPU_LIMIT:-0.5}'
reservations:
memory: ${MEMORY_RESERVATION:-256}M
cpus: '${CPU_RESERVATION:-0.25}'
# 可选:添加Nginx反向代理
nginx:
image: nginx:alpine
container_name: xianyu-nginx
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
depends_on:
- xianyu-app
networks:
- xianyu-network
profiles:
- with-nginx
networks:
xianyu-network:
driver: bridge
volumes:
xianyu-data:
driver: local
xianyu-logs:
driver: local
+228
View File
@@ -0,0 +1,228 @@
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
REM 闲鱼自动回复系统 Docker 部署脚本 (Windows版本)
REM 支持快速部署和管理
title 闲鱼自动回复系统 Docker 部署
REM 项目配置
set PROJECT_NAME=xianyu-auto-reply
set COMPOSE_FILE=docker-compose.yml
REM 颜色定义(Windows CMD不支持ANSI颜色,使用echo代替)
set "INFO_PREFIX=[INFO]"
set "SUCCESS_PREFIX=[SUCCESS]"
set "WARNING_PREFIX=[WARNING]"
set "ERROR_PREFIX=[ERROR]"
REM 检查依赖
echo %INFO_PREFIX% 检查系统依赖...
where docker >nul 2>&1
if %errorlevel% neq 0 (
echo %ERROR_PREFIX% Docker 未安装,请先安装 Docker Desktop
echo 下载地址: https://www.docker.com/products/docker-desktop
pause
exit /b 1
)
where docker-compose >nul 2>&1
if %errorlevel% neq 0 (
echo %ERROR_PREFIX% Docker Compose 未安装,请先安装 Docker Compose
pause
exit /b 1
)
echo %SUCCESS_PREFIX% 系统依赖检查通过
REM 初始化配置
echo %INFO_PREFIX% 初始化配置文件...
REM 检查关键文件
if not exist "entrypoint.sh" (
echo %ERROR_PREFIX% entrypoint.sh 文件不存在,Docker容器将无法启动
echo %INFO_PREFIX% 请确保项目文件完整
pause
exit /b 1
) else (
echo %SUCCESS_PREFIX% entrypoint.sh 文件已存在
)
if not exist "global_config.yml" (
echo %ERROR_PREFIX% global_config.yml 配置文件不存在
echo %INFO_PREFIX% 请确保配置文件存在
pause
exit /b 1
) else (
echo %SUCCESS_PREFIX% global_config.yml 配置文件已存在
)
REM 创建必要的目录
if not exist "data" mkdir data
if not exist "logs" mkdir logs
if not exist "backups" mkdir backups
if not exist "static\uploads\images" mkdir static\uploads\images
echo %SUCCESS_PREFIX% 已创建必要的目录
REM 处理命令行参数
if "%1"=="" goto quick_deploy
if "%1"=="help" goto show_help
if "%1"=="start" goto start_services
if "%1"=="stop" goto stop_services
if "%1"=="restart" goto restart_services
if "%1"=="status" goto show_status
if "%1"=="logs" goto show_logs
if "%1"=="build" goto build_image
if "%1"=="cleanup" goto cleanup
goto unknown_command
:quick_deploy
echo %INFO_PREFIX% 快速部署模式
goto build_and_start
:build_image
echo %INFO_PREFIX% 构建 Docker 镜像...
set /p use_cn="是否使用国内镜像源?(y/n): "
if /i "!use_cn!"=="y" (
docker-compose -f docker-compose-cn.yml build --no-cache
) else (
docker-compose build --no-cache
)
if %errorlevel% neq 0 (
echo %ERROR_PREFIX% 镜像构建失败
pause
exit /b 1
)
echo %SUCCESS_PREFIX% 镜像构建完成
goto end
:build_and_start
call :build_image
if %errorlevel% neq 0 exit /b 1
:start_services
echo %INFO_PREFIX% 启动服务...
docker-compose up -d
if %errorlevel% neq 0 (
echo %ERROR_PREFIX% 服务启动失败
docker-compose logs
pause
exit /b 1
)
echo %SUCCESS_PREFIX% 服务启动完成
REM 等待服务就绪
echo %INFO_PREFIX% 等待服务就绪...
timeout /t 10 /nobreak >nul
REM 检查服务状态
docker-compose ps | findstr "Up" >nul
if %errorlevel% equ 0 (
echo %SUCCESS_PREFIX% 服务运行正常
call :show_access_info
) else (
echo %ERROR_PREFIX% 服务启动失败
docker-compose logs
pause
exit /b 1
)
goto end
:stop_services
echo %INFO_PREFIX% 停止服务...
docker-compose down
echo %SUCCESS_PREFIX% 服务已停止
goto end
:restart_services
echo %INFO_PREFIX% 重启服务...
docker-compose restart
echo %SUCCESS_PREFIX% 服务已重启
goto end
:show_status
echo %INFO_PREFIX% 服务状态:
docker-compose ps
echo.
echo %INFO_PREFIX% 资源使用:
for /f "tokens=*" %%i in ('docker-compose ps -q') do (
docker stats --no-stream %%i
)
goto end
:show_logs
if "%2"=="" (
docker-compose logs -f
) else (
docker-compose logs -f %2
)
goto end
:cleanup
echo %WARNING_PREFIX% 这将删除所有容器、镜像和数据,确定要继续吗?
set /p confirm="请输入 y 确认: "
if /i "!confirm!"=="y" (
echo %INFO_PREFIX% 清理环境...
docker-compose down -v --rmi all
rmdir /s /q data logs backups 2>nul
echo %SUCCESS_PREFIX% 环境清理完成
) else (
echo %INFO_PREFIX% 取消清理操作
)
goto end
:show_access_info
echo.
echo %SUCCESS_PREFIX% 🎉 部署完成!
echo.
echo 📱 访问地址:
echo HTTP: http://localhost:8080
echo.
echo 🔐 默认登录信息:
echo 用户名: admin
echo 密码: admin123
echo.
echo 📊 管理命令:
echo 查看状态: %~nx0 status
echo 查看日志: %~nx0 logs
echo 重启服务: %~nx0 restart
echo 停止服务: %~nx0 stop
echo.
goto :eof
:show_help
echo 闲鱼自动回复系统 Docker 部署脚本 (Windows版本)
echo.
echo 用法: %~nx0 [命令]
echo.
echo 命令:
echo start 启动服务
echo stop 停止服务
echo restart 重启服务
echo status 查看服务状态
echo logs 查看日志
echo build 构建镜像
echo cleanup 清理环境
echo help 显示帮助信息
echo.
echo 示例:
echo %~nx0 # 快速部署
echo %~nx0 start # 启动服务
echo %~nx0 logs # 查看日志
echo.
goto end
:unknown_command
echo %ERROR_PREFIX% 未知命令: %1
call :show_help
exit /b 1
:end
if "%1"=="" (
echo.
echo 按任意键退出...
pause >nul
)
+360
View File
@@ -0,0 +1,360 @@
#!/bin/bash
# 闲鱼自动回复系统 Docker 部署脚本
# 支持快速部署和管理
set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 项目配置
PROJECT_NAME="xianyu-auto-reply"
COMPOSE_FILE="docker-compose.yml"
# 打印带颜色的消息
print_info() {
echo -e "${BLUE}ℹ️ $1${NC}"
}
print_success() {
echo -e "${GREEN}✅ $1${NC}"
}
print_warning() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
print_error() {
echo -e "${RED}❌ $1${NC}"
}
# 检查依赖
check_dependencies() {
print_info "检查系统依赖..."
if ! command -v docker &> /dev/null; then
print_error "Docker 未安装,请先安装 Docker"
exit 1
fi
if ! command -v docker-compose &> /dev/null; then
print_error "Docker Compose 未安装,请先安装 Docker Compose"
exit 1
fi
print_success "系统依赖检查通过"
}
# 初始化配置
init_config() {
print_info "初始化配置文件..."
# 检查关键文件
if [ ! -f "entrypoint.sh" ]; then
print_error "entrypoint.sh 文件不存在,Docker容器将无法启动"
print_info "请确保项目文件完整"
exit 1
else
print_success "entrypoint.sh 文件已存在"
fi
if [ ! -f "global_config.yml" ]; then
print_error "global_config.yml 配置文件不存在"
print_info "请确保配置文件存在"
exit 1
else
print_success "global_config.yml 配置文件已存在"
fi
# 创建必要的目录
mkdir -p data logs backups static/uploads/images
print_success "已创建必要的目录"
}
# 构建镜像
build_image() {
print_info "构建 Docker 镜像..."
echo "是否需要使用国内镜像(y/n): " && read iscn
if [[ $iscn == "y" ]]; then
docker-compose -f docker-compose-cn.yml build --no-cache
else
docker-compose build --no-cache
fi
print_success "镜像构建完成"
}
# 启动服务
start_services() {
local profile=""
if [ "$1" = "with-nginx" ]; then
profile="--profile with-nginx"
print_info "启动服务(包含 Nginx)..."
else
print_info "启动基础服务..."
fi
docker-compose $profile up -d
print_success "服务启动完成"
# 等待服务就绪
print_info "等待服务就绪..."
sleep 10
# 检查服务状态
if docker-compose ps | grep -q "Up"; then
print_success "服务运行正常"
show_access_info "$1"
else
print_error "服务启动失败"
docker-compose logs
exit 1
fi
}
# 停止服务
stop_services() {
print_info "停止服务..."
docker-compose down
print_success "服务已停止"
}
# 重启服务
restart_services() {
print_info "重启服务..."
docker-compose restart
print_success "服务已重启"
}
# 查看日志
show_logs() {
local service="$1"
if [ -z "$service" ]; then
docker-compose logs -f
else
docker-compose logs -f "$service"
fi
}
# 查看状态
show_status() {
print_info "服务状态:"
docker-compose ps
print_info "资源使用:"
docker stats --no-stream $(docker-compose ps -q)
}
# 显示访问信息
show_access_info() {
local with_nginx="$1"
echo ""
print_success "🎉 部署完成!"
echo ""
if [ "$with_nginx" = "with-nginx" ]; then
echo "📱 访问地址:"
echo " HTTP: http://localhost"
echo " HTTPS: https://localhost (如果配置了SSL)"
else
echo "📱 访问地址:"
echo " HTTP: http://localhost:8080"
fi
echo ""
echo "🔐 默认登录信息:"
echo " 用户名: admin"
echo " 密码: admin123"
echo ""
echo "📊 管理命令:"
echo " 查看状态: $0 status"
echo " 查看日志: $0 logs"
echo " 重启服务: $0 restart"
echo " 停止服务: $0 stop"
echo ""
}
# 健康检查
health_check() {
print_info "执行健康检查..."
local url="http://localhost:8080/health"
local max_attempts=30
local attempt=1
while [ $attempt -le $max_attempts ]; do
if curl -f -s "$url" > /dev/null 2>&1; then
print_success "健康检查通过"
return 0
fi
print_info "等待服务就绪... ($attempt/$max_attempts)"
sleep 2
((attempt++))
done
print_error "健康检查失败"
return 1
}
# 备份数据
backup_data() {
print_info "备份数据..."
local backup_dir="backups/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir"
# 备份数据库
if [ -f "data/xianyu_data.db" ]; then
cp data/xianyu_data.db "$backup_dir/"
print_success "数据库备份完成"
fi
# 备份配置
cp "$ENV_FILE" "$backup_dir/"
cp global_config.yml "$backup_dir/" 2>/dev/null || true
print_success "数据备份完成: $backup_dir"
}
# 更新部署
update_deployment() {
print_info "更新部署..."
# 备份数据
backup_data
# 停止服务
stop_services
# 拉取最新代码(如果是git仓库)
if [ -d ".git" ]; then
print_info "拉取最新代码..."
git pull
fi
# 重新构建
build_image
# 启动服务
start_services
print_success "更新完成"
}
# 清理环境
cleanup() {
print_warning "这将删除所有容器、镜像和数据,确定要继续吗?(y/N)"
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
print_info "清理环境..."
# 停止并删除容器
docker-compose down -v --rmi all
# 删除数据目录
rm -rf data logs backups
print_success "环境清理完成"
else
print_info "取消清理操作"
fi
}
# 显示帮助信息
show_help() {
echo "闲鱼自动回复系统 Docker 部署脚本"
echo ""
echo "用法: $0 [命令] [选项]"
echo ""
echo "命令:"
echo " init 初始化配置文件"
echo " build 构建 Docker 镜像"
echo " start [with-nginx] 启动服务(可选包含 Nginx)"
echo " stop 停止服务"
echo " restart 重启服务"
echo " status 查看服务状态"
echo " logs [service] 查看日志"
echo " health 健康检查"
echo " backup 备份数据"
echo " update 更新部署"
echo " cleanup 清理环境"
echo " help 显示帮助信息"
echo ""
echo "示例:"
echo " $0 init # 初始化配置"
echo " $0 start # 启动基础服务"
echo " $0 start with-nginx # 启动包含 Nginx 的服务"
echo " $0 logs xianyu-app # 查看应用日志"
echo ""
}
# 主函数
main() {
case "$1" in
"init")
check_dependencies
init_config
;;
"build")
check_dependencies
build_image
;;
"start")
check_dependencies
init_config
build_image
start_services "$2"
;;
"stop")
stop_services
;;
"restart")
restart_services
;;
"status")
show_status
;;
"logs")
show_logs "$2"
;;
"health")
health_check
;;
"backup")
backup_data
;;
"update")
check_dependencies
update_deployment
;;
"cleanup")
cleanup
;;
"help"|"--help"|"-h")
show_help
;;
"")
print_info "快速部署模式"
check_dependencies
init_config
build_image
start_services
;;
*)
print_error "未知命令: $1"
show_help
exit 1
;;
esac
}
# 执行主函数
main "$@"
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
set -e
echo "🚀 启动闲鱼自动回复系统..."
echo "📊 数据库将在应用启动时自动初始化..."
echo "🎯 启动主应用..."
# 确保数据目录存在
mkdir -p /app/data /app/logs /app/backups /app/static/uploads/images
# 设置目录权限
chmod 777 /app/data /app/logs /app/backups /app/static/uploads /app/static/uploads/images
# 启动主应用
exec python Start.py
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""
基于文件监控的日志收集器
"""
import os
import re
import time
import threading
from collections import deque
from datetime import datetime
from typing import List, Dict, Optional
from pathlib import Path
class FileLogCollector:
"""基于文件监控的日志收集器"""
def __init__(self, max_logs: int = 2000):
self.max_logs = max_logs
self.logs = deque(maxlen=max_logs)
self.lock = threading.Lock()
# 日志文件路径
self.log_file = None
self.last_position = 0
# 启动文件监控
self.setup_file_monitoring()
def setup_file_monitoring(self):
"""设置文件监控"""
# 查找日志文件
possible_files = [
"xianyu.log",
"app.log",
"system.log",
"logs/xianyu.log",
"logs/app.log"
]
for file_path in possible_files:
if os.path.exists(file_path):
self.log_file = file_path
break
if not self.log_file:
# 如果没有找到现有文件,创建一个新的
self.log_file = "realtime.log"
# 设置loguru输出到文件
self.setup_loguru_file_output()
# 启动文件监控线程
self.monitor_thread = threading.Thread(target=self.monitor_file, daemon=True)
self.monitor_thread.start()
def setup_loguru_file_output(self):
"""设置loguru输出到文件"""
try:
from loguru import logger
# 添加文件输出
logger.add(
self.log_file,
format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {name}:{function}:{line} - {message}",
level="DEBUG",
rotation="10 MB",
retention="7 days",
enqueue=False, # 改为False,避免队列延迟
buffering=1 # 行缓冲,立即写入
)
logger.info("文件日志收集器已启动")
except ImportError:
pass
def monitor_file(self):
"""监控日志文件变化"""
while True:
try:
if os.path.exists(self.log_file):
# 获取文件大小
file_size = os.path.getsize(self.log_file)
if file_size > self.last_position:
# 读取新增内容
with open(self.log_file, 'r', encoding='utf-8') as f:
f.seek(self.last_position)
new_lines = f.readlines()
self.last_position = f.tell()
# 解析新增的日志行
for line in new_lines:
self.parse_log_line(line.strip())
time.sleep(0.5) # 每0.5秒检查一次
except Exception as e:
time.sleep(1) # 出错时等待1秒
def parse_log_line(self, line: str):
"""解析日志行"""
if not line:
return
try:
# 解析loguru格式的日志
# 格式: 2025-07-23 15:46:03.430 | INFO | __main__:debug_collector:70 - 消息
pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}) \| (\w+) \| ([^:]+):([^:]+):(\d+) - (.*)'
match = re.match(pattern, line)
if match:
timestamp_str, level, source, function, line_num, message = match.groups()
# 转换时间格式
try:
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S.%f')
except:
timestamp = datetime.now()
log_entry = {
"timestamp": timestamp.isoformat(),
"level": level,
"source": source,
"function": function,
"line": int(line_num),
"message": message
}
with self.lock:
self.logs.append(log_entry)
except Exception as e:
# 如果解析失败,作为普通消息处理
log_entry = {
"timestamp": datetime.now().isoformat(),
"level": "INFO",
"source": "system",
"function": "unknown",
"line": 0,
"message": line
}
with self.lock:
self.logs.append(log_entry)
def get_logs(self, lines: int = 200, level_filter: str = None, source_filter: str = None) -> List[Dict]:
"""获取日志记录"""
with self.lock:
logs_list = list(self.logs)
# 应用过滤器
if level_filter:
logs_list = [log for log in logs_list if log['level'] == level_filter]
if source_filter:
logs_list = [log for log in logs_list if source_filter.lower() in log['source'].lower()]
# 返回最后N行
return logs_list[-lines:] if len(logs_list) > lines else logs_list
def clear_logs(self):
"""清空日志"""
with self.lock:
self.logs.clear()
def get_stats(self) -> Dict:
"""获取日志统计信息"""
with self.lock:
total_logs = len(self.logs)
# 统计各级别日志数量
level_counts = {}
source_counts = {}
for log in self.logs:
level = log['level']
source = log['source']
level_counts[level] = level_counts.get(level, 0) + 1
source_counts[source] = source_counts.get(source, 0) + 1
return {
"total_logs": total_logs,
"level_counts": level_counts,
"source_counts": source_counts,
"max_capacity": self.max_logs,
"log_file": self.log_file
}
# 全局文件日志收集器实例
_file_collector = None
_file_collector_lock = threading.Lock()
def get_file_log_collector() -> FileLogCollector:
"""获取全局文件日志收集器实例"""
global _file_collector
if _file_collector is None:
with _file_collector_lock:
if _file_collector is None:
_file_collector = FileLogCollector(max_logs=2000)
return _file_collector
def setup_file_logging():
"""设置文件日志系统"""
collector = get_file_log_collector()
return collector
if __name__ == "__main__":
# 测试文件日志收集器
collector = setup_file_logging()
# 生成一些测试日志
from loguru import logger
logger.info("文件日志收集器测试开始")
logger.debug("这是调试信息")
logger.warning("这是警告信息")
logger.error("这是错误信息")
logger.info("文件日志收集器测试结束")
# 等待文件写入和监控
time.sleep(2)
# 获取日志
logs = collector.get_logs(10)
print(f"收集到 {len(logs)} 条日志:")
for log in logs:
print(f" [{log['level']}] {log['source']}: {log['message']}")
# 获取统计信息
stats = collector.get_stats()
print(f"\n统计信息: {stats}")
+89
View File
@@ -0,0 +1,89 @@
API_ENDPOINTS:
login_check: https://passport.goofish.com/newlogin/hasLogin.do
message_headinfo: https://h5api.m.goofish.com/h5/mtop.idle.trade.pc.message.headinfo/1.0/
token: https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/
APP_CONFIG:
api_version: '1.0'
app_key: 444e9908a51d1cb236a27862abc769c9
app_version: '1.0'
platform: web
AUTO_REPLY:
api:
enabled: false # 禁用API回复,使用AI回复或关键词回复
host: 0.0.0.0 # 绑定所有网络接口,支持IP访问
port: 8080 # Web服务端口
timeout: 10
url: http://localhost:8080/xianyu/reply # 修复URL地址
default_message: 亲爱的"{send_user_name}" 老板你好!所有宝贝都可以拍,秒发货的哈~不满意的话可以直接申请退款哈~
enabled: true
max_retry: 3
retry_interval: 5
ITEM_DETAIL:
auto_fetch:
enabled: true # 是否启用自动获取商品详情
api_url: https://selfapi.zhinianboke.com/api/getItemDetail # 外部API地址
timeout: 30 # 请求超时时间(秒)
max_concurrent: 3 # 最大并发请求数
retry_delay: 0.5 # 请求间隔(秒)
COOKIES:
last_update_time: ''
value: ''
DEFAULT_HEADERS:
accept: application/json
accept-language: zh-CN,zh;q=0.9
cache-control: no-cache
origin: https://www.goofish.com
pragma: no-cache
priority: u=1, i
referer: https://www.goofish.com/
sec-ch-ua: '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"'
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: '"Windows"'
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/133.0.0.0 Safari/537.36
HEARTBEAT_INTERVAL: 15
HEARTBEAT_TIMEOUT: 5
LOG_CONFIG:
compression: zip
format: '<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level>
| <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>'
level: INFO
retention: 7 days
rotation: 1 day
MANUAL_MODE:
enabled: false
timeout: 3600
toggle_keywords: []
MESSAGE_EXPIRE_TIME: 300000
TOKEN_REFRESH_INTERVAL: 36000 # 10小时刷新一次token(原来20小时太长)
TOKEN_RETRY_INTERVAL: 1800 # 失败后30分钟重试(原来2小时太长)
COOKIE_KEEPALIVE_INTERVAL: 7200 # 每2小时发一次保活请求,延长Cookie有效期
WEBSOCKET_HEADERS:
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: no-cache
Connection: Upgrade
Host: wss-goofish.dingtalk.com
Origin: https://www.goofish.com
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/133.0.0.0 Safari/537.36
WEBSOCKET_URL: wss://wss-goofish.dingtalk.com/
# 阿奇索转卖配置
AGISO_CONFIG:
enabled: true # 是否启用了阿奇索转卖功能
base_url: https://aldsidle.agiso.com # 阿奇索平台地址
api_endpoints:
verify: /api/GetUserInfo # 验证账户接口
upload: /api/upload # 图片上传接口
publish: /api/item/publish # 商品发布接口
item_list: /api/item/list # 商品列表接口
category_list: /api/category/list # 分类列表接口
timeout: 60 # 请求超时时间(秒)
max_concurrent: 3 # 最大并发请求数
retry_times: 2 # 重试次数
retry_delay: 1 # 重试间隔(秒)
+123
View File
@@ -0,0 +1,123 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# 基本设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 10M;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/atom+xml
image/svg+xml;
# 上游服务器
upstream xianyu_backend {
server xianyu-app:8080;
keepalive 32;
}
# HTTP服务器配置
server {
listen 80;
server_name localhost;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# 代理到后端应用
location / {
proxy_pass http://xianyu_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
proxy_pass http://xianyu_backend;
expires 1y;
add_header Cache-Control "public, immutable";
}
# 健康检查
location /health {
proxy_pass http://xianyu_backend/health;
access_log off;
}
# 错误页面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# HTTPS服务器配置(可选)
# server {
# listen 443 ssl http2;
# server_name localhost;
#
# ssl_certificate /etc/nginx/ssl/cert.pem;
# ssl_certificate_key /etc/nginx/ssl/key.pem;
# ssl_session_timeout 1d;
# ssl_session_cache shared:MozTLS:10m;
# ssl_session_tickets off;
#
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
# ssl_prefer_server_ciphers off;
#
# location / {
# proxy_pass http://xianyu_backend;
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection 'upgrade';
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# proxy_cache_bypass $http_upgrade;
# }
# }
}
+5014
View File
File diff suppressed because it is too large. Load diff
+81
View File
@@ -0,0 +1,81 @@
# ================================
# 闲鱼自动回复系统 - Python依赖包
# ================================
# ==================== 核心Web框架 ====================
fastapi>=0.111.0
uvicorn[standard]>=0.29.0
pydantic>=2.7.0
# ==================== 日志记录 ====================
loguru>=0.7.0
# ==================== 网络通信 ====================
websockets>=10.0,<13.0
aiohttp>=3.9.0
requests>=2.31.0
httpx>=0.25.0
# ==================== 配置文件处理 ====================
PyYAML>=6.0.0
# ==================== JavaScript执行引擎 ====================
PyExecJS>=1.5.1
# ==================== 协议缓冲区解析 ====================
blackboxprotobuf>=1.0.1
# ==================== 系统监控 ====================
psutil>=5.9.0
# ==================== 文件上传支持 ====================
python-multipart>=0.0.6
# ==================== AI回复引擎 ====================
openai>=1.65.5
# ==================== 图像处理 ====================
Pillow>=10.0.0
qrcode[pil]>=7.4.2
# ==================== 浏览器自动化 ====================
playwright>=1.40.0
# ==================== 加密和安全 ====================
PyJWT>=2.8.0
passlib[bcrypt]>=1.7.4
cryptography>=41.0.0
# ==================== 时间处理 ====================
python-dateutil>=2.8.2
# ==================== Excel文件处理 ====================
pandas>=2.0.0
openpyxl>=3.1.0
# ==================== 邮件发送 ====================
email-validator>=2.0.0
# ==================== 数据处理和验证 ====================
xlsxwriter>=3.1.0
# ==================== 版本说明 ====================
# 本文件包含闲鱼自动回复系统的所有必需依赖
# 版本号已经过测试验证,确保兼容性和稳定性
#
# Python版本要求: 3.11+
#
# 安装命令:
# pip install --upgrade pip
# pip install -r requirements.txt
# playwright install chromium
# playwright install-deps chromium # Linux系统需要
#
# ==================== 内置模块说明 ====================
# 以下模块是Python内置模块,无需安装:
# sqlite3, json, base64, hashlib, hmac, time, datetime, os, sys, re, urllib
# asyncio, threading, pathlib, uuid, random, secrets, traceback, logging
# collections, itertools, functools, copy, pickle, gzip, zipfile, shutil
# tempfile, io, csv, xml, html, http, socket, ssl, subprocess, signal
# inspect, ast, enum, math, decimal, array, queue, contextlib, warnings
# typing, dataclasses, weakref, gc, platform, stat, glob, fnmatch
+180
View File
@@ -0,0 +1,180 @@
"""
自动确认发货模块 - 解密版本
这是secure_confirm_ultra.py的解密版本,用于自动确认发货功能
"""
import asyncio
import json
import time
import aiohttp
from loguru import logger
from utils.xianyu_utils import generate_sign, trans_cookies
class SecureConfirm:
"""自动确认发货类"""
def __init__(self, session, cookies_str, cookie_id, main_instance=None):
"""
初始化确认发货实例
Args:
session: aiohttp会话对象
cookies_str: Cookie字符串
cookie_id: Cookie ID
main_instance: 主实例对象(XianyuLive)
"""
self.session = session
self.cookies_str = cookies_str
self.cookie_id = cookie_id
self.main_instance = main_instance
# 解析cookies
self.cookies = trans_cookies(cookies_str) if cookies_str else {}
# Token相关属性
self.current_token = None
self.last_token_refresh_time = 0
self.token_refresh_interval = 3600 # 1小时
def _safe_str(self, obj):
"""安全字符串转换"""
try:
return str(obj)
except:
return "无法转换的对象"
async def _get_real_item_id(self):
"""从数据库中获取一个真实的商品ID"""
try:
from db_manager import db_manager
# 获取该账号的商品列表
items = db_manager.get_items_by_cookie(self.cookie_id)
if items:
# 返回第一个商品的ID
item_id = items[0].get('item_id')
if item_id:
logger.debug(f"【{self.cookie_id}】获取到真实商品ID: {item_id}")
return item_id
# 如果该账号没有商品,尝试获取任意一个商品ID
all_items = db_manager.get_all_items()
if all_items:
item_id = all_items[0].get('item_id')
if item_id:
logger.debug(f"【{self.cookie_id}】使用其他账号的商品ID: {item_id}")
return item_id
logger.warning(f"【{self.cookie_id}】数据库中没有找到任何商品ID")
return None
except Exception as e:
logger.error(f"【{self.cookie_id}】获取真实商品ID失败: {self._safe_str(e)}")
return None
async def _update_config_cookies(self):
"""更新数据库中的Cookie配置"""
try:
from db_manager import db_manager
# 更新数据库中的cookies
db_manager.update_cookie_value(self.cookie_id, self.cookies_str)
logger.debug(f"【{self.cookie_id}】已更新数据库中的Cookie")
except Exception as e:
logger.error(f"【{self.cookie_id}】更新数据库Cookie失败: {self._safe_str(e)}")
async def auto_confirm(self, order_id, item_id=None, retry_count=0):
"""自动确认发货 - 使用真实商品ID刷新token"""
if retry_count >= 4: # 最多重试3次
logger.error("自动确认发货失败,重试次数过多")
return {"error": "自动确认发货失败,重试次数过多"}
# 保存item_id供Token刷新使用
if item_id:
self._current_item_id = item_id
logger.debug(f"【{self.cookie_id}】设置当前商品ID: {item_id}")
# 确保session已创建
if not self.session:
raise Exception("Session未创建")
params = {
'jsv': '2.7.2',
'appKey': '34839810',
't': str(int(time.time()) * 1000),
'sign': '',
'v': '1.0',
'type': 'originaljson',
'accountSite': 'xianyu',
'dataType': 'json',
'timeout': '20000',
'api': 'mtop.taobao.idle.logistic.consign.dummy',
'sessionOption': 'AutoLoginOnly',
}
data_val = '{"orderId":"' + order_id + '", "tradeText":"","picList":[],"newUnconsign":true}'
data = {
'data': data_val,
}
# 始终从最新的cookies中获取_m_h5_tk token(刷新后cookies会被更新)
token = trans_cookies(self.cookies_str).get('_m_h5_tk', '').split('_')[0] if trans_cookies(self.cookies_str).get('_m_h5_tk') else ''
if token:
logger.info(f"使用cookies中的_m_h5_tk token: {token}")
else:
logger.warning("cookies中没有找到_m_h5_tk token")
sign = generate_sign(params['t'], token, data_val)
params['sign'] = sign
try:
logger.info(f"【{self.cookie_id}】开始自动确认发货,订单ID: {order_id}")
async with self.session.post(
'https://h5api.m.goofish.com/h5/mtop.taobao.idle.logistic.consign.dummy/1.0/',
params=params,
data=data
) as response:
res_json = await response.json()
# 检查并更新Cookie
if 'set-cookie' in response.headers:
new_cookies = {}
for cookie in response.headers.getall('set-cookie', []):
if '=' in cookie:
name, value = cookie.split(';')[0].split('=', 1)
new_cookies[name.strip()] = value.strip()
# 更新cookies
if new_cookies:
self.cookies.update(new_cookies)
# 生成新的cookie字符串
self.cookies_str = '; '.join([f"{k}={v}" for k, v in self.cookies.items()])
# 更新数据库中的Cookie
await self._update_config_cookies()
logger.debug("已更新Cookie到数据库")
logger.info(f"【{self.cookie_id}】自动确认发货响应: {res_json}")
# 检查响应结果
if res_json.get('ret') and res_json['ret'][0] == 'SUCCESS::调用成功':
logger.info(f"【{self.cookie_id}】✅ 自动确认发货成功,订单ID: {order_id}")
return {"success": True, "order_id": order_id}
else:
error_msg = res_json.get('ret', ['未知错误'])[0] if res_json.get('ret') else '未知错误'
logger.warning(f"【{self.cookie_id}】❌ 自动确认发货失败: {error_msg}")
return await self.auto_confirm(order_id, item_id, retry_count + 1)
except Exception as e:
logger.error(f"【{self.cookie_id}】自动确认发货API请求异常: {self._safe_str(e)}")
await asyncio.sleep(0.5)
# 网络异常也进行重试
if retry_count < 2:
logger.info(f"【{self.cookie_id}】网络异常,准备重试...")
return await self.auto_confirm(order_id, item_id, retry_count + 1)
return {"error": f"网络异常: {self._safe_str(e)}", "order_id": order_id}
+42
View File
@@ -0,0 +1,42 @@
"""
自动确认发货模块 - 超级混淆版本
代码经过多层编码和混淆处理
"""
import base64 as LsWYPXmT
import zlib as oxWwRTDp
import types as AUdcGvRk
import binascii as qKAaznVW
class pDLWZWoi:
def __init__(self):
self.vrCYrtTq = "d3d377b48583e6f264836734d633a5653516c45665f66426839344731386f205b683230524976655c456667463d497b236c445b493e4c613670733d477b2b23356a726f4430744b49535856364d473e4953757d4d44725f2b645337707e6754467435633d6776484a563e6661667f237372357f266f4a6732376e6b2f2571753153533347493a617739594743587536324c6f4e6c4c6e4e496b62536854307054496d607178673a5d45703d6964327c6d424055497765636e48333665385f25443f463850553548594e444274744257757051495f4a654f656d4148626f463465453f6c645977326e40353468425341333633457d667374337e4a6a5a4f63735a5e49345433777a577436403e413c67323276346c4f46717860766945455a6c6072534c466451743735726f466675343a61767f2b627a554a615d66485a7864474d42644942685e6b454d4f667548624b61477d634668583c634b455f6e645035543349374971317d6e48607a4836746c6f4b4377397c4d6b4a496a766570596a6f4847395172797b66717230523e46387355487a50566f456b213541474838714f665357363b23567457717641334c6f637e67647e665152344e40747662614f2b24633466793f64566f616058624f2364453d69334a42767c6b485c683d4e483b647745586672544f6e4f4e494572776254375e497774435c453a6d637a713855533943686d426a633159354d4d436b484864375037415d41724954624e6858746e605f203a7e477f61607977546856494469654770555837346363533a6237626b207b4267383345323c4f6a545858736c4c484f4a5566653a68546c6a7f495f4a576369447158723f2c4a49635968577f285d40524a5f22475555715765426878394334487e4d6e61516b276a674558685347687a7677397a7b474d486a46563241505a7359317c4649645c415966487a7a44385c645c6956447953643b677943623d4b63483344396a686a7d49793877445374355a4c657264464174383536425f2736577774467857647c694d69675f667a4b46566a59564267616554597373414f664759443030336f654a765a6b4a447a615f2436635139796f233a5a5f6b224b225347515c4c44433e455548757c4771786a634a76513655717a40713f63577e4f6a7d626772575d697173736d66556a66575166317a4c6f4146517477413e625462694166683e456d625c4a70366e657a5641553c64703a4c6777743a4a48364d494d685c634f277b4f22335a6a64407c40593961625a405b6836423769384c69526564557b454c4a405c497d63544c4f68444e4635515a7059734f2b6235483332737f4a757e467f6e4149595c67513f4131555367415a78507153315a6a55644773514969674a5861324857526c4a4f4b6c484b28605544365f236b6f2f4276624b283d4f457833616a763a42676734703057676766627464597675775e6458623a4c4964697549454574747f2b267f4a477e4667637b67786b23647156654372696f49543c483033574f66463f40575a7c4b2348524d63354c41565a477e6c466130383359413a4959783c6448385937476b6b6e6341776056463237767546455259403b4e685574776a7c6959473b4a787070323651377a6631573261337c64583e6c403e6439417a543b2c65605737463a533f6740317174565f687357667375545451374142607f465d617c4b4f4059335c63645078475270307161654e4758477451513c433976337641714c4e476a79747a58454f6b6c446b64635976546347626b47397f4d66434456763456565e4f663d6b607e6f647b2878655455543c69554643696d6d6569764863655763555630376b2363753a6569745746535b47537b63425f683538405f6f46693938755c6c493a7644305263527a4835327f64585b2273505a48694646624d6671486773636172616146587e46484f21524d6663365d625a45543a5574463872474c64565c4349613f2971437830784b2e6834616f2b63684754327f6e466b43566b26454257563b4969707452363737644b2733627b2f243277396e6c6032645a6836513475785462727a7378414b6c4969753b287e45663436483669633d663f4b6a716b645f41346f6277695f49793c487c42326a5154705779635a565633796d4741537d436d65587c657a45384058685c46537055663b276935324d4d6165405b277a7f2547334a4744324974733f6f2a6f4556773f416f287447564a4962594932643c67414134307b61515247627f67667637513a7a4c434e6b42455f2e667e61615237736a7539407b475135595d65523f49753869476b676d444f285a5a51583d6445435d65436a487346383b683a436956793b24505457314866327756444b625a4765433e4368435354456054703d40797658755d6a515b4d696677496072317654683959553152453775525a524e457077786754417c6f684939344268614073617f237d48607561437978686249513446717f624a47354557377a743573316f2f4336793c40534964436e4a65325332463b4b4258724e645b6b656a59454a476755303d4d6735423b2c687c684568564d6a74543275764a5679335536373e42796358467a7a745233463d4f2136446550374f2a4038675577505b296e4f433b2474795972727769584858695a554b29674e4339717c45444c63437148523f615a6b28784e4075377a5c41396b4c486b4863383d4f46626e625558724444744b2932367662407e425372576740764442403c42664775527078605379723578725738765762637b653a59787c42567365663879734246483b4943466d40536c45697c6a75565177775679576941753e6843353c4c48437e674971485f29403244423246347f696a634d67635c403f205e6056416634317836554149483645464a6668323a43683b205a7443715e69553c666653765c475c6058365643484a757a595841686055546154455237536159746353414a4156315b6c4a613d405b46415f254a5348397e49493775495455536a7c453b66514c616f294d6a4a797e6469436f227b64387e667c4a7370576f4441533376695a573e4a61373445424b2b2574795c486e6f25545341655d6e4165586d623975794e646577657241694233524731505238567a7e47305567334a7964395f4072766338647858383e664c4467366172305072737a5a4b237b233b2b2333373b21775f2f22356b2a74443a796269303877346938724534486b2758467f274162666b41537165756564747f2d6230543e6a78725f6f26365035413b4362585445693645745462434b4f41445346424e65653d64356079403c6339605f463532395751315d614557634854797151556a71636d6034586437336776436541344f414665794b20796b485464626b444455675a6559643937417561603650514a7835716559553a626c66415Line truncated
def gdVvQitT(self):
step1_var = self.vrCYrtTq[::-1]
step2_var = bytes.fromhex(step1_var)
step3_var = LsWYPXmT.b64decode(step2_var)
step4_var = oxWwRTDp.decompress(step3_var)
step5_var = step4_var.decode('utf-8')
return step5_var
def CHsKCWCD(self):
"""创建模块"""
decoded_code = self.gdVvQitT()
module_obj = AUdcGvRk.ModuleType('secure_confirm')
exec(decoded_code, module_obj.__dict__)
return module_obj
OhPXQtOT = pDLWZWoi()
amBCLCwC = OhPXQtOT.CHsKCWCD()
SecureConfirm = amBCLCwC.SecureConfirm
# 清理所有变量
del OhPXQtOT
del amBCLCwC
del pDLWZWoi
+130
View File
@@ -0,0 +1,130 @@
import asyncio
import time
from loguru import logger
from utils.xianyu_utils import trans_cookies, generate_sign
class SecureFreeshipping:
def __init__(self, session, cookies_str, cookie_id):
self.session = session
self.cookies_str = cookies_str
self.cookie_id = cookie_id
self.cookies = trans_cookies(cookies_str) if cookies_str else {}
# 这些属性将由主类传递
self.current_token = None
self.last_token_refresh_time = None
self.token_refresh_interval = None
def _safe_str(self, obj):
"""安全转换为字符串"""
try:
return str(obj)
except:
return "无法转换的对象"
async def update_config_cookies(self):
"""更新数据库中的cookies"""
try:
from db_manager import db_manager
# 更新数据库中的Cookie
db_manager.update_config_cookies(self.cookie_id, self.cookies_str)
logger.debug(f"【{self.cookie_id}】Cookie已更新到数据库")
except Exception as e:
logger.error(f"【{self.cookie_id}】更新Cookie到数据库失败: {self._safe_str(e)}")
async def auto_freeshipping(self, order_id, item_id, buyer_id, retry_count=0):
"""自动免拼发货 - 加密版本"""
if retry_count >= 4: # 最多重试3次
logger.error("免拼发货发货失败,重试次数过多")
return {"error": "免拼发货发货失败,重试次数过多"}
# 确保session已创建
if not self.session:
raise Exception("Session未创建")
params = {
'jsv': '2.7.2',
'appKey': '34839810',
't': str(int(time.time()) * 1000),
'sign': '',
'v': '1.0',
'type': 'originaljson',
'accountSite': 'xianyu',
'dataType': 'json',
'timeout': '20000',
'api': 'mtop.idle.groupon.activity.seller.freeshipping',
'sessionOption': 'AutoLoginOnly',
}
data_val = '{"bizOrderId":"' + order_id + '", "itemId":' + item_id + ',"buyerId":' + buyer_id + '}'
data = {
'data': data_val,
}
# 打印参数信息
logger.info(f"【{self.cookie_id}】免拼发货请求参数: data_val = {data_val}")
logger.info(f"【{self.cookie_id}】参数详情 - order_id: {order_id}, item_id: {item_id}, buyer_id: {buyer_id}")
# 始终从最新的cookies中获取_m_h5_tk token(刷新后cookies会被更新)
token = trans_cookies(self.cookies_str).get('_m_h5_tk', '').split('_')[0] if trans_cookies(self.cookies_str).get('_m_h5_tk') else ''
if token:
logger.info(f"使用cookies中的_m_h5_tk token: {token}")
else:
logger.warning("cookies中没有找到_m_h5_tk token")
sign = generate_sign(params['t'], token, data_val)
params['sign'] = sign
try:
logger.info(f"【{self.cookie_id}】开始自动免拼发货,订单ID: {order_id}")
async with self.session.post(
'https://h5api.m.goofish.com/h5/mtop.idle.groupon.activity.seller.freeshipping/1.0/',
params=params,
data=data
) as response:
res_json = await response.json()
# 检查并更新Cookie
if 'set-cookie' in response.headers:
new_cookies = {}
for cookie in response.headers.getall('set-cookie', []):
if '=' in cookie:
name, value = cookie.split(';')[0].split('=', 1)
new_cookies[name.strip()] = value.strip()
# 更新cookies
if new_cookies:
self.cookies.update(new_cookies)
# 生成新的cookie字符串
self.cookies_str = '; '.join([f"{k}={v}" for k, v in self.cookies.items()])
# 更新数据库中的Cookie
await self.update_config_cookies()
logger.debug("已更新Cookie到数据库")
logger.info(f"【{self.cookie_id}】自动免拼发货响应: {res_json}")
# 检查响应结果
if res_json.get('ret') and res_json['ret'][0] == 'SUCCESS::调用成功':
logger.info(f"【{self.cookie_id}】✅ 自动免拼发货成功,订单ID: {order_id}")
return {"success": True, "order_id": order_id}
else:
error_msg = res_json.get('ret', ['未知错误'])[0] if res_json.get('ret') else '未知错误'
logger.warning(f"【{self.cookie_id}】❌ 自动免拼发货失败: {error_msg}")
return await self.auto_freeshipping(order_id, item_id, buyer_id, retry_count + 1)
except Exception as e:
logger.error(f"【{self.cookie_id}】自动免拼发货API请求异常: {self._safe_str(e)}")
await asyncio.sleep(0.5)
# 网络异常也进行重试
if retry_count < 2:
logger.info(f"【{self.cookie_id}】网络异常,准备重试...")
return await self.auto_freeshipping(order_id, item_id, buyer_id, retry_count + 1)
return {"error": f"网络异常: {self._safe_str(e)}", "order_id": order_id}
+43
View File
@@ -0,0 +1,43 @@
"""
自动免拼发货模块 - 超级混淆版本
代码经过多层编码和混淆处理
"""
import base64 as LsWYPXmT
import zlib as oxWwRTDp
import types as AUdcGvRk
import binascii as qKAaznVW
class pDLWZWoi:
def __init__(self):
self.vrCYrtTq = "d3b61374a5c6036483a6f68524a585a765c42545a447c6f243767333f2f22464e47556544315a5a5a685174554973395b295f68733379636730517c4e4e4956726576397170515f696978453054464d665642676e675134666754323876534541733855347f2f4538396a7e677d626b2833384c40353434653f26643c4d63747840534137746778795b63497e464b423474603235764a434a415259546951537e485656546f433c46726f2856777b26315b634b697852556f226f4e4f4a425a68353a636d633554454b2251424a5338736f43716f454277774955523359644050357e6446684e447971313352765f6b2669383956787e6634473b4b2c694163443933387769485a756d684270713658727a7776386676713537457b457b6538703c4873466a5a575b6a4a65763b685847336f233276693767573938616b687941413352643941584f407a503c62573b474a7f6576407953595d6a48647458747b643242366c624e48314f63465968543c474e674b214150326e645b6038417c437930533971394a723a43375277705b47637b455855337f2c65703a4d683552337e657f2f446762495a4a703e4133796b28685132655174384b25436769316b494235735d4a74766b47746845733b2d6a7b467f4439543845594174324369393a7271333e6a6a60347857774d4979407e443d6b6a75484350774e4d46794539323256445764307449636371623b623878324363686b67584a4367413a414375354779735378713c45736e4d40317a517649687b664f656971543f26575c43743942546668444b694265507763316465736478705d4a774949375264316864327f243d435a55457561677032386155727d497a5979725754525d48614d6559524956494f665d474b4e6749577a797a636b6960594b47393a637c4738493455365464683448686f694579535934694a755e60547b645c4453394253747b4e493555424c6b476d4172503f2b4e474a735c67363770313772425f4159475f6a544677744446313c623f4a7561475a763931495769497e674337373357614b6845503a493c4568597f26776278423870384f2f644141656445776a5c44717d45323a4561333367624479603951314e663777786161554779397c43407948766f446c4d6a51785856366a5b424362386b277a603d415a615238767e49737a4a674b6a5870725a733f6c6075527c414e6e47343a627b636853313a5278734c635958743d61764f6b4d64337436353461384565315a45725674333532685c4f2336616f2557663f485c654b4549713f4f64516a5c624669723874524a566f6331657751464e6441644c6342687074375b63365e4948514f4431456853594b27577572525b4156675a4a73525e4836765e4776423737774838624f6039703172426f217f4b60737351517a7c42366549503c46725773414954353f247f617b2b2f217135417a736f6d407549695b4669703932734d637455654e46445e48754273796561527232555d4a4265497c69794155765377545171507170326b683346787555324855377262573774433f273038397a6f6475433674344c68585640585538327f237f455e6e4e624731627a503f256e4b2564647b263246536f65744545414b6244323a60377568547039384974543b44526e47503451614f484552705a514a685d4953387965605148784a5d414570365246695e663a773a587e435e61516735396162594961754279673647325b6333307f42754149764a755c4d615d484445646b2344347051633a74487351373f2f427c6f226755314d65463a4a613742464e435076403243584275435f44747540703b41765d4975537f6b6b4466496077507668725a5b4b435b416a5557666f4f446a65697b6b61665a7a426a783b605f274d67524b684c6851355d45555b45413a47675038397f4e6d636d603b664a793c6a58783835467f435957474833537877615a6165655774735439735b475055545a734932685331744f6d6b6c6161757271364343335b6554696f424a76396564707b4866426a4a59683f275358614d613656553c6032424b694368664357507a67754363693231545b617e4a56334d6a5932337e4a46436071694a733557474c4735425971594875445f4637314465524935563558794552714561414a4e4c45715877745d4537623f26745050367b2830726c414f285755707a45364e683452593261705a40754c66624f46714a48394136477359323750324c463678407658793a7d664d4c6b60765146436947494a455e4868616f41426161774a675379305146623666437437554a434b293f6466616269317a4779516a747c603853535432537769426575483369484d4157366d69613f486476753f263772643a7b267647596547447935337530744666323462773c68583b2b293637397268474a7c456a7f627932714773434753474b434669585354667a43353b24726c6b205b63354b2330537f2932703334485751573678775b2664597f267b6f434a4051397779355657657473776b4148527438736054574853635d4a6e46433642764e42463a437635536466785531376b4e4551795f654b6c6434594f6b2f23323f2b273137614941796876503361357e4260574259756a43473f61634a657663403739673f603e6b63563a576652366a4875353c4432774535673976716a776b67536a79667b447168537178743476365b6540523b614165645462415242463661657a476c6451413a5567517d424174556463455a48607d4a515b65344641757167446e635c653a565e4d683448744449373576366f25763738613a47324e645e4446656a64475733547e617f2775756259663036576077465c6136307330776b4677596471346f2852307b2f223073376d67347675483572644560707e4a636956797c486f2b474c61334c61447460523a545840514d6134705e6a4071423a773477344e6037347a7f2676756735667168483a42763f2433573f217e69767b6a41324433416b2365376b2a59314a713a697a43683158735d4e6d6a47465f2642666244474c6b6e44575a656e4757495a57317e427533484d4b476b677254503b2055303f4d48485650583954753a5038636c4b29323e63356765605264493467356266667a43353f2e4964324f2f673b26787b273b2b2f6934454e6f21586a57394550344169543447696d6257577453437159654c4f614974674052554a6934494979743255476d44776c4d4137484f63557866717b6442563266455134364a675738713773586259554d6842387762575241736a72564d663b49454e67407135536553496860313a68796373703d48723951783a7758336c654f6a6272774651395a6d46374075377168575a6937446546464378486a7070794477713462697a416a437e67553a6358535b2e4178635565796532627f4335694Line truncated
def gdVvQitT(self):
# 解密过程
step1_var = self.vrCYrtTq[::-1]
step2_var = bytes.fromhex(step1_var)
step3_var = LsWYPXmT.b64decode(step2_var)
step4_var = oxWwRTDp.decompress(step3_var)
step5_var = step4_var.decode('utf-8')
return step5_var
def CHsKCWCD(self):
"""创建模块"""
decoded_code = self.gdVvQitT()
module_obj = AUdcGvRk.ModuleType('secure_freeshipping')
exec(decoded_code, module_obj.__dict__)
return module_obj
OhPXQtOT = pDLWZWoi()
amBCLCwC = OhPXQtOT.CHsKCWCD()
SecureFreeshipping = amBCLCwC.SecureFreeshipping
# 清理所有变量
del OhPXQtOT
del amBCLCwC
del pDLWZWoi
+227
View File
@@ -0,0 +1,227 @@
/* ================================
【账号管理菜单】相关样式
================================ */
.status-toggle {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
.status-toggle input {
opacity: 0;
width: 0;
height: 0;
}
.status-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 24px;
}
.status-slider:before {
position: absolute;
content: "";
height: 18px;
width: 18px;
left: 3px;
bottom: 3px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .status-slider {
background-color: #10b981;
}
input:checked + .status-slider:before {
transform: translateX(26px);
}
.status-badge {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.25rem 0.5rem;
border-radius: 12px;
font-size: 0.875rem;
font-weight: 500;
min-width: 2rem;
height: 1.5rem;
}
.status-badge.enabled {
background: #dcfce7;
color: #166534;
border: 1px solid #bbf7d0;
}
.status-badge.disabled {
background: #fef2f2;
color: #991b1b;
border: 1px solid #fecaca;
}
.account-row.disabled {
opacity: 0.6;
background-color: #f9fafb;
}
.account-row.disabled .cookie-value {
background-color: #f3f4f6;
}
/* 关键词管理界面的状态提示 */
.account-badge .badge.bg-warning {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.7; }
100% { opacity: 1; }
}
.disabled-account-notice {
background: #fef3c7;
border: 1px solid #f59e0b;
border-radius: 8px;
padding: 0.75rem;
margin-bottom: 1rem;
color: #92400e;
}
.disabled-account-notice .bi {
color: #f59e0b;
}
/* 扫码登录按钮特殊样式 */
.qr-login-btn {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
border: none;
box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.qr-login-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
background: linear-gradient(135deg, #218838 0%, #1ea085 100%);
}
.qr-login-btn:active {
transform: translateY(0);
}
.qr-login-btn::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
transition: left 0.5s;
}
.qr-login-btn:hover::before {
left: 100%;
}
/* 二维码容器样式 */
.qr-code-wrapper {
border: 3px solid #28a745;
box-shadow: 0 4px 15px rgba(40, 167, 69, 0.2);
transition: all 0.3s ease;
}
.qr-code-wrapper:hover {
box-shadow: 0 6px 20px rgba(40, 167, 69, 0.3);
}
/* 步骤指引样式 */
.step-item {
text-align: center;
}
.step-number {
font-weight: bold;
font-size: 14px;
box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
}
/* 手动输入按钮样式 */
.manual-input-btn {
transition: all 0.3s ease;
}
.manual-input-btn:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(108, 117, 125, 0.2);
}
/* 等待提示样式 */
.bg-light-warning {
background-color: #fff3cd !important;
}
.qr-loading-tip {
animation: pulse-warning 2s infinite;
}
@keyframes pulse-warning {
0% {
opacity: 0.8;
}
50% {
opacity: 1;
}
100% {
opacity: 0.8;
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.status-toggle {
width: 40px;
height: 20px;
}
.status-slider:before {
height: 14px;
width: 14px;
left: 3px;
bottom: 3px;
}
input:checked + .status-slider:before {
transform: translateX(20px);
}
.qr-login-btn, .manual-input-btn {
margin-bottom: 10px;
font-size: 0.9rem;
}
.step-item {
margin-bottom: 15px;
}
.step-number {
width: 25px !important;
height: 25px !important;
font-size: 12px;
}
}
+405
View File
@@ -0,0 +1,405 @@
/* ================================
管理员功能样式 - 用户管理和数据管理
================================ */
/* 用户管理样式 */
.user-card {
transition: transform 0.2s ease, box-shadow 0.2s ease;
border: 1px solid var(--border-color);
border-radius: 12px;
}
.user-card:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
.user-card .card-body {
padding: 1.25rem;
}
.user-card .badge {
font-size: 0.75rem;
padding: 0.375rem 0.75rem;
}
/* 数据管理样式 */
.table-container {
max-height: 600px;
overflow-y: auto;
border: 1px solid var(--border-color);
border-radius: 8px;
}
.table th {
position: sticky;
top: 0;
background: var(--dark-color);
color: white;
z-index: 10;
border: none;
font-weight: 600;
font-size: 0.875rem;
padding: 0.75rem;
}
.table td {
padding: 0.75rem;
font-size: 0.875rem;
border-bottom: 1px solid var(--border-color);
vertical-align: middle;
}
.table tbody tr:hover {
background-color: rgba(79, 70, 229, 0.05);
}
/* 数据统计卡片 */
.data-stats {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
color: white;
border: none;
}
.data-stats .card-body {
padding: 0.75rem;
}
/* 表格状态样式 */
#loadingTable,
#noTableSelected,
#noTableData {
padding: 3rem 1rem;
}
#loadingTable .spinner-border {
width: 3rem;
height: 3rem;
border-width: 0.3em;
}
#noTableSelected i,
#noTableData i {
font-size: 4rem;
color: var(--secondary-color);
opacity: 0.5;
}
/* 按钮组样式 */
.btn-group .btn {
border-radius: 0;
}
.btn-group .btn:first-child {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.btn-group .btn:last-child {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
/* 表格选择器样式 */
#tableSelect {
border: 2px solid var(--border-color);
border-radius: 8px;
padding: 0.75rem;
font-size: 0.875rem;
transition: border-color 0.2s ease;
}
#tableSelect:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 0.2rem rgba(79, 70, 229, 0.25);
}
/* 记录计数样式 */
#recordCount {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary-color);
}
/* 响应式调整 */
@media (max-width: 768px) {
.user-card {
margin-bottom: 1rem;
}
.table-container {
max-height: 400px;
}
.table th,
.table td {
padding: 0.5rem;
font-size: 0.8rem;
}
.btn-group {
flex-direction: column;
}
.btn-group .btn {
border-radius: 6px !important;
margin-bottom: 0.25rem;
}
}
/* 加载状态动画 */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.user-card,
.table-container {
animation: fadeIn 0.3s ease-out;
}
/* 表格滚动条样式 */
.table-container::-webkit-scrollbar {
width: 8px;
}
.table-container::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.table-container::-webkit-scrollbar-thumb {
background: var(--secondary-color);
border-radius: 4px;
}
.table-container::-webkit-scrollbar-thumb:hover {
background: var(--primary-color);
}
/* 文本截断样式 */
.text-truncate-custom {
max-width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
/* 状态徽章样式 */
.status-badge {
font-size: 0.75rem;
padding: 0.25rem 0.5rem;
border-radius: 12px;
}
/* 工具提示样式增强 */
[title] {
cursor: help;
}
/* 空状态图标样式 */
.empty-state-icon {
font-size: 4rem;
color: var(--secondary-color);
opacity: 0.3;
margin-bottom: 1rem;
}
/* 操作按钮样式 */
.action-buttons .btn {
margin: 0 0.125rem;
padding: 0.375rem 0.75rem;
}
.action-buttons .btn-sm {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
}
/* ================================
系统使用手册样式
================================ */
.manual-wrapper {
display: flex;
min-height: 100%;
}
.manual-sidebar {
width: 220px;
flex-shrink: 0;
background: #fff;
border-right: 1px solid var(--border-color);
position: sticky;
top: 0;
height: 100%;
overflow-y: auto;
align-self: flex-start;
}
.manual-sidebar-header {
padding: 1rem 1.25rem;
font-weight: 700;
font-size: 0.95rem;
color: var(--dark-color);
border-bottom: 1px solid var(--border-color);
background: #f9fafb;
}
.manual-nav {
display: flex;
flex-direction: column;
padding: 0.5rem 0;
}
.manual-nav-link {
display: block;
padding: 0.6rem 1.25rem;
color: var(--secondary-color);
text-decoration: none;
font-size: 0.875rem;
border-left: 3px solid transparent;
transition: all 0.2s ease;
}
.manual-nav-link:hover {
color: var(--primary-color);
background: rgba(79, 70, 229, 0.04);
border-left-color: var(--primary-light);
}
.manual-nav-link.active {
color: var(--primary-color);
background: rgba(79, 70, 229, 0.06);
border-left-color: var(--primary-color);
font-weight: 600;
}
.manual-content {
flex: 1;
padding: 2rem 2.5rem;
}
.manual-section {
margin-bottom: 2.5rem;
padding-bottom: 2rem;
border-bottom: 1px solid #f0f0f0;
}
.manual-section:last-of-type {
border-bottom: none;
margin-bottom: 1rem;
}
.manual-section-title {
font-size: 1.35rem;
font-weight: 700;
color: var(--dark-color);
margin-bottom: 0.75rem;
padding-bottom: 0.5rem;
border-bottom: 2px solid var(--primary-color);
display: inline-block;
}
.manual-desc {
color: var(--secondary-color);
font-size: 0.95rem;
margin-bottom: 1.25rem;
line-height: 1.6;
}
.manual-section h4 {
font-size: 1rem;
font-weight: 600;
color: var(--dark-color);
margin-top: 1.25rem;
margin-bottom: 0.5rem;
}
.manual-section ul,
.manual-section ol {
padding-left: 1.5rem;
margin-bottom: 0.75rem;
}
.manual-section li {
font-size: 0.9rem;
line-height: 1.7;
color: #374151;
margin-bottom: 0.25rem;
}
.manual-section li strong {
color: var(--dark-color);
}
.manual-tip,
.manual-warn {
margin-top: 0.75rem;
padding: 0.75rem 1rem;
border-radius: 8px;
font-size: 0.85rem;
line-height: 1.5;
}
.manual-tip {
background: #ecfdf5;
border: 1px solid #a7f3d0;
color: #065f46;
}
.manual-warn {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
}
.manual-footer {
margin-top: 1rem;
padding-top: 1rem;
}
.manual-sidebar::-webkit-scrollbar {
width: 5px;
}
.manual-sidebar::-webkit-scrollbar-track {
background: transparent;
}
.manual-sidebar::-webkit-scrollbar-thumb {
background: #d1d5db;
border-radius: 3px;
}
@media (max-width: 992px) {
.manual-sidebar {
display: none;
}
.manual-content {
padding: 1.5rem;
}
}
/* 统计卡片渐变背景 */
.stats-card-primary {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
}
.stats-card-info {
background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
}
.stats-card-success {
background: linear-gradient(135deg, var(--success-color) 0%, #0d9488 100%);
}
.stats-card-warning {
background: linear-gradient(135deg, var(--warning-color) 0%, #d97706 100%);
}
+13
View File
@@ -0,0 +1,13 @@
@import url('variables.css');
@import url('layout.css');
@import url('dashboard.css');
@import url('logs.css');
@import url('keywords.css');
@import url('accounts.css');
@import url('items.css');
@import url('notifications.css');
@import url('components.css');
@import url('admin.css');
+403
View File
@@ -0,0 +1,403 @@
/* ================================
通用卡片样式 - 适用于所有菜单的卡片
================================ */
.card {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 16px;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
margin-bottom: 2rem;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
.card-header {
background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
color: white;
border: none;
border-radius: 16px 16px 0 0 !important;
font-weight: 600;
font-size: 1.1rem;
padding: 1.25rem 1.5rem;
}
.card-body {
padding: 1.5rem;
}
.btn {
border-radius: 10px;
font-weight: 500;
transition: all 0.3s ease;
padding: 0.5rem 1rem;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
.btn-primary {
background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
border: none;
}
.btn-success {
background: linear-gradient(135deg, var(--success-color), #059669);
border: none;
}
.btn-danger {
background: linear-gradient(135deg, var(--danger-color), #dc2626);
border: none;
}
.btn-outline-primary {
border: 2px solid var(--primary-color);
color: var(--primary-color);
}
.btn-outline-primary:hover {
background: var(--primary-color);
border-color: var(--primary-color);
color: white;
}
.btn-outline-success {
border: 2px solid var(--success-color);
color: var(--success-color);
}
.btn-outline-success:hover {
background: var(--success-color);
border-color: var(--success-color);
color: white;
}
.btn-outline-info {
border: 2px solid #0dcaf0;
color: #0dcaf0;
}
.btn-outline-info:hover {
background: #0dcaf0;
border-color: #0dcaf0;
color: white;
}
.btn-outline-danger {
border: 2px solid var(--danger-color);
color: var(--danger-color);
}
.btn-outline-danger:hover {
background: var(--danger-color);
border-color: var(--danger-color);
color: white;
}
/* ================================
通用表格样式 - 适用于所有菜单的表格
================================ */
.table {
margin-bottom: 0;
background: transparent;
}
.table th {
border-top: none;
border-bottom: 2px solid var(--border-color);
font-weight: 600;
color: var(--dark-color);
background: rgba(79, 70, 229, 0.05);
padding: 1rem;
}
.table td {
padding: 1rem;
border-bottom: 1px solid var(--border-color);
vertical-align: middle;
}
.table tbody tr:hover {
background: rgba(79, 70, 229, 0.02);
}
.badge {
font-weight: 500;
padding: 5px 10px;
}
.form-control:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
.cookie-value {
font-family: 'JetBrains Mono', 'Fira Code', 'Courier New', monospace;
font-size: 0.85rem;
background: #f8fafc;
padding: 0.75rem;
border-radius: 8px;
border: 1px solid #e5e7eb;
word-break: break-all;
line-height: 1.4;
max-height: 120px;
overflow-y: auto;
white-space: pre-wrap;
}
.loading {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(255,255,255,0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.loading-spinner {
width: 3rem;
height: 3rem;
}
.keyword-editor {
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.modal-content {
border-radius: 10px;
border: none;
}
.modal-header {
border-bottom: 1px solid rgba(0,0,0,0.05);
}
.modal-footer {
border-top: 1px solid rgba(0,0,0,0.05);
}
.cookie-id {
font-weight: 600;
color: var(--primary-color);
font-size: 1rem;
}
.empty-state {
text-align: center;
padding: 3rem 2rem;
color: var(--secondary-color);
}
.empty-state i {
opacity: 0.5;
}
.form-control, .form-select {
border-radius: 10px;
border: 2px solid var(--border-color);
transition: all 0.3s ease;
padding: 0.75rem 1rem;
}
.form-control:focus, .form-select:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
transform: translateY(-1px);
}
.form-label {
font-weight: 600;
color: var(--dark-color);
margin-bottom: 0.5rem;
}
/* ================================
通用模态框样式 - 适用于所有菜单的模态框
================================ */
.modal-content {
border: none;
border-radius: 16px;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(10px);
}
.modal-header {
background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
color: white;
border: none;
border-radius: 16px 16px 0 0;
}
.toast-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 9999;
}
.toast {
border: none;
border-radius: 12px;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(10px);
}
.btn-group .btn {
margin-right: 0.25rem;
}
.btn-group .btn:last-child {
margin-right: 0;
}
@media (max-width: 768px) {
.container {
margin-top: 1rem;
padding: 0 1rem;
}
.card-body {
padding: 1rem;
}
.btn {
font-size: 0.875rem;
padding: 0.375rem 0.75rem;
}
.cookie-value {
font-size: 0.75rem;
max-height: 80px;
}
.btn-group {
flex-direction: column;
}
.btn-group .btn {
margin-right: 0;
margin-bottom: 0.25rem;
}
/* 移动端商品表格优化 */
#itemsTableBody .btn-group {
flex-direction: row;
}
#itemsTableBody .btn-group .btn {
padding: 0.2rem 0.4rem;
font-size: 0.75rem;
}
}
/* ================================
API参数提示样式
================================ */
.param-item {
display: flex;
align-items: center;
padding: 0.25rem 0;
}
.param-name {
background-color: #f8f9fa;
color: #495057;
padding: 0.2rem 0.4rem;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid #dee2e6;
cursor: pointer;
transition: all 0.2s ease;
min-width: 120px;
display: inline-block;
}
.param-name:hover {
background-color: #e9ecef;
border-color: #adb5bd;
transform: translateY(-1px);
}
#postParamsHelp,
#editPostParamsHelp {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 1rem;
}
#postParamsHelp .alert,
#editPostParamsHelp .alert {
margin-bottom: 0;
border-radius: 6px;
}
/* 参数项点击效果 */
.param-name:active {
transform: translateY(0);
background-color: #dee2e6;
}
/* ================================
API参数提示样式
================================ */
.param-item {
display: flex;
align-items: center;
padding: 0.25rem 0;
}
.param-name {
background-color: #f8f9fa;
color: #495057;
padding: 0.2rem 0.4rem;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid #dee2e6;
cursor: pointer;
transition: all 0.2s ease;
min-width: 120px;
display: inline-block;
}
.param-name:hover {
background-color: #e9ecef;
border-color: #adb5bd;
transform: translateY(-1px);
}
#postParamsHelp,
#editPostParamsHelp {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 1rem;
}
#postParamsHelp .alert,
#editPostParamsHelp .alert {
margin-bottom: 0;
border-radius: 6px;
}
/* 参数项点击效果 */
.param-name:active {
transform: translateY(0);
background-color: #dee2e6;
}
+68
View File
@@ -0,0 +1,68 @@
/* 仪表盘样式 */
.dashboard-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
/* ================================
【仪表盘菜单】相关样式
================================ */
.stat-card {
background: white;
border-radius: 12px;
padding: 1.5rem;
box-shadow: var(--shadow-sm);
border: 1px solid var(--border-color);
transition: all 0.3s ease;
}
.stat-card:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
.stat-icon {
width: 48px;
height: 48px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
margin-bottom: 1rem;
}
.stat-icon.primary {
background: rgba(79, 70, 229, 0.1);
color: var(--primary-color);
}
.stat-icon.success {
background: rgba(16, 185, 129, 0.1);
color: var(--success-color);
}
.stat-icon.warning {
background: rgba(245, 158, 11, 0.1);
color: var(--warning-color);
}
.stat-icon.info {
background: rgba(59, 130, 246, 0.1);
color: #3b82f6;
}
.stat-number {
font-size: 2rem;
font-weight: 700;
color: var(--dark-color);
margin-bottom: 0.5rem;
}
.stat-label {
color: var(--secondary-color);
font-size: 0.875rem;
font-weight: 500;
}
+52
View File
@@ -0,0 +1,52 @@
/* ================================
【商品管理菜单】表格样式
================================ */
#itemsTableBody .btn-group {
white-space: nowrap;
}
#itemsTableBody .btn-group .btn {
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
border-radius: 0.25rem;
}
#itemsTableBody .btn-group .btn:first-child {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
#itemsTableBody .btn-group .btn:last-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
border-left: 0;
}
#itemsTableBody .btn-group .btn i {
font-size: 0.875rem;
}
/* 表格操作列样式 */
.table td:last-child {
text-align: center;
vertical-align: middle;
padding: 0.5rem 0.25rem;
}
/* 表格文本截断优化 */
.table td {
vertical-align: middle;
}
.table td[title] {
cursor: help;
}
/* 商品表格特定优化 */
#itemsTableBody td:nth-child(4),
#itemsTableBody td:nth-child(5) {
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
+403
View File
@@ -0,0 +1,403 @@
/* 关键词管理现代化样式 */
.keyword-container {
background: white;
border-radius: 16px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
overflow: hidden;
transition: all 0.3s ease;
}
.keyword-header {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
color: white;
padding: 1.5rem 2rem;
display: flex;
align-items: center;
justify-content: space-between;
}
.keyword-header h3 {
margin: 0;
font-weight: 600;
display: flex;
align-items: center;
}
.keyword-header .account-badge {
background: rgba(255, 255, 255, 0.2);
padding: 0.5rem 1rem;
border-radius: 20px;
font-size: 0.875rem;
font-weight: 500;
}
.keyword-input-area {
padding: 2rem;
background: #f8fafc;
border-bottom: 1px solid #e5e7eb;
}
.keyword-input-group {
display: grid;
grid-template-columns: 1fr 2fr 1fr auto;
gap: 1rem;
align-items: end;
}
.input-field {
position: relative;
}
.input-field label {
position: absolute;
top: -0.5rem;
left: 0.75rem;
background: #f8fafc;
padding: 0 0.5rem;
font-size: 0.75rem;
font-weight: 500;
color: #6b7280;
z-index: 1;
}
.input-field input, .input-field select {
width: 100%;
padding: 1rem 0.75rem 0.75rem;
border: 2px solid #e5e7eb;
border-radius: 12px;
font-size: 0.875rem;
transition: all 0.3s ease;
background: white;
}
.input-field input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.add-btn {
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
color: white;
border: none;
border-radius: 12px;
padding: 1rem 1.5rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 0.5rem;
}
.add-btn:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(16, 185, 129, 0.3);
}
.add-btn:active {
transform: translateY(0);
}
/* ================================
【自动回复菜单】相关样式
================================ */
.keywords-list {
padding: 1.5rem 2rem 2rem;
max-height: 500px;
overflow-y: auto;
}
.keyword-item {
background: white;
border: 1px solid #e5e7eb;
border-radius: 12px;
margin-bottom: 1rem;
transition: all 0.3s ease;
overflow: hidden;
}
.keyword-item:hover {
border-color: #667eea;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
transform: translateY(-1px);
}
.keyword-item-header {
padding: 1rem 1.5rem;
background: #f8fafc;
border-bottom: 1px solid #e5e7eb;
display: flex;
align-items: center;
justify-content: space-between;
}
.keyword-tag {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
color: white;
padding: 0.5rem 1rem;
border-radius: 20px;
font-size: 0.875rem;
font-weight: 500;
display: flex;
align-items: center;
gap: 0.5rem;
}
.keyword-actions {
display: flex;
gap: 0.5rem;
}
.action-btn {
width: 36px;
height: 36px;
border: none;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}
.edit-btn {
background: #f3f4f6;
color: #6b7280;
}
.edit-btn:hover {
background: #e5e7eb;
color: #374151;
}
.edit-btn-disabled {
background: #f9fafb !important;
color: #9ca3af !important;
cursor: not-allowed !important;
}
.edit-btn-disabled:hover {
background: #f9fafb !important;
color: #9ca3af !important;
}
.delete-btn {
background: #fef2f2;
color: #ef4444;
}
.delete-btn:hover {
background: #fee2e2;
color: #dc2626;
}
.keyword-content {
padding: 1.5rem;
}
.reply-text {
color: #374151;
line-height: 1.6;
margin: 0;
font-size: 0.875rem;
}
.empty-state {
text-align: center;
padding: 4rem 2rem;
color: #6b7280;
}
.empty-state i {
font-size: 4rem;
margin-bottom: 1rem;
opacity: 0.5;
}
.empty-state h3 {
margin: 0 0 0.5rem;
color: #374151;
}
.empty-state p {
margin: 0 0 2rem;
font-size: 0.875rem;
}
.quick-add-btn {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
color: white;
border: none;
border-radius: 12px;
padding: 0.75rem 1.5rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
}
.quick-add-btn:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}
/* 账号选择器现代化 */
.account-selector {
background: white;
border-radius: 16px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 2rem;
margin-bottom: 2rem;
}
.selector-header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.5rem;
}
.selector-icon {
width: 48px;
height: 48px;
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 1.25rem;
}
.selector-title {
margin: 0;
color: #1f2937;
font-weight: 600;
}
.selector-subtitle {
margin: 0;
color: #6b7280;
font-size: 0.875rem;
}
.account-select-wrapper {
position: relative;
}
.account-select {
width: 100%;
padding: 1rem 1.25rem;
border: 2px solid #e5e7eb;
border-radius: 12px;
font-size: 1rem;
background: white;
cursor: pointer;
transition: all 0.3s ease;
}
.account-select:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
/* ================================
【自动回复菜单】图片关键词样式
================================ */
.btn-image {
background: linear-gradient(135deg, #28a745, #20c997) !important;
border: none !important;
margin-left: 10px;
}
.btn-image:hover {
background: linear-gradient(135deg, #218838, #1ea085) !important;
transform: translateY(-1px);
}
.keyword-input-group {
display: flex;
gap: 15px;
align-items: end;
flex-wrap: wrap;
}
.keyword-input-group .add-btn {
white-space: nowrap;
min-width: auto;
}
.image-preview {
margin-top: 10px;
}
.preview-container {
padding: 10px;
border: 2px dashed #ddd;
border-radius: 8px;
text-align: center;
background-color: #f8f9fa;
}
.keyword-type-badge {
display: inline-block;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 500;
margin-left: 8px;
}
.keyword-type-text {
background-color: #e3f2fd;
color: #1976d2;
}
.keyword-type-image {
background-color: #f3e5f5;
color: #7b1fa2;
}
/* 关键词列表中的图片预览 */
.keyword-image-preview {
max-width: 60px;
max-height: 60px;
border-radius: 4px;
border: 1px solid #ddd;
cursor: pointer;
}
.keyword-image-preview:hover {
border-color: #007bff;
transform: scale(1.05);
transition: all 0.2s ease;
}
/* 响应式调整 */
@media (max-width: 768px) {
.keyword-input-group {
grid-template-columns: 1fr;
gap: 1rem;
}
.keyword-item-header {
flex-direction: column;
align-items: flex-start;
gap: 1rem;
}
.keyword-actions {
align-self: flex-end;
}
.keyword-input-group {
flex-direction: column;
align-items: stretch;
}
.keyword-input-group .add-btn {
margin-left: 0;
margin-top: 10px;
}
}
+202
View File
@@ -0,0 +1,202 @@
/* ================================
通用布局 - 侧边栏和导航
================================ */
.sidebar {
position: fixed;
top: 0;
left: 0;
height: 100vh;
width: 250px;
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
color: white;
z-index: 1000;
transition: all 0.3s ease;
box-shadow: 2px 0 10px rgba(0,0,0,0.1);
display: flex;
flex-direction: column;
overflow: hidden;
}
.sidebar-header {
padding: 1.5rem 1rem;
border-bottom: 1px solid rgba(255,255,255,0.1);
flex-shrink: 0;
}
.sidebar-brand {
font-size: 1.25rem;
font-weight: 700;
color: white;
text-decoration: none;
display: flex;
align-items: center;
}
.sidebar-nav {
padding: 1rem 0;
flex: 1;
overflow-y: auto;
overflow-x: hidden;
}
/* 侧边栏滚动条样式 */
.sidebar-nav::-webkit-scrollbar {
width: 6px;
}
.sidebar-nav::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 3px;
}
.sidebar-nav::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 3px;
transition: background 0.3s ease;
}
.sidebar-nav::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
/* Firefox滚动条样式 */
.sidebar-nav {
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.3) rgba(255, 255, 255, 0.1);
}
.nav-item {
margin: 0.25rem 0;
}
.nav-link {
display: flex;
align-items: center;
padding: 0.75rem 1.5rem;
color: rgba(255,255,255,0.8);
text-decoration: none;
transition: all 0.3s ease;
border-left: 3px solid transparent;
}
.nav-link:hover {
color: white;
background: rgba(255,255,255,0.1);
border-left-color: rgba(255,255,255,0.5);
}
.nav-link.active {
color: white;
background: rgba(255,255,255,0.15);
border-left-color: white;
}
.nav-link i {
margin-right: 0.75rem;
width: 20px;
text-align: center;
}
.nav-divider {
padding: 0.5rem 1rem;
border-top: 1px solid rgba(255,255,255,0.1);
margin-top: 0.5rem;
}
.nav-divider small {
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
}
/* 主内容区域 */
.main-content {
margin-left: 250px;
height: 100vh;
background: #f8fafc;
display: flex;
flex-direction: column;
}
.content-header {
background: white;
padding: 1.5rem 2rem;
border-bottom: 1px solid var(--border-color);
box-shadow: var(--shadow-sm);
flex-shrink: 0;
}
.content-body {
padding: 2rem;
}
/* 响应式设计 */
@media (max-width: 768px) {
.sidebar {
transform: translateX(-100%);
}
.sidebar.show {
transform: translateX(0);
}
.main-content {
margin-left: 0;
}
.mobile-toggle {
display: block !important;
}
}
.mobile-toggle {
display: none;
position: fixed;
top: 1rem;
left: 1rem;
z-index: 1001;
background: var(--primary-color);
color: white;
border: none;
border-radius: 8px;
padding: 0.5rem;
box-shadow: var(--shadow-md);
}
/* 内容区域样式 */
.content-section {
display: none;
}
.content-section.active {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.content-section.active .content-body {
flex: 1;
min-height: 0;
overflow: auto;
}
/* 全局底部信息 */
.global-footer {
flex-shrink: 0;
text-align: center;
padding: 0.75rem 2rem;
background: none;
border-top: 1px solid var(--border-color);
font-size: 0.8rem;
color: var(--secondary-color);
}
.global-footer a {
color: var(--primary-color);
text-decoration: none;
}
.global-footer a:hover {
text-decoration: underline;
}
+147
View File
@@ -0,0 +1,147 @@
/* ================================
【日志管理菜单】相关样式
================================ */
.log-container {
height: 70vh;
overflow-y: auto;
background-color: #1e1e1e;
color: #d4d4d4;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 12px;
line-height: 1.2;
padding: 8px;
border-radius: 4px;
}
.log-entry {
margin-bottom: 0px;
padding: 1px 0;
word-wrap: break-word;
white-space: pre-wrap;
line-height: 1.2;
}
.log-entry.DEBUG {
color: #9cdcfe;
}
.log-entry.INFO {
color: #4ec9b0;
}
.log-entry.WARNING {
color: #dcdcaa;
}
.log-entry.ERROR {
color: #f48771;
}
.log-entry.CRITICAL {
color: #ff6b6b;
font-weight: bold;
}
.log-timestamp {
color: #808080;
}
.log-level {
font-weight: bold;
margin: 0 5px;
}
.log-source {
color: #569cd6;
}
.log-message {
color: inherit;
}
.log-container::-webkit-scrollbar {
width: 8px;
}
.log-container::-webkit-scrollbar-track {
background: #2d2d30;
}
.log-container::-webkit-scrollbar-thumb {
background: #464647;
border-radius: 4px;
}
.log-container::-webkit-scrollbar-thumb:hover {
background: #5a5a5c;
}
/* 日志过滤标签样式 */
.filter-badge {
cursor: pointer;
transition: all 0.2s;
margin-right: 0.5rem;
margin-bottom: 0.25rem;
}
.filter-badge:hover {
transform: scale(1.05);
}
.filter-badge.active {
box-shadow: 0 0 0 2px rgba(255,255,255,0.5);
}
/* 自动刷新指示器 */
.auto-refresh-indicator {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
/* 日志行悬停效果 */
.log-entry:hover {
background: rgba(255,255,255,0.05);
}
/* 商品搜索相关样式 */
.item-card {
transition: transform 0.2s;
border: none;
border-radius: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.item-card:hover {
transform: translateY(-2px);
}
.item-image {
width: 100%;
height: 200px;
object-fit: cover;
border-radius: 10px;
}
.price {
color: #e74c3c;
font-weight: bold;
font-size: 1.2em;
}
.seller-name {
color: #6c757d;
font-size: 0.9em;
}
.want-count {
margin-top: 10px;
}
.want-count .badge {
font-size: 0.8em;
}
+83
View File
@@ -0,0 +1,83 @@
/* ================================
【通知渠道菜单】卡片样式
================================ */
.channel-type-card {
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
min-height: 180px; /* 设置最小高度,让卡片更紧凑 */
}
.channel-type-card .card-body {
padding: 1rem; /* 减少内边距 */
}
.channel-type-card .channel-icon {
transition: transform 0.3s ease;
margin-bottom: 0.75rem !important; /* 减少图标下方间距 */
}
.channel-type-card .channel-icon i {
font-size: 2.2rem !important; /* 减小图标大小 */
}
.channel-type-card .card-title {
font-size: 1.1rem; /* 减小标题字体 */
margin-bottom: 0.5rem;
}
.channel-type-card .card-text {
font-size: 0.85rem; /* 减小描述文字 */
margin-bottom: 0.75rem;
}
.channel-type-card .btn {
transition: all 0.3s ease;
font-size: 0.85rem; /* 减小按钮文字 */
padding: 0.375rem 0.75rem; /* 减小按钮内边距 */
}
.channel-type-card:hover {
transform: translateY(-3px); /* 减少悬停位移 */
box-shadow: 0 6px 20px rgba(0,0,0,0.12);
border-color: var(--bs-primary);
}
.channel-type-card:hover .channel-icon {
transform: scale(1.05); /* 减少悬停缩放 */
}
.channel-type-card:hover .btn {
transform: scale(1.02); /* 减少按钮悬停缩放 */
}
/* 响应式调整 */
@media (max-width: 768px) {
.channel-type-card {
margin-bottom: 10px;
min-height: 160px; /* 移动端稍微减小高度 */
}
.channel-type-card .card-body {
padding: 0.75rem; /* 移动端减少内边距 */
}
.channel-type-card .channel-icon i {
font-size: 2rem !important; /* 移动端图标更小 */
}
.channel-type-card .card-title {
font-size: 1rem; /* 移动端标题更小 */
}
.channel-type-card .card-text {
font-size: 0.8rem; /* 移动端描述文字更小 */
}
}
/* 大屏幕优化 */
@media (min-width: 1400px) {
.channel-type-card {
min-height: 200px; /* 大屏幕稍微增加高度 */
}
}
+26
View File
@@ -0,0 +1,26 @@
/* ================================
全局变量和基础样式
================================ */
:root {
--primary-color: #4f46e5;
--primary-hover: #4338ca;
--primary-light: #6366f1;
--secondary-color: #6b7280;
--success-color: #10b981;
--danger-color: #ef4444;
--warning-color: #f59e0b;
--light-color: #f9fafb;
--dark-color: #1f2937;
--border-color: #e5e7eb;
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
body {
font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f8fafc;
min-height: 100vh;
padding: 0;
margin: 0;
}
+556
View File
@@ -0,0 +1,556 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据管理 - 闲鱼自动回复系统</title>
<link href="/static/lib/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="/static/lib/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<style>
.admin-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem 0;
margin-bottom: 2rem;
}
.table-container {
max-height: 600px;
overflow-y: auto;
border: 1px solid #dee2e6;
border-radius: 0.375rem;
}
.table th {
position: sticky;
top: 0;
background: #f8f9fa;
z-index: 10;
}
.btn-delete {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
}
.table-info {
background: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 1rem;
margin-bottom: 1rem;
}
.data-stats {
background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
color: white;
border: none;
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="/">
<i class="bi bi-robot"></i> 闲鱼自动回复系统
</a>
<div class="navbar-nav ms-auto">
<a class="nav-link" href="/">
<i class="bi bi-house"></i> 首页
</a>
<a class="nav-link" href="/user_management.html">
<i class="bi bi-people"></i> 用户管理
</a>
<a class="nav-link active" href="/data_management.html">
<i class="bi bi-database"></i> 数据管理
</a>
<a class="nav-link" href="/log_management.html">
<i class="bi bi-file-text"></i> 日志管理
</a>
<a class="nav-link" href="#" onclick="logout()">
<i class="bi bi-box-arrow-right"></i> 退出
</a>
</div>
</div>
</nav>
<!-- 管理员标题 -->
<div class="admin-header">
<div class="container">
<h1 class="mb-0">
<i class="bi bi-database"></i> 数据管理
</h1>
<p class="mb-0 mt-2">查看和管理数据库中的所有表数据</p>
</div>
</div>
<div class="container">
<!-- 表选择器 -->
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">
<i class="bi bi-table"></i> 数据表选择
</h5>
</div>
<div class="card-body">
<div class="row align-items-center">
<div class="col-md-6">
<label class="form-label">选择数据表</label>
<select class="form-select" id="tableSelect" onchange="loadTableData()">
<option value="">请选择数据表...</option>
<option value="users">users - 用户表</option>
<option value="cookies">cookies - Cookie账号表</option>
<option value="cookie_status">cookie_status - Cookie状态表</option>
<option value="keywords">keywords - 关键字表</option>
<option value="default_replies">default_replies - 默认回复表</option>
<option value="item_replay">item_replay - 指定商品回复表</option>
<option value="default_reply_records">default_reply_records - 默认回复记录表</option>
<option value="ai_reply_settings">ai_reply_settings - AI回复设置表</option>
<option value="ai_conversations">ai_conversations - AI对话历史表</option>
<option value="ai_item_cache">ai_item_cache - AI商品信息缓存表</option>
<option value="item_info">item_info - 商品信息表</option>
<option value="message_notifications">message_notifications - 消息通知表</option>
<option value="cards">cards - 卡券表</option>
<option value="delivery_rules">delivery_rules - 发货规则表</option>
<option value="notification_channels">notification_channels - 通知渠道表</option>
<option value="user_settings">user_settings - 用户设置表</option>
<option value="system_settings">system_settings - 系统设置表</option>
<option value="email_verifications">email_verifications - 邮箱验证表</option>
<option value="captcha_codes">captcha_codes - 验证码表</option>
<option value="orders">orders - 订单表</option>
</select>
</div>
<div class="col-md-3">
<label class="form-label">数据统计</label>
<div class="card data-stats">
<div class="card-body text-center py-2">
<h5 id="recordCount" class="mb-0">-</h5>
<small>条记录</small>
</div>
</div>
</div>
<div class="col-md-3">
<label class="form-label">&nbsp;</label>
<div class="d-grid">
<button class="btn btn-primary" onclick="refreshTableData()">
<i class="bi bi-arrow-clockwise"></i> 刷新数据
</button>
</div>
</div>
</div>
</div>
</div>
<!-- 表信息 -->
<div id="tableInfo" class="table-info" style="display: none;">
<h6 class="mb-2">
<i class="bi bi-info-circle"></i> 表信息
</h6>
<div class="row">
<div class="col-md-4">
<strong>表名:</strong> <span id="tableName">-</span>
</div>
<div class="col-md-4">
<strong>中文名:</strong> <span id="tableDescription">-</span>
</div>
<div class="col-md-4">
<strong>记录数:</strong> <span id="tableRecordCount">-</span>
</div>
</div>
</div>
<!-- 数据表格 -->
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="bi bi-table"></i> 数据内容
</h5>
<div class="d-flex gap-2">
<button class="btn btn-sm btn-outline-warning" onclick="confirmDeleteAll()" style="display: none;" id="deleteAllBtn">
<i class="bi bi-trash"></i> 清空表
</button>
</div>
</div>
<div class="card-body p-0">
<div id="loadingData" class="text-center py-4" style="display: none;">
<div class="spinner-border" role="status">
<span class="visually-hidden">加载中...</span>
</div>
<p class="mt-2">正在加载数据...</p>
</div>
<div id="noTableSelected" class="text-center py-4">
<i class="bi bi-table" style="font-size: 3rem; color: #ccc;"></i>
<p class="mt-2 text-muted">请选择要查看的数据表</p>
</div>
<div id="noData" class="text-center py-4" style="display: none;">
<i class="bi bi-inbox" style="font-size: 3rem; color: #ccc;"></i>
<p class="mt-2 text-muted">该表暂无数据</p>
</div>
<div id="tableContainer" class="table-container" style="display: none;">
<table class="table table-striped table-hover mb-0">
<thead id="tableHead"></thead>
<tbody id="tableBody"></tbody>
</table>
</div>
</div>
</div>
</div>
<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-exclamation-triangle text-warning"></i> 确认删除
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<p>您确定要删除这条记录吗?</p>
<div class="alert alert-warning">
<i class="bi bi-exclamation-triangle"></i>
<strong>警告:</strong>此操作不可恢复!
</div>
<div id="deleteRecordInfo" class="bg-light p-2 rounded">
<!-- 记录信息将在这里显示 -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" onclick="confirmDelete()">
<i class="bi bi-trash"></i> 确认删除
</button>
</div>
</div>
</div>
</div>
<!-- 清空表确认模态框 -->
<div class="modal fade" id="deleteAllModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-exclamation-triangle text-danger"></i> 确认清空表
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<p>您确定要清空整个表的所有数据吗?</p>
<div class="alert alert-danger">
<i class="bi bi-exclamation-triangle"></i>
<strong>危险操作:</strong>这将删除表中的所有记录,此操作不可恢复!
</div>
<p>表名: <strong id="deleteAllTableName">-</strong></p>
<p>记录数: <strong id="deleteAllRecordCount">-</strong> 条</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" onclick="confirmDeleteAll()">
<i class="bi bi-trash"></i> 确认清空
</button>
</div>
</div>
</div>
</div>
<script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
<script>
let currentTable = '';
let currentData = [];
let deleteModal = null;
let deleteAllModal = null;
let currentDeleteId = null;
// 表的中文描述
const tableDescriptions = {
'users': '用户表',
'cookies': 'Cookie账号表',
'cookie_status': 'Cookie状态表',
'keywords': '关键字表',
'item_replay': '指定商品回复表',
'default_replies': '默认回复表',
'default_reply_records': '默认回复记录表',
'ai_reply_settings': 'AI回复设置表',
'ai_conversations': 'AI对话历史表',
'ai_item_cache': 'AI商品信息缓存表',
'item_info': '商品信息表',
'message_notifications': '消息通知表',
'cards': '卡券表',
'delivery_rules': '发货规则表',
'notification_channels': '通知渠道表',
'user_settings': '用户设置表',
'system_settings': '系统设置表',
'email_verifications': '邮箱验证表',
'captcha_codes': '验证码表',
'orders': '订单表'
};
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 检查管理员权限
checkAdminPermission();
// 初始化模态框
deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
deleteAllModal = new bootstrap.Modal(document.getElementById('deleteAllModal'));
});
// 检查管理员权限
function checkAdminPermission() {
const token = localStorage.getItem('auth_token');
if (!token) {
alert('请先登录');
window.location.href = '/login.html';
return;
}
// 验证token并检查是否为管理员
fetch('/verify', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
if (!data.authenticated) {
alert('登录已过期,请重新登录');
window.location.href = '/login.html';
return;
}
// 检查是否为管理员
if (data.username !== 'admin') {
alert('此功能仅限管理员使用');
window.location.href = '/';
return;
}
})
.catch(error => {
console.error('权限验证失败:', error);
alert('权限验证失败');
window.location.href = '/login.html';
});
}
// 加载表数据
function loadTableData() {
const tableSelect = document.getElementById('tableSelect');
const selectedTable = tableSelect.value;
if (!selectedTable) {
showNoTableSelected();
return;
}
currentTable = selectedTable;
showLoading();
const token = localStorage.getItem('auth_token');
fetch(`/admin/data/${selectedTable}`, {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
currentData = data.data;
displayTableData(data.data, data.columns);
updateTableInfo(selectedTable, data.data.length);
} else {
alert('加载数据失败: ' + data.message);
showNoData();
}
})
.catch(error => {
console.error('加载数据失败:', error);
alert('加载数据失败');
showNoData();
});
}
// 刷新表数据
function refreshTableData() {
if (currentTable) {
loadTableData();
}
}
// 显示表数据
function displayTableData(data, columns) {
const tableHead = document.getElementById('tableHead');
const tableBody = document.getElementById('tableBody');
// 清空表格
tableHead.innerHTML = '';
tableBody.innerHTML = '';
if (!data || data.length === 0) {
showNoData();
return;
}
// 创建表头
const headerRow = document.createElement('tr');
columns.forEach(column => {
const th = document.createElement('th');
th.textContent = column;
headerRow.appendChild(th);
});
// 添加操作列
const actionTh = document.createElement('th');
actionTh.textContent = '操作';
actionTh.style.width = '100px';
headerRow.appendChild(actionTh);
tableHead.appendChild(headerRow);
// 创建表格数据
data.forEach((row, index) => {
const tr = document.createElement('tr');
columns.forEach(column => {
const td = document.createElement('td');
let value = row[column];
// 处理特殊值
if (value === null || value === undefined) {
value = '-';
} else if (typeof value === 'string' && value.length > 50) {
value = value.substring(0, 50) + '...';
}
td.textContent = value;
tr.appendChild(td);
});
// 添加操作按钮
const actionTd = document.createElement('td');
const deleteBtn = document.createElement('button');
deleteBtn.className = 'btn btn-danger btn-delete';
deleteBtn.innerHTML = '<i class="bi bi-trash"></i>';
deleteBtn.onclick = () => deleteRecord(row, index);
actionTd.appendChild(deleteBtn);
tr.appendChild(actionTd);
tableBody.appendChild(tr);
});
showTableContainer();
updateRecordCount(data.length);
}
// 更新表信息
function updateTableInfo(tableName, recordCount) {
document.getElementById('tableName').textContent = tableName;
document.getElementById('tableDescription').textContent = tableDescriptions[tableName] || '未知表';
document.getElementById('tableRecordCount').textContent = recordCount;
document.getElementById('tableInfo').style.display = 'block';
// 显示/隐藏清空表按钮
const deleteAllBtn = document.getElementById('deleteAllBtn');
if (recordCount > 0) {
deleteAllBtn.style.display = 'inline-block';
} else {
deleteAllBtn.style.display = 'none';
}
}
// 更新记录数
function updateRecordCount(count) {
document.getElementById('recordCount').textContent = count;
}
// 显示状态函数
function showLoading() {
document.getElementById('loadingData').style.display = 'block';
document.getElementById('noTableSelected').style.display = 'none';
document.getElementById('noData').style.display = 'none';
document.getElementById('tableContainer').style.display = 'none';
document.getElementById('tableInfo').style.display = 'none';
}
function showNoTableSelected() {
document.getElementById('loadingData').style.display = 'none';
document.getElementById('noTableSelected').style.display = 'block';
document.getElementById('noData').style.display = 'none';
document.getElementById('tableContainer').style.display = 'none';
document.getElementById('tableInfo').style.display = 'none';
updateRecordCount('-');
}
function showNoData() {
document.getElementById('loadingData').style.display = 'none';
document.getElementById('noTableSelected').style.display = 'none';
document.getElementById('noData').style.display = 'block';
document.getElementById('tableContainer').style.display = 'none';
}
function showTableContainer() {
document.getElementById('loadingData').style.display = 'none';
document.getElementById('noTableSelected').style.display = 'none';
document.getElementById('noData').style.display = 'none';
document.getElementById('tableContainer').style.display = 'block';
}
// 删除记录
function deleteRecord(record, index) {
currentDeleteId = record.id || record.user_id || index;
// 显示记录信息
const deleteRecordInfo = document.getElementById('deleteRecordInfo');
deleteRecordInfo.innerHTML = '';
Object.keys(record).forEach(key => {
const div = document.createElement('div');
div.innerHTML = `<strong>${key}:</strong> ${record[key] || '-'}`;
deleteRecordInfo.appendChild(div);
});
deleteModal.show();
}
// 确认删除
function confirmDelete() {
if (!currentDeleteId || !currentTable) return;
const token = localStorage.getItem('auth_token');
fetch(`/admin/data/${currentTable}/${currentDeleteId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
deleteModal.hide();
if (data.success) {
alert('删除成功');
loadTableData(); // 重新加载数据
} else {
alert('删除失败: ' + data.message);
}
})
.catch(error => {
console.error('删除失败:', error);
alert('删除失败');
});
}
// 确认清空表
function confirmDeleteAll() {
if (!currentTable) return;
document.getElementById('deleteAllTableName').textContent = currentTable;
document.getElementById('deleteAllRecordCount').textContent = currentData.length;
deleteAllModal.show();
}
// 退出登录
function logout() {
localStorage.removeItem('auth_token');
window.location.href = '/login.html';
}
</script>
</body>
</html>
+4458
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+10915
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e()}(this,(function(){"use strict";const t=new Map,e={set(e,i,n){t.has(e)||t.set(e,new Map);const s=t.get(e);s.has(i)||0===s.size?s.set(i,n):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(s.keys())[0]}.`)},get:(e,i)=>t.has(e)&&t.get(e).get(i)||null,remove(e,i){if(!t.has(e))return;const n=t.get(e);n.delete(i),0===n.size&&t.delete(e)}},i="transitionend",n=t=>(t&&window.CSS&&window.CSS.escape&&(t=t.replace(/#([^\s"#']+)/g,((t,e)=>`#${CSS.escape(e)}`))),t),s=t=>{t.dispatchEvent(new Event(i))},o=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),r=t=>o(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(n(t)):null,a=t=>{if(!o(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},l=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),c=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?c(t.parentNode):null},h=()=>{},d=t=>{t.offsetHeight},u=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,f=[],p=()=>"rtl"===document.documentElement.dir,m=t=>{var e;e=()=>{const e=u();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(f.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of f)t()})),f.push(e)):e()},g=(t,e=[],i=t)=>"function"==typeof t?t(...e):i,_=(t,e,n=!0)=>{if(!n)return void g(t);const o=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let r=!1;const a=({target:n})=>{n===e&&(r=!0,e.removeEventListener(i,a),g(t))};e.addEventListener(i,a),setTimeout((()=>{r||s(e)}),o)},b=(t,e,i,n)=>{const s=t.length;let o=t.indexOf(e);return-1===o?!i&&n?t[s-1]:t[0]:(o+=i?1:-1,n&&(o=(o+s)%s),t[Math.max(0,Math.min(o,s-1))])},v=/[^.]*(?=\..*)\.|.*/,y=/\..*/,w=/::\d+$/,A={};let E=1;const T={mouseenter:"mouseover",mouseleave:"mouseout"},C=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function O(t,e){return e&&`${e}::${E++}`||t.uidEvent||E++}function x(t){const e=O(t);return t.uidEvent=e,A[e]=A[e]||{},A[e]}function k(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function L(t,e,i){const n="string"==typeof e,s=n?i:e||i;let o=I(t);return C.has(o)||(o=t),[n,s,o]}function S(t,e,i,n,s){if("string"!=typeof e||!t)return;let[o,r,a]=L(e,i,n);if(e in T){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=x(t),c=l[a]||(l[a]={}),h=k(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=O(r,e.replace(v,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return P(s,{delegateTarget:r}),n.oneOff&&N.off(t,s.type,e,i),i.apply(r,[s])}}(t,i,r):function(t,e){return function i(n){return P(n,{delegateTarget:t}),i.oneOff&&N.off(t,n.type,e),e.apply(t,[n])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function D(t,e,i,n,s){const o=k(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function $(t,e,i,n){const s=e[i]||{};for(const[o,r]of Object.entries(s))o.includes(n)&&D(t,e,i,r.callable,r.delegationSelector)}function I(t){return t=t.replace(y,""),T[t]||t}const N={on(t,e,i,n){S(t,e,i,n,!1)},one(t,e,i,n){S(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=L(e,i,n),a=r!==e,l=x(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))$(t,l,i,e.slLine truncated
//# sourceMappingURL=bootstrap.bundle.min.js.map
+6
View File
@@ -0,0 +1,6 @@
@charset "UTF-8";/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, 0.175);--bs-border-radius:0.375rem;--bs-border-radius-sm:0.25rem;--bs-border-radius-lg:0.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width:0.25rem;--bs-focus-ring-opacity:0.25;--bs-focus-ring-color:rgba(13, 110, 253, 0.25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, 0.5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherLine truncated
/*# sourceMappingURL=bootstrap.min.css.map */
+457
View File
@@ -0,0 +1,457 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>日志管理 - 闲鱼自动回复系统</title>
<link href="/static/lib/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="/static/lib/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<style>
.admin-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem 0;
margin-bottom: 2rem;
}
.log-container {
background: #1e1e1e;
color: #f8f9fa;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
max-height: 600px;
overflow-y: auto;
border-radius: 0.375rem;
}
.log-line {
padding: 0.25rem 0.5rem;
border-bottom: 1px solid #333;
white-space: pre-wrap;
word-break: break-all;
}
.log-line:hover {
background: #2d2d2d;
}
.log-info { color: #17a2b8; }
.log-warning { color: #ffc107; }
.log-error { color: #dc3545; }
.log-debug { color: #6c757d; }
.filter-badge {
cursor: pointer;
transition: all 0.2s;
}
.filter-badge:hover {
transform: scale(1.05);
}
.filter-badge.active {
box-shadow: 0 0 0 2px rgba(255,255,255,0.5);
}
.auto-refresh-indicator {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="/">
<i class="bi bi-robot"></i> 闲鱼自动回复系统
</a>
<div class="navbar-nav ms-auto">
<a class="nav-link" href="/">
<i class="bi bi-house"></i> 首页
</a>
<a class="nav-link" href="/user_management.html">
<i class="bi bi-people"></i> 用户管理
</a>
<a class="nav-link" href="/data_management.html">
<i class="bi bi-database"></i> 数据管理
</a>
<a class="nav-link active" href="/log_management.html">
<i class="bi bi-file-text"></i> 日志管理
</a>
<a class="nav-link" href="#" onclick="logout()">
<i class="bi bi-box-arrow-right"></i> 退出
</a>
</div>
</div>
</nav>
<!-- 管理员标题 -->
<div class="admin-header">
<div class="container">
<h1 class="mb-0">
<i class="bi bi-file-text"></i> 日志管理
</h1>
<p class="mb-0 mt-2">查看和监控系统运行日志</p>
</div>
</div>
<div class="container">
<!-- 控制面板 -->
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">
<i class="bi bi-sliders"></i> 日志控制
</h5>
</div>
<div class="card-body">
<div class="row align-items-center">
<div class="col-md-3">
<label class="form-label">显示行数</label>
<select class="form-select" id="logLines" onchange="loadLogs()">
<option value="50">50行</option>
<option value="100" selected>100行</option>
<option value="200">200行</option>
<option value="500">500行</option>
<option value="1000">1000行</option>
</select>
</div>
<div class="col-md-4">
<label class="form-label">日志级别过滤</label>
<div class="d-flex gap-2 flex-wrap">
<span class="badge bg-secondary filter-badge active" data-level="" onclick="filterByLevel('')">
全部
</span>
<span class="badge bg-info filter-badge log-info" data-level="info" onclick="filterByLevel('info')">
INFO
</span>
<span class="badge bg-warning filter-badge log-warning" data-level="warning" onclick="filterByLevel('warning')">
WARNING
</span>
<span class="badge bg-danger filter-badge log-error" data-level="error" onclick="filterByLevel('error')">
ERROR
</span>
<span class="badge bg-secondary filter-badge log-debug" data-level="debug" onclick="filterByLevel('debug')">
DEBUG
</span>
</div>
</div>
<div class="col-md-3">
<label class="form-label">自动刷新</label>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="autoRefresh" onchange="toggleAutoRefresh()">
<label class="form-check-label" for="autoRefresh">
<span id="autoRefreshLabel">关闭</span>
<i id="autoRefreshIcon" class="bi bi-circle" style="display: none;"></i>
</label>
</div>
</div>
<div class="col-md-2">
<label class="form-label">&nbsp;</label>
<div class="d-grid">
<button class="btn btn-primary" onclick="loadLogs()">
<i class="bi bi-arrow-clockwise"></i> 刷新
</button>
</div>
</div>
</div>
</div>
</div>
<!-- 日志信息 -->
<div class="card mb-4">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="bi bi-info-circle"></i> 日志信息
</h5>
<small class="text-muted" id="lastUpdate">最后更新: -</small>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<strong>日志文件:</strong>
<span id="logFile" class="text-muted">-</span>
</div>
<div class="col-md-4">
<strong>显示行数:</strong>
<span id="displayLines" class="text-muted">-</span>
</div>
<div class="col-md-4">
<strong>当前过滤:</strong>
<span id="currentFilter" class="text-muted">全部</span>
</div>
</div>
</div>
</div>
<!-- 日志内容 -->
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="bi bi-terminal"></i> 日志内容
</h5>
<div class="d-flex gap-2">
<button class="btn btn-sm btn-outline-secondary" onclick="scrollToTop()">
<i class="bi bi-arrow-up"></i> 顶部
</button>
<button class="btn btn-sm btn-outline-secondary" onclick="scrollToBottom()">
<i class="bi bi-arrow-down"></i> 底部
</button>
</div>
</div>
<div class="card-body p-0">
<div id="loadingLogs" class="text-center py-4">
<div class="spinner-border" role="status">
<span class="visually-hidden">加载中...</span>
</div>
<p class="mt-2">正在加载日志...</p>
</div>
<div id="logContainer" class="log-container" style="display: none;"></div>
<div id="noLogs" class="text-center py-4" style="display: none;">
<i class="bi bi-file-text" style="font-size: 3rem; color: #ccc;"></i>
<p class="mt-2 text-muted">暂无日志数据</p>
</div>
</div>
</div>
</div>
<script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
<script>
let autoRefreshInterval = null;
let currentLevel = '';
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 检查管理员权限
checkAdminPermission();
// 加载日志
loadLogs();
});
// 检查管理员权限
function checkAdminPermission() {
const token = localStorage.getItem('auth_token');
if (!token) {
alert('请先登录');
window.location.href = '/login.html';
return;
}
// 验证token并检查是否为管理员
fetch('/verify', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
if (!data.authenticated) {
alert('登录已过期,请重新登录');
window.location.href = '/login.html';
return;
}
// 检查是否为管理员
if (data.username !== 'admin') {
alert('此功能仅限管理员使用');
window.location.href = '/';
return;
}
})
.catch(error => {
console.error('权限验证失败:', error);
alert('权限验证失败');
window.location.href = '/login.html';
});
}
// 加载日志
function loadLogs() {
const token = localStorage.getItem('auth_token');
const lines = document.getElementById('logLines').value;
const level = currentLevel;
const loadingDiv = document.getElementById('loadingLogs');
const logContainer = document.getElementById('logContainer');
const noLogsDiv = document.getElementById('noLogs');
loadingDiv.style.display = 'block';
logContainer.style.display = 'none';
noLogsDiv.style.display = 'none';
let url = `/admin/logs?lines=${lines}`;
if (level) {
url += `&level=${level}`;
}
fetch(url, {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => {
console.log('API响应状态:', response.status);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
})
.then(data => {
console.log('API响应数据:', data);
loadingDiv.style.display = 'none';
if (data.success === false) {
console.error('API返回错误:', data.message);
noLogsDiv.innerHTML = `
<div class="text-center p-4 text-danger">
<i class="bi bi-exclamation-triangle fs-1"></i>
<p class="mt-2">加载日志失败</p>
<p class="small">${data.message || '未知错误'}</p>
</div>
`;
noLogsDiv.style.display = 'block';
return;
}
if (data.logs && data.logs.length > 0) {
console.log(`显示 ${data.logs.length} 条日志`);
displayLogs(data.logs);
updateLogInfo(data);
logContainer.style.display = 'block';
} else {
console.log('没有日志数据');
noLogsDiv.innerHTML = `
<div class="text-center p-4 text-muted">
<i class="bi bi-file-text fs-1"></i>
<p class="mt-2">暂无日志数据</p>
</div>
`;
noLogsDiv.style.display = 'block';
}
// 更新最后更新时间
document.getElementById('lastUpdate').textContent =
'最后更新: ' + new Date().toLocaleTimeString('zh-CN');
})
.catch(error => {
console.error('加载日志失败:', error);
loadingDiv.style.display = 'none';
noLogsDiv.innerHTML = `
<div class="text-center p-4 text-danger">
<i class="bi bi-exclamation-triangle fs-1"></i>
<p class="mt-2">加载日志失败</p>
<p class="small">${error.message}</p>
</div>
`;
noLogsDiv.style.display = 'block';
});
}
// 显示日志
function displayLogs(logs) {
const logContainer = document.getElementById('logContainer');
logContainer.innerHTML = '';
// 反转日志数组,让最新的日志显示在最上面
const reversedLogs = [...logs].reverse();
reversedLogs.forEach(log => {
const logLine = document.createElement('div');
logLine.className = 'log-line';
// 根据日志级别添加颜色类
if (/\|\s*INFO\s*\|/.test(log)) {
logLine.classList.add('log-info');
} else if (/\|\s*WARNING\s*\|/.test(log)) {
logLine.classList.add('log-warning');
} else if (/\|\s*ERROR\s*\|/.test(log)) {
logLine.classList.add('log-error');
} else if (/\|\s*DEBUG\s*\|/.test(log)) {
logLine.classList.add('log-debug');
}
logLine.textContent = log;
logContainer.appendChild(logLine);
});
// 自动滚动到顶部(显示最新日志)
scrollToTop();
}
// 更新日志信息
function updateLogInfo(data) {
document.getElementById('logFile').textContent = data.log_file || '-';
document.getElementById('displayLines').textContent = data.total_lines || '-';
}
// 按级别过滤
function filterByLevel(level) {
currentLevel = level;
// 更新过滤按钮状态
document.querySelectorAll('.filter-badge').forEach(badge => {
badge.classList.remove('active');
});
document.querySelector(`[data-level="${level}"]`).classList.add('active');
// 更新当前过滤显示
const filterText = level ? level.toUpperCase() : '全部';
document.getElementById('currentFilter').textContent = filterText;
// 重新加载日志
loadLogs();
}
// 切换自动刷新
function toggleAutoRefresh() {
const autoRefresh = document.getElementById('autoRefresh');
const label = document.getElementById('autoRefreshLabel');
const icon = document.getElementById('autoRefreshIcon');
if (autoRefresh.checked) {
// 开启自动刷新
autoRefreshInterval = setInterval(loadLogs, 5000); // 每5秒刷新
label.textContent = '开启 (5s)';
icon.style.display = 'inline';
icon.classList.add('auto-refresh-indicator');
} else {
// 关闭自动刷新
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
autoRefreshInterval = null;
}
label.textContent = '关闭';
icon.style.display = 'none';
icon.classList.remove('auto-refresh-indicator');
}
}
// 滚动到顶部
function scrollToTop() {
const logContainer = document.getElementById('logContainer');
logContainer.scrollTop = 0;
}
// 滚动到底部
function scrollToBottom() {
const logContainer = document.getElementById('logContainer');
logContainer.scrollTop = logContainer.scrollHeight;
}
// 退出登录
function logout() {
// 清理自动刷新
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
}
localStorage.removeItem('auth_token');
window.location.href = '/login.html';
}
// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
}
});
</script>
</body>
</html>
+673
View File
@@ -0,0 +1,673 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 闲鱼自动回复管理系统</title>
<link rel="stylesheet" href="/static/lib/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="/static/lib/bootstrap-icons/bootstrap-icons.css">
<style>
:root {
--primary-color: #0d6efd;
--secondary-color: #6c757d;
--success-color: #198754;
--danger-color: #dc3545;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.login-container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
overflow: hidden;
width: 100%;
max-width: 400px;
}
.login-header {
background: var(--primary-color);
color: white;
padding: 30px;
text-align: center;
}
.login-header h2 {
margin: 0;
font-weight: 600;
}
.login-header p {
margin: 10px 0 0 0;
opacity: 0.9;
}
.login-body {
padding: 40px 30px;
}
.form-control {
border-radius: 10px;
border: 2px solid #e9ecef;
padding: 12px 15px;
font-size: 16px;
transition: all 0.3s ease;
}
.form-control:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
.btn-login {
background: var(--primary-color);
border: none;
border-radius: 10px;
padding: 12px;
font-size: 16px;
font-weight: 600;
width: 100%;
transition: all 0.3s ease;
}
.btn-login:hover {
background: #0b5ed7;
transform: translateY(-2px);
}
.input-group {
position: relative;
margin-bottom: 20px;
}
.input-group i {
position: absolute;
left: 15px;
top: 50%;
transform: translateY(-50%);
color: var(--secondary-color);
z-index: 10;
}
.input-group .form-control {
padding-left: 45px;
}
.alert {
border-radius: 10px;
border: none;
}
.loading {
display: none;
}
.loading.show {
display: inline-block;
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-header">
<i class="bi bi-chat-dots-fill fs-1 mb-3"></i>
<h2>闲鱼自动回复</h2>
<p>管理系统登录</p>
</div>
<div class="login-body">
<!-- 登录方式选择 -->
<div class="login-tabs mb-4">
<div class="btn-group w-100" role="group">
<input type="radio" class="btn-check" name="loginType" id="usernameLogin" value="username" checked>
<label class="btn btn-outline-primary" for="usernameLogin">用户名/密码</label>
<input type="radio" class="btn-check" name="loginType" id="emailPasswordLogin" value="email-password">
<label class="btn btn-outline-primary" for="emailPasswordLogin">邮箱/密码</label>
<input type="radio" class="btn-check" name="loginType" id="emailCodeLogin" value="email-code">
<label class="btn btn-outline-primary" for="emailCodeLogin">邮箱/验证码</label>
</div>
</div>
<form id="loginForm">
<!-- 用户名/密码登录 -->
<div id="usernameLoginForm" class="login-form-section">
<div class="input-group">
<i class="bi bi-person-fill"></i>
<input type="text" class="form-control" id="username" placeholder="请输入用户名">
</div>
<div class="input-group">
<i class="bi bi-lock-fill"></i>
<input type="password" class="form-control" id="password" placeholder="请输入密码">
</div>
</div>
<!-- 邮箱/密码登录 -->
<div id="emailPasswordLoginForm" class="login-form-section" style="display: none;">
<div class="input-group">
<i class="bi bi-envelope-fill"></i>
<input type="email" class="form-control" id="emailForPassword" placeholder="请输入邮箱地址">
</div>
<div class="input-group">
<i class="bi bi-lock-fill"></i>
<input type="password" class="form-control" id="emailPassword" placeholder="请输入密码">
</div>
</div>
<!-- 邮箱/验证码登录 -->
<div id="emailCodeLoginForm" class="login-form-section" style="display: none;">
<div class="input-group">
<i class="bi bi-envelope-fill"></i>
<input type="email" class="form-control" id="emailForCode" placeholder="请输入邮箱地址">
</div>
<!-- 邮箱验证码 -->
<div class="input-group">
<input type="text" class="form-control" id="verificationCode" placeholder="输入6位验证码" maxlength="6">
<button type="button" class="btn btn-outline-secondary" id="sendCodeBtn" onclick="sendVerificationCode()" disabled>
发送验证码
</button>
</div>
<div class="form-text mb-3">
<span id="codeStatus">请先验证数字验证码</span>
</div>
</div>
<!-- 数字验证码(所有登录方式通用,默认隐藏,输错密码后显示) -->
<div class="mb-3" id="captchaSection" style="display: none;">
<label class="form-label">数字验证码</label>
<div class="row g-2">
<div class="col-7">
<input type="text" class="form-control" id="captchaCode" placeholder="输入4位数字验证码" maxlength="4" inputmode="numeric" pattern="\d*">
</div>
<div class="col-5">
<div class="captcha-container" style="position: relative;">
<img id="captchaImage" src="" alt="数字验证码"
style="width: 100%; height: 38px; border: 1px solid #ddd; border-radius: 5px; cursor: pointer;"
onclick="refreshCaptcha()">
<div id="captchaLoading" class="text-center" style="display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
<div class="spinner-border spinner-border-sm" role="status"></div>
</div>
</div>
</div>
</div>
<div class="form-text">
<span id="captchaStatus">请输入4位数字验证码,点击图片可刷新</span>
</div>
</div>
<div id="errorAlert" class="alert alert-danger d-none" role="alert">
<i class="bi bi-exclamation-triangle-fill me-2"></i>
<span id="errorMessage"></span>
</div>
<button type="submit" class="btn btn-primary btn-login">
<span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
<span id="loginText">登录</span>
</button>
</form>
<!-- 注册链接 -->
<div id="registerSection" class="text-center mt-3">
<span class="text-muted">还没有账号?</span>
<a href="/register.html" class="text-decoration-none">
<i class="bi bi-person-plus me-1"></i>立即注册
</a>
</div>
</div>
</div>
<script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
<script>
const loginForm = document.getElementById('loginForm');
const errorAlert = document.getElementById('errorAlert');
const errorMessage = document.getElementById('errorMessage');
const loading = document.querySelector('.loading');
const loginText = document.getElementById('loginText');
function showError(message) {
errorMessage.textContent = message;
errorAlert.classList.remove('d-none');
}
function hideError() {
errorAlert.classList.add('d-none');
}
function setLoading(isLoading) {
if (isLoading) {
loading.classList.add('show');
loginText.textContent = '登录中...';
loginForm.querySelector('button').disabled = true;
} else {
loading.classList.remove('show');
loginText.textContent = '登录';
loginForm.querySelector('button').disabled = false;
}
}
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
hideError();
setLoading(true);
const loginType = document.querySelector('input[name="loginType"]:checked').value;
let loginData = {};
try {
if (captchaRequired && !captchaVerified) {
showError('请先验证数字验证码');
return;
}
if (loginType === 'username') {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (!username || !password) {
showError('请输入用户名和密码');
return;
}
loginData = { username, password };
} else if (loginType === 'email-password') {
const email = document.getElementById('emailForPassword').value;
const password = document.getElementById('emailPassword').value;
if (!email || !password) {
showError('请输入邮箱和密码');
return;
}
if (!validateEmail(email)) {
showError('请输入有效的邮箱地址');
return;
}
loginData = { email, password };
} else if (loginType === 'email-code') {
const email = document.getElementById('emailForCode').value;
const verificationCode = document.getElementById('verificationCode').value;
if (!email) {
showError('请输入邮箱地址');
return;
}
if (!validateEmail(email)) {
showError('请输入有效的邮箱地址');
return;
}
if (!verificationCode || verificationCode.length !== 6) {
showError('请输入6位验证码');
return;
}
loginData = { email, verification_code: verificationCode };
}
const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(loginData)
});
const result = await response.json();
if (result.success) {
// 保存token到localStorage
localStorage.setItem('auth_token', result.token);
// 保存用户信息到localStorage
const userInfo = {
user_id: result.user_id,
username: result.username,
is_admin: result.is_admin
};
localStorage.setItem('user_info', JSON.stringify(userInfo));
// 检查是否有重定向URL
const redirectUrl = localStorage.getItem('redirectAfterLogin');
if (redirectUrl) {
// 清除重定向URL
localStorage.removeItem('redirectAfterLogin');
// 跳转到原来的页面
window.location.href = redirectUrl;
} else {
// 默认跳转到管理页面
window.location.href = '/admin';
}
} else {
showError(result.message);
showCaptcha();
}
} catch (error) {
showError('登录失败,请检查网络连接');
} finally {
setLoading(false);
}
});
// 检查是否已经登录
const token = localStorage.getItem('auth_token');
if (token) {
// 验证token是否有效
fetch('/verify', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(result => {
if (result.authenticated) {
window.location.href = '/admin';
}
})
.catch(() => {
// token无效,清除
localStorage.removeItem('auth_token');
});
}
// 登录方式切换相关变量
let captchaVerified = false;
let captchaRequired = false;
let countdownTimer = null;
let countdownSeconds = 0;
let sessionId = generateSessionId();
// 生成会话ID
function generateSessionId() {
return 'session_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
}
// 登录方式切换
function switchLoginType() {
const loginType = document.querySelector('input[name="loginType"]:checked').value;
// 隐藏所有表单
document.querySelectorAll('.login-form-section').forEach(section => {
section.style.display = 'none';
});
// 显示对应表单
if (loginType === 'username') {
document.getElementById('usernameLoginForm').style.display = 'block';
} else if (loginType === 'email-password') {
document.getElementById('emailPasswordLoginForm').style.display = 'block';
} else if (loginType === 'email-code') {
document.getElementById('emailCodeLoginForm').style.display = 'block';
}
hideError();
}
// 显示验证码区域
function showCaptcha() {
const captchaSection = document.getElementById('captchaSection');
if (captchaSection.style.display === 'none') {
captchaSection.style.display = 'block';
captchaRequired = true;
loadCaptcha();
}
}
// 加载图形验证码
async function loadCaptcha() {
const captchaImage = document.getElementById('captchaImage');
const captchaLoading = document.getElementById('captchaLoading');
const captchaStatus = document.getElementById('captchaStatus');
captchaLoading.style.display = 'block';
captchaImage.style.display = 'none';
try {
const response = await fetch('/generate-captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ session_id: sessionId })
});
const result = await response.json();
if (result.success) {
captchaImage.src = result.captcha_image;
captchaStatus.textContent = '请输入4位数字验证码,点击图片可刷新';
captchaVerified = false;
updateSendCodeButton();
} else {
captchaStatus.textContent = '数字验证码加载失败,请刷新页面重试';
}
} catch (error) {
console.error('加载数字验证码失败:', error);
captchaStatus.textContent = '数字验证码加载失败,请检查网络连接';
} finally {
captchaLoading.style.display = 'none';
captchaImage.style.display = 'block';
}
}
// 刷新图形验证码
function refreshCaptcha() {
loadCaptcha();
}
// 验证图形验证码
async function verifyCaptcha() {
const captchaCode = document.getElementById('captchaCode').value.trim();
const captchaStatus = document.getElementById('captchaStatus');
if (!captchaCode) {
captchaStatus.textContent = '请输入4位数字验证码';
captchaVerified = false;
updateSendCodeButton();
return;
}
if (!/^\d{4}$/.test(captchaCode)) {
captchaStatus.innerHTML = '<span style="color: red;">请输入4位数字验证码</span>';
captchaVerified = false;
return;
}
try {
const response = await fetch('/verify-captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
session_id: sessionId,
captcha_code: captchaCode
})
});
const result = await response.json();
if (result.success) {
captchaStatus.innerHTML = '<span style="color: green;">✓ 数字验证码验证成功</span>';
captchaVerified = true;
} else {
captchaStatus.innerHTML = '<span style="color: red;">✗ 数字验证码错误,请重新输入</span>';
captchaVerified = false;
refreshCaptcha();
}
updateSendCodeButton();
} catch (error) {
console.error('验证数字验证码失败:', error);
captchaStatus.innerHTML = '<span style="color: red;">验证失败,请检查网络连接</span>';
captchaVerified = false;
updateSendCodeButton();
}
}
// 更新发送验证码按钮状态
function updateSendCodeButton() {
const sendCodeBtn = document.getElementById('sendCodeBtn');
const email = document.getElementById('emailForCode').value.trim();
const codeStatus = document.getElementById('codeStatus');
if (email && validateEmail(email)) {
sendCodeBtn.disabled = false;
if (captchaVerified) {
codeStatus.textContent = '数字验证码已验证,可以发送邮箱验证码';
} else {
codeStatus.textContent = '点击发送后将显示数字验证码';
}
} else {
sendCodeBtn.disabled = true;
if (!email) {
codeStatus.textContent = '请先输入邮箱地址';
} else if (!validateEmail(email)) {
codeStatus.textContent = '请输入有效的邮箱地址';
}
}
}
// 邮箱格式验证
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// 开始倒计时
function startCountdown() {
countdownSeconds = 60;
const sendCodeBtn = document.getElementById('sendCodeBtn');
const codeStatus = document.getElementById('codeStatus');
sendCodeBtn.disabled = true;
countdownTimer = setInterval(() => {
countdownSeconds--;
sendCodeBtn.textContent = `重新发送 (${countdownSeconds}s)`;
codeStatus.innerHTML = `<span class="countdown">验证码已发送,${countdownSeconds}秒后可重新发送</span>`;
if (countdownSeconds <= 0) {
clearInterval(countdownTimer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '发送验证码';
codeStatus.textContent = '可以重新发送验证码';
}
}, 1000);
}
// 发送邮箱验证码
async function sendVerificationCode() {
const email = document.getElementById('emailForCode').value.trim();
if (!email) {
showError('请先输入邮箱地址');
return;
}
if (!validateEmail(email)) {
showError('请输入有效的邮箱地址');
return;
}
if (!captchaVerified) {
showCaptcha();
return;
}
try {
const response = await fetch('/send-verification-code', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
type: 'login',
session_id: sessionId
})
});
const result = await response.json();
if (result.success) {
startCountdown();
} else {
showError(result.message);
}
} catch (error) {
console.error('发送验证码失败:', error);
showError('发送验证码失败,请检查网络连接');
}
}
// 检查注册状态
async function checkRegistrationStatus() {
try {
const response = await fetch('/registration-status');
if (response.ok) {
const data = await response.json();
const registerSection = document.getElementById('registerSection');
if (registerSection) {
registerSection.style.display = data.enabled ? 'block' : 'none';
}
}
} catch (error) {
console.error('检查注册状态失败:', error);
// 出错时默认显示注册链接
}
}
// 事件监听器
document.addEventListener('DOMContentLoaded', function() {
// 检查注册状态
checkRegistrationStatus();
// 登录方式切换
document.querySelectorAll('input[name="loginType"]').forEach(radio => {
radio.addEventListener('change', switchLoginType);
});
// 数字验证码输入框事件
const captchaCodeInput = document.getElementById('captchaCode');
if (captchaCodeInput) {
captchaCodeInput.addEventListener('input', function() {
// 只允许数字输入
this.value = this.value.replace(/\D/g, '');
if (this.value.length === 4) {
verifyCaptcha();
} else {
captchaVerified = false;
updateSendCodeButton();
document.getElementById('captchaStatus').textContent = '请输入4位数字验证码';
}
});
}
// 邮箱输入框事件
const emailForCodeInput = document.getElementById('emailForCode');
if (emailForCodeInput) {
emailForCodeInput.addEventListener('input', updateSendCodeButton);
}
});
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

+576
View File
@@ -0,0 +1,576 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户注册 - 闲鱼自动回复系统</title>
<link rel="stylesheet" href="/static/lib/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="/static/lib/bootstrap-icons/bootstrap-icons.css">
<style>
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
}
.register-container {
background: white;
border-radius: 12px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
overflow: hidden;
max-width: 420px;
width: 100%;
max-height: 95vh;
overflow-y: auto;
}
.register-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1.2rem;
text-align: center;
}
.register-header h2 {
margin-bottom: 0.3rem;
font-size: 1.4rem;
}
.register-header p {
margin-bottom: 0;
font-size: 0.85rem;
}
.register-body {
padding: 1.2rem;
}
.form-control {
border-radius: 8px;
border: 1px solid #e9ecef;
padding: 8px 12px;
transition: all 0.3s ease;
font-size: 0.9rem;
}
.form-control:focus {
border-color: #667eea;
box-shadow: 0 0 0 0.15rem rgba(102, 126, 234, 0.2);
}
.btn-register {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 8px;
padding: 10px;
font-weight: 600;
transition: all 0.3s ease;
font-size: 0.9rem;
}
.btn-register:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.btn-code {
border-radius: 8px;
border: 1px solid #667eea;
color: #667eea;
font-weight: 600;
transition: all 0.3s ease;
padding: 8px 12px;
font-size: 0.85rem;
}
.btn-code:hover {
background: #667eea;
color: white;
}
.btn-code:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.login-link {
text-align: center;
margin-top: 0.8rem;
}
.login-link a {
color: #667eea;
text-decoration: none;
font-weight: 600;
font-size: 0.9rem;
}
.login-link a:hover {
text-decoration: underline;
}
.alert {
border-radius: 8px;
border: none;
padding: 0.6rem 1rem;
font-size: 0.85rem;
}
.input-group {
margin-bottom: 0.8rem;
}
.countdown {
color: #6c757d;
font-size: 0.8rem;
}
.mb-3 {
margin-bottom: 0.8rem !important;
}
.form-label {
margin-bottom: 0.3rem;
font-weight: 600;
font-size: 0.85rem;
color: #495057;
}
.form-text {
margin-top: 0.2rem;
font-size: 0.75rem;
}
.captcha-container img {
height: 32px !important;
}
/* 响应式优化 */
@media (max-height: 700px) {
.register-header {
padding: 1rem;
}
.register-header h2 {
font-size: 1.2rem;
margin-bottom: 0.2rem;
}
.register-header p {
font-size: 0.8rem;
}
.register-body {
padding: 1rem;
}
.mb-3 {
margin-bottom: 0.6rem !important;
}
.form-control {
padding: 6px 10px;
}
.btn-code {
padding: 6px 10px;
font-size: 0.8rem;
}
}
@media (max-width: 480px) {
.register-container {
margin: 5px;
max-width: none;
}
.row.g-2 > * {
padding-left: 0.25rem;
padding-right: 0.25rem;
}
}
</style>
</head>
<body>
<div class="register-container">
<div class="register-header">
<h2 class="mb-0">
<i class="bi bi-person-plus-fill me-2"></i>
用户注册
</h2>
<p class="mb-0 mt-2 opacity-75">创建您的闲鱼自动回复账号</p>
</div>
<div class="register-body">
<div id="alertContainer"></div>
<form id="registerForm">
<div class="mb-3">
<label for="username" class="form-label">
<i class="bi bi-person me-1"></i>用户名
</label>
<input type="text" class="form-control" id="username" name="username"
placeholder="3-20个字符,支持字母、数字、下划线" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">
<i class="bi bi-envelope me-1"></i>邮箱地址
</label>
<input type="email" class="form-control" id="email" name="email"
placeholder="用于接收验证码和重要通知" required>
</div>
<div class="mb-3">
<label for="captchaCode" class="form-label">
<i class="bi bi-shield-lock me-1"></i>数字验证码
</label>
<div class="row g-2">
<div class="col-7">
<input type="text" class="form-control" id="captchaCode" name="captchaCode"
placeholder="输入4位数字验证码" maxlength="4" inputmode="numeric" pattern="\d*" required>
</div>
<div class="col-5">
<div class="captcha-container" style="position: relative;">
<img id="captchaImage" src="" alt="数字验证码"
style="width: 100%; height: 32px; border: 1px solid #ddd; border-radius: 5px; cursor: pointer;"
onclick="refreshCaptcha()">
<div id="captchaLoading" class="text-center" style="display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
<div class="spinner-border spinner-border-sm" role="status"></div>
</div>
</div>
</div>
</div>
<div class="form-text">
<span id="captchaStatus">请输入4位数字验证码,点击图片可刷新</span>
</div>
</div>
<div class="mb-3">
<label for="verificationCode" class="form-label">
<i class="bi bi-shield-check me-1"></i>邮箱验证码
</label>
<div class="input-group">
<input type="text" class="form-control" id="verificationCode" name="verificationCode"
placeholder="输入6位验证码" maxlength="6" required>
<button type="button" class="btn btn-code" id="sendCodeBtn" onclick="sendVerificationCode()" disabled>
发送验证码
</button>
</div>
<div class="form-text">
<span id="codeStatus">请先验证数字验证码</span>
</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">
<i class="bi bi-lock me-1"></i>设置密码
</label>
<input type="password" class="form-control" id="password" name="password"
placeholder="至少6个字符" required>
</div>
<div class="mb-3">
<label for="confirmPassword" class="form-label">
<i class="bi bi-lock-fill me-1"></i>确认密码
</label>
<input type="password" class="form-control" id="confirmPassword" name="confirmPassword"
placeholder="再次输入密码" required>
</div>
<button type="submit" class="btn btn-register btn-primary w-100 mt-2">
<i class="bi bi-person-plus me-1"></i>立即注册
</button>
</form>
<div class="login-link">
<span class="text-muted">已有账号?</span>
<a href="/login.html">立即登录</a>
</div>
</div>
</div>
<script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
<script>
let countdownTimer = null;
let countdownSeconds = 0;
let sessionId = generateSessionId();
let captchaVerified = false;
function generateSessionId() {
return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
function showAlert(message, type = 'danger') {
const alertContainer = document.getElementById('alertContainer');
const alertHtml = `
<div class="alert alert-${type} alert-dismissible fade show" role="alert">
<i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}-fill me-2"></i>
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
`;
alertContainer.innerHTML = alertHtml;
}
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
async function loadCaptcha() {
const captchaImage = document.getElementById('captchaImage');
const captchaLoading = document.getElementById('captchaLoading');
const captchaStatus = document.getElementById('captchaStatus');
try {
captchaLoading.style.display = 'block';
captchaImage.style.display = 'none';
const response = await fetch('/generate-captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ session_id: sessionId })
});
const result = await response.json();
if (result.success) {
captchaImage.src = result.captcha_image;
captchaStatus.textContent = '请输入4位数字验证码,点击图片可刷新';
captchaVerified = false;
updateSendCodeButton();
} else {
captchaStatus.textContent = '数字验证码加载失败,请刷新页面重试';
}
} catch (error) {
console.error('加载数字验证码失败:', error);
captchaStatus.textContent = '数字验证码加载失败,请检查网络连接';
} finally {
captchaLoading.style.display = 'none';
captchaImage.style.display = 'block';
}
}
function refreshCaptcha() {
sessionId = generateSessionId(); // 生成新的session ID
loadCaptcha();
// 不再自动清空验证码输入框,让用户自己决定是否清空
}
async function verifyCaptcha() {
const captchaCode = document.getElementById('captchaCode').value.trim();
const captchaStatus = document.getElementById('captchaStatus');
if (!captchaCode) {
captchaStatus.textContent = '请输入4位数字验证码';
captchaVerified = false;
updateSendCodeButton();
return;
}
if (!/^\d{4}$/.test(captchaCode)) {
captchaStatus.innerHTML = '<span style="color: red;">请输入4位数字验证码</span>';
captchaVerified = false;
return;
}
try {
const response = await fetch('/verify-captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
session_id: sessionId,
captcha_code: captchaCode
})
});
const result = await response.json();
if (result.success) {
captchaStatus.innerHTML = '<span style="color: green;">✓ 数字验证码验证成功</span>';
captchaVerified = true;
} else {
captchaStatus.innerHTML = '<span style="color: red;">✗ 数字验证码错误,请重新输入</span>';
captchaVerified = false;
refreshCaptcha();
}
updateSendCodeButton();
} catch (error) {
console.error('验证数字验证码失败:', error);
captchaStatus.innerHTML = '<span style="color: red;">验证失败,请检查网络连接</span>';
captchaVerified = false;
updateSendCodeButton();
}
}
function updateSendCodeButton() {
const sendCodeBtn = document.getElementById('sendCodeBtn');
const email = document.getElementById('email').value.trim();
const codeStatus = document.getElementById('codeStatus');
if (captchaVerified && email && validateEmail(email)) {
sendCodeBtn.disabled = false;
codeStatus.textContent = '数字验证码已验证,可以发送邮箱验证码';
} else {
sendCodeBtn.disabled = true;
if (!captchaVerified) {
codeStatus.textContent = '请先验证数字验证码';
} else if (!email) {
codeStatus.textContent = '请先输入邮箱地址';
} else if (!validateEmail(email)) {
codeStatus.textContent = '请输入有效的邮箱地址';
}
}
}
function startCountdown() {
countdownSeconds = 60;
const sendCodeBtn = document.getElementById('sendCodeBtn');
const codeStatus = document.getElementById('codeStatus');
sendCodeBtn.disabled = true;
countdownTimer = setInterval(() => {
countdownSeconds--;
sendCodeBtn.textContent = `重新发送 (${countdownSeconds}s)`;
codeStatus.innerHTML = `<span class="countdown">验证码已发送,${countdownSeconds}秒后可重新发送</span>`;
if (countdownSeconds <= 0) {
clearInterval(countdownTimer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '发送验证码';
codeStatus.textContent = '可以重新发送验证码';
}
}, 1000);
}
async function sendVerificationCode() {
const email = document.getElementById('email').value.trim();
if (!captchaVerified) {
showAlert('请先验证数字验证码');
return;
}
if (!email) {
showAlert('请先输入邮箱地址');
return;
}
if (!validateEmail(email)) {
showAlert('请输入有效的邮箱地址');
return;
}
try {
const response = await fetch('/send-verification-code', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
session_id: sessionId
})
});
const result = await response.json();
if (result.success) {
showAlert(result.message, 'success');
startCountdown();
} else {
showAlert(result.message);
}
} catch (error) {
console.error('发送验证码失败:', error);
showAlert('发送验证码失败,请检查网络连接');
}
}
document.getElementById('registerForm').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(this);
const username = formData.get('username').trim();
const email = formData.get('email').trim();
const captchaCode = formData.get('captchaCode').trim();
const verificationCode = formData.get('verificationCode').trim();
const password = formData.get('password');
const confirmPassword = formData.get('confirmPassword');
// 前端验证
if (!captchaVerified) {
showAlert('请先验证数字验证码');
return;
}
if (username.length < 3 || username.length > 20) {
showAlert('用户名长度必须在3-20个字符之间');
return;
}
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
showAlert('用户名只能包含字母、数字和下划线');
return;
}
if (!validateEmail(email)) {
showAlert('请输入有效的邮箱地址');
return;
}
if (verificationCode.length !== 6) {
showAlert('请输入6位验证码');
return;
}
if (password.length < 6) {
showAlert('密码长度至少6个字符');
return;
}
if (password !== confirmPassword) {
showAlert('两次输入的密码不一致');
return;
}
try {
const response = await fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
email: email,
verification_code: verificationCode,
password: password
})
});
const result = await response.json();
if (result.success) {
showAlert(result.message, 'success');
setTimeout(() => {
window.location.href = '/login.html';
}, 2000);
} else {
showAlert(result.message);
}
} catch (error) {
console.error('注册失败:', error);
showAlert('注册失败,请检查网络连接');
}
});
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
loadCaptcha();
});
// 数字验证码输入框事件
document.getElementById('captchaCode').addEventListener('input', function() {
this.value = this.value.replace(/\D/g, '');
if (this.value.length === 4) {
verifyCaptcha();
} else {
captchaVerified = false;
updateSendCodeButton();
document.getElementById('captchaStatus').textContent = '请输入4位数字验证码';
}
});
// 邮箱输入框事件
document.getElementById('email').addEventListener('input', function() {
updateSendCodeButton();
});
document.getElementById('email').addEventListener('blur', function() {
const email = this.value.trim();
updateSendCodeButton();
});
</script>
</body>
</html>
+400
View File
@@ -0,0 +1,400 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户管理 - 闲鱼自动回复系统</title>
<link href="/static/lib/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="/static/lib/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<style>
.admin-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem 0;
margin-bottom: 2rem;
}
.user-card {
transition: transform 0.2s;
border: 1px solid #e0e0e0;
}
.user-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.stats-card {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
border: none;
}
.btn-danger-custom {
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
border: none;
}
.btn-danger-custom:hover {
background: linear-gradient(135deg, #ee5a52 0%, #ff6b6b 100%);
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="/">
<i class="bi bi-robot"></i> 闲鱼自动回复系统
</a>
<div class="navbar-nav ms-auto">
<a class="nav-link" href="/">
<i class="bi bi-house"></i> 首页
</a>
<a class="nav-link active" href="/user_management.html">
<i class="bi bi-people"></i> 用户管理
</a>
<a class="nav-link" href="/data_management.html">
<i class="bi bi-database"></i> 数据管理
</a>
<a class="nav-link" href="/log_management.html">
<i class="bi bi-file-text"></i> 日志管理
</a>
<a class="nav-link" href="#" onclick="logout()">
<i class="bi bi-box-arrow-right"></i> 退出
</a>
</div>
</div>
</nav>
<!-- 管理员标题 -->
<div class="admin-header">
<div class="container">
<h1 class="mb-0">
<i class="bi bi-people"></i> 用户管理
</h1>
<p class="mb-0 mt-2">管理系统中的所有用户账号</p>
</div>
</div>
<div class="container">
<!-- 统计信息 -->
<div class="row mb-4">
<div class="col-md-3">
<div class="card stats-card">
<div class="card-body text-center">
<h3 id="totalUsers">-</h3>
<p class="mb-0">总用户数</p>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-info text-white">
<div class="card-body text-center">
<h3 id="totalCookies">-</h3>
<p class="mb-0">总Cookie数</p>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-success text-white">
<div class="card-body text-center">
<h3 id="totalCards">-</h3>
<p class="mb-0">总卡券数</p>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-warning text-white">
<div class="card-body text-center">
<h3 id="systemUptime">运行中</h3>
<p class="mb-0">系统状态</p>
</div>
</div>
</div>
</div>
<!-- 用户列表 -->
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="bi bi-people-fill"></i> 用户列表
</h5>
<button class="btn btn-primary" onclick="refreshUsers()">
<i class="bi bi-arrow-clockwise"></i> 刷新
</button>
</div>
<div class="card-body">
<div id="loadingUsers" class="text-center py-4">
<div class="spinner-border" role="status">
<span class="visually-hidden">加载中...</span>
</div>
<p class="mt-2">正在加载用户信息...</p>
</div>
<div id="usersList" class="row" style="display: none;"></div>
<div id="noUsers" class="text-center py-4" style="display: none;">
<i class="bi bi-people" style="font-size: 3rem; color: #ccc;"></i>
<p class="mt-2 text-muted">暂无用户</p>
</div>
</div>
</div>
</div>
<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteUserModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-exclamation-triangle text-warning"></i> 确认删除
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<p>您确定要删除用户 <strong id="deleteUserName"></strong> 吗?</p>
<div class="alert alert-warning">
<i class="bi bi-exclamation-triangle"></i>
<strong>警告:</strong>此操作将删除该用户的所有数据,包括:
<ul class="mt-2 mb-0">
<li>所有Cookie账号</li>
<li>所有卡券</li>
<li>所有关键字和回复设置</li>
<li>所有个人设置</li>
</ul>
<p class="mt-2 mb-0"><strong>此操作不可恢复!</strong></p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger-custom" onclick="confirmDeleteUser()">
<i class="bi bi-trash"></i> 确认删除
</button>
</div>
</div>
</div>
</div>
<script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
<script>
let currentDeleteUserId = null;
let deleteUserModal = null;
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 检查管理员权限
checkAdminPermission();
// 初始化模态框
deleteUserModal = new bootstrap.Modal(document.getElementById('deleteUserModal'));
// 加载数据
loadSystemStats();
loadUsers();
});
// 检查管理员权限
function checkAdminPermission() {
const token = localStorage.getItem('auth_token');
if (!token) {
alert('请先登录');
window.location.href = '/login.html';
return;
}
// 验证token并检查是否为管理员
fetch('/verify', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
if (!data.authenticated) {
alert('登录已过期,请重新登录');
window.location.href = '/login.html';
return;
}
// 检查是否为管理员
if (data.username !== 'admin') {
alert('此功能仅限管理员使用');
window.location.href = '/';
return;
}
})
.catch(error => {
console.error('权限验证失败:', error);
alert('权限验证失败');
window.location.href = '/login.html';
});
}
// 加载系统统计信息
function loadSystemStats() {
const token = localStorage.getItem('auth_token');
fetch('/admin/stats', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
document.getElementById('totalUsers').textContent = data.users.total;
document.getElementById('totalCookies').textContent = data.cookies.total;
document.getElementById('totalCards').textContent = data.cards.total;
})
.catch(error => {
console.error('加载统计信息失败:', error);
});
}
// 加载用户列表
function loadUsers() {
const token = localStorage.getItem('auth_token');
const loadingDiv = document.getElementById('loadingUsers');
const usersListDiv = document.getElementById('usersList');
const noUsersDiv = document.getElementById('noUsers');
loadingDiv.style.display = 'block';
usersListDiv.style.display = 'none';
noUsersDiv.style.display = 'none';
fetch('/admin/users', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
loadingDiv.style.display = 'none';
if (data.users && data.users.length > 0) {
displayUsers(data.users);
usersListDiv.style.display = 'block';
} else {
noUsersDiv.style.display = 'block';
}
})
.catch(error => {
console.error('加载用户列表失败:', error);
loadingDiv.style.display = 'none';
noUsersDiv.style.display = 'block';
alert('加载用户列表失败');
});
}
// 显示用户列表
function displayUsers(users) {
const usersListDiv = document.getElementById('usersList');
usersListDiv.innerHTML = '';
users.forEach(user => {
const userCard = createUserCard(user);
usersListDiv.appendChild(userCard);
});
}
// 创建用户卡片
function createUserCard(user) {
const col = document.createElement('div');
col.className = 'col-md-6 col-lg-4 mb-3';
const isAdmin = user.username === 'admin';
const badgeClass = isAdmin ? 'bg-danger' : 'bg-primary';
const badgeText = isAdmin ? '管理员' : '普通用户';
col.innerHTML = `
<div class="card user-card h-100">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start mb-2">
<h6 class="card-title mb-0">
<i class="bi bi-person-circle"></i> ${user.username}
</h6>
<span class="badge ${badgeClass}">${badgeText}</span>
</div>
<p class="card-text text-muted small mb-2">
<i class="bi bi-envelope"></i> ${user.email}
</p>
<div class="row text-center mb-3">
<div class="col">
<small class="text-muted">Cookie数</small>
<div class="fw-bold">${user.cookie_count || 0}</div>
</div>
<div class="col">
<small class="text-muted">卡券数</small>
<div class="fw-bold">${user.card_count || 0}</div>
</div>
</div>
<div class="text-muted small mb-2">
<i class="bi bi-calendar"></i> 注册时间:${formatDate(user.created_at)}
</div>
${!isAdmin ? `
<div class="d-grid">
<button class="btn btn-danger-custom btn-sm" onclick="deleteUser(${user.id}, '${user.username}')">
<i class="bi bi-trash"></i> 删除用户
</button>
</div>
` : `
<div class="text-center">
<small class="text-muted">
<i class="bi bi-shield-check"></i> 管理员账号不可删除
</small>
</div>
`}
</div>
</div>
`;
return col;
}
// 格式化日期
function formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
}
// 删除用户
function deleteUser(userId, username) {
currentDeleteUserId = userId;
document.getElementById('deleteUserName').textContent = username;
deleteUserModal.show();
}
// 确认删除用户
function confirmDeleteUser() {
if (!currentDeleteUserId) return;
const token = localStorage.getItem('auth_token');
fetch(`/admin/users/${currentDeleteUserId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
deleteUserModal.hide();
alert(data.message || '用户删除成功');
// 刷新页面数据
loadSystemStats();
loadUsers();
})
.catch(error => {
console.error('删除用户失败:', error);
alert('删除用户失败');
});
}
// 刷新用户列表
function refreshUsers() {
loadSystemStats();
loadUsers();
}
// 退出登录
function logout() {
localStorage.removeItem('auth_token');
window.location.href = '/login.html';
}
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

+568
View File
@@ -0,0 +1,568 @@
const crypto = require('crypto')
const generate_mid = () => {
return "" + Math.floor(1e3 * Math.random()) + new Date().getTime() + " 0"
}
const generate_uuid = () => {
return "-" + Date.now() + "1"
}
const generate_device_id = (user_id) => {
for (var ee, et = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""), en = [], eo = Math.random, ei = 0; ei < 36; ei++)
8 === ei || 13 === ei || 18 === ei || 23 === ei ? en[ei] = "-" : 14 === ei ? en[ei] = "4" : (ee = 0 | 16 * eo(),
en[ei] = et[19 === ei ? 3 & ee | 8 : ee]);
return en.join("") + "-" + user_id
}
const generate_sign = (t, token, data) => {
const j = t
const h = 34839810
const msg = token + "&" + j + "&" + h + "&" + data
const md5 = crypto.createHash('md5')
md5.update(msg)
return md5.digest('hex')
}
eM = new TextDecoder("utf-8");
eL = null
var sv = Array(4096);
function sg() {
var ee, et = eI[aG++];
if (!(et >= 160) || !(et < 192))
return aG--,
sy(a5());
if (et -= 160,
aX >= aG)
return eR.slice(aG - aq, (aG += et) - aq);
if (!(0 == aX && eO < 180))
return se(et);
var en = (et << 5 ^ (et > 1 ? eZ.getUint16(aG) : et > 0 ? eI[aG] : 0)) & 4095
, eo = sv[en]
, ei = aG
, ec = aG + et - 3
, eu = 0;
if (eo && eo.bytes == et) {
for (; ei < ec;) {
if ((ee = eZ.getUint32(ei)) != eo[eu++]) {
ei = 1879048192;
break
}
ei += 4
}
for (ec += 3; ei < ec;)
if ((ee = eI[ei++]) != eo[eu++]) {
ei = 1879048192;
break
}
if (ei === ec)
return aG = ei,
eo.string;
ec -= 3,
ei = aG
}
for (eo = [],
sv[en] = eo,
eo.bytes = et; ei < ec;)
ee = eZ.getUint32(ei),
eo.push(ee),
ei += 4;
for (ec += 3; ei < ec;)
ee = eI[ei++],
eo.push(ee);
var ed = et < 16 ? su(et) : sl(et);
return null != ed ? eo.string = ed : eo.string = se(et)
}
function sy(ee) {
if ("string" == typeof ee)
return ee;
if ("number" == typeof ee || "boolean" == typeof ee || "bigint" == typeof ee)
return ee.toString();
if (null == ee)
return ee + "";
throw Error("Invalid property type for record", typeof ee)
}
r9 = function (ee) {
return atob(rW(ee))
}
rW = function (ee) {
return ee.replace(/[^A-Za-z0-9\+\/]/g, "")
}
aW = {
"useRecords": false,
"mapsAsObjects": true
}
aJ = false
eP = []
function a3(ee) {
if (!aW.trusted && !aJ) {
var et, en, eo = eP.sharedLength || 0;
eo < eP.length && (eP.length = eo)
}
if (aW.randomAccessStructure && eI[aG] < 64 && eI[aG] >= 32 && ej ? (et = ej(eI, aG, eO, aW),
eI = null,
!(ee && ee.lazy) && et && (et = et.toJSON()),
aG = eO) : et = a5(),
eD && (aG = eD.postBundlePosition,
eD = null),
aJ && (eP.restoreStructures = null),
aG == eO)
eP && eP.restoreStructures && a4(),
eP = null,
eI = null,
eL && (eL = null);
else if (aG > eO)
throw Error("Unexpected end of MessagePack data");
else if (!aJ) {
try {
en = JSON.stringify(et, function (ee, et) {
return "bigint" == typeof et ? "".concat(et, "n") : et
}).slice(0, 100)
} catch (ee) {
en = "(JSON view not available " + ee + ")"
}
throw Error("Data read, but end of buffer not reached " + en)
}
return et
}
function so(ee) {
if (ee < 16 && (et = su(ee)))
return et;
if (ee > 64 && eM)
return eM.decode(eI.subarray(aG, aG += ee));
var et, en = aG + ee, eo = [];
for (et = ""; aG < en;) {
var ei = eI[aG++];
if ((128 & ei) === 0)
eo.push(ei);
else if ((224 & ei) === 192) {
var ec = 63 & eI[aG++];
eo.push((31 & ei) << 6 | ec)
} else if ((240 & ei) === 224) {
var eu = 63 & eI[aG++]
, ed = 63 & eI[aG++];
eo.push((31 & ei) << 12 | eu << 6 | ed)
} else if ((248 & ei) === 240) {
var ef = (7 & ei) << 18 | (63 & eI[aG++]) << 12 | (63 & eI[aG++]) << 6 | 63 & eI[aG++];
ef > 65535 && (ef -= 65536,
eo.push(ef >>> 10 & 1023 | 55296),
ef = 56320 | 1023 & ef),
eo.push(ef)
} else
eo.push(ei);
eo.length >= 4096 && (et += sc.apply(String, eo),
eo.length = 0)
}
return eo.length > 0 && (et += sc.apply(String, eo)),
et
}
se = so;
var sc = String.fromCharCode;
function sl(ee) {
for (var et = aG, en = Array(ee), eo = 0; eo < ee; eo++) {
var ei = eI[aG++];
if ((128 & ei) > 0) {
aG = et;
return
}
en[eo] = ei
}
return sc.apply(String, en)
}
function su(ee) {
if (ee < 4) {
if (ee < 2) {
if (0 === ee)
return "";
var et = eI[aG++];
if ((128 & et) > 1) {
aG -= 1;
return
}
return sc(et)
}
var en = eI[aG++]
, eo = eI[aG++];
if ((128 & en) > 0 || (128 & eo) > 0) {
aG -= 2;
return
}
if (ee < 3)
return sc(en, eo);
var ei = eI[aG++];
if ((128 & ei) > 0) {
aG -= 3;
return
}
return sc(en, eo, ei)
}
var ec = eI[aG++]
, eu = eI[aG++]
, ed = eI[aG++]
, ef = eI[aG++];
if ((128 & ec) > 0 || (128 & eu) > 0 || (128 & ed) > 0 || (128 & ef) > 0) {
aG -= 4;
return
}
if (ee < 6) {
if (4 === ee)
return sc(ec, eu, ed, ef);
var ep = eI[aG++];
if ((128 & ep) > 0) {
aG -= 5;
return
}
return sc(ec, eu, ed, ef, ep)
}
if (ee < 8) {
var em = eI[aG++]
, eh = eI[aG++];
if ((128 & em) > 0 || (128 & eh) > 0) {
aG -= 6;
return
}
if (ee < 7)
return sc(ec, eu, ed, ef, em, eh);
var ev = eI[aG++];
if ((128 & ev) > 0) {
aG -= 7;
return
}
return sc(ec, eu, ed, ef, em, eh, ev)
}
var eg = eI[aG++]
, eC = eI[aG++]
, eS = eI[aG++]
, ew = eI[aG++];
if ((128 & eg) > 0 || (128 & eC) > 0 || (128 & eS) > 0 || (128 & ew) > 0) {
aG -= 8;
return
}
if (ee < 10) {
if (8 === ee)
return sc(ec, eu, ed, ef, eg, eC, eS, ew);
var eE = eI[aG++];
if ((128 & eE) > 0) {
aG -= 9;
return
}
return sc(ec, eu, ed, ef, eg, eC, eS, ew, eE)
}
if (ee < 12) {
var ek = eI[aG++]
, e_ = eI[aG++];
if ((128 & ek) > 0 || (128 & e_) > 0) {
aG -= 10;
return
}
if (ee < 11)
return sc(ec, eu, ed, ef, eg, eC, eS, ew, ek, e_);
var eT = eI[aG++];
if ((128 & eT) > 0) {
aG -= 11;
return
}
return sc(ec, eu, ed, ef, eg, eC, eS, ew, ek, e_, eT)
}
var eN = eI[aG++]
, eM = eI[aG++]
, eO = eI[aG++]
, eP = eI[aG++];
if ((128 & eN) > 0 || (128 & eM) > 0 || (128 & eO) > 0 || (128 & eP) > 0) {
aG -= 12;
return
}
if (ee < 14) {
if (12 === ee)
return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP);
var eR = eI[aG++];
if ((128 & eR) > 0) {
aG -= 13;
return
}
return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP, eR)
}
var eD = eI[aG++]
, eL = eI[aG++];
if ((128 & eD) > 0 || (128 & eL) > 0) {
aG -= 14;
return
}
if (ee < 15)
return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP, eD, eL);
var eZ = eI[aG++];
if ((128 & eZ) > 0) {
aG -= 15;
return
}
return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP, eD, eL, eZ)
}
function ss(ee) {
if (aW.mapsAsObjects) {
for (var et = {}, en = 0; en < ee; en++) {
var eo = sg();
"__proto__" === eo && (eo = "__proto_"),
et[eo] = a5()
}
return et
}
for (var ei = new Map, ec = 0; ec < ee; ec++)
ei.set(a5(), a5());
return ei
}
function a5() {
var ee, et = eI[aG++];
if (et < 160) {
if (et < 128) {
if (et < 64)
return et;
var en = eP[63 & et] || aW.getStructures && a9()[63 & et];
return en ? (en.read || (en.read = a8(en, 63 & et)),
en.read()) : et
}
if (et < 144) {
if (et -= 128,
aW.mapsAsObjects) {
for (var eo = {}, ei = 0; ei < et; ei++) {
var ec = sg();
"__proto__" === ec && (ec = "__proto_"),
eo[ec] = a5()
}
return eo
}
for (var eu = new Map, ed = 0; ed < et; ed++)
eu.set(a5(), a5());
return eu
}
for (var ef = Array(et -= 144), ep = 0; ep < et; ep++)
ef[ep] = a5();
return aW.freezeData ? Object.freeze(ef) : ef
}
if (et < 192) {
var em = et - 160;
if (aX >= aG)
return eR.slice(aG - aq, (aG += em) - aq);
if (0 == aX && eO < 140) {
var eh = em < 16 ? su(em) : sl(em);
if (null != eh)
return eh
}
return se(em)
}
switch (et) {
case 192:
return null;
case 193:
if (eD) {
if ((ee = a5()) > 0)
return eD[1].slice(eD.position1, eD.position1 += ee);
return eD[0].slice(eD.position0, eD.position0 -= ee)
}
return aY;
case 194:
return !1;
case 195:
return !0;
case 196:
if (void 0 === (ee = eI[aG++]))
throw Error("Unexpected end of buffer");
return sm(ee);
case 197:
return ee = eZ.getUint16(aG),
aG += 2,
sm(ee);
case 198:
return ee = eZ.getUint32(aG),
aG += 4,
sm(ee);
case 199:
return sh(eI[aG++]);
case 200:
return ee = eZ.getUint16(aG),
aG += 2,
sh(ee);
case 201:
return ee = eZ.getUint32(aG),
aG += 4,
sh(ee);
case 202:
if (ee = eZ.getFloat32(aG),
aW.useFloat32 > 2) {
var ev = sT[(127 & eI[aG]) << 1 | eI[aG + 1] >> 7];
return aG += 4,
(ev * ee + (ee > 0 ? .5 : -.5) >> 0) / ev
}
return aG += 4,
ee;
case 203:
return ee = eZ.getFloat64(aG),
aG += 8,
ee;
case 204:
return eI[aG++];
case 205:
return ee = eZ.getUint16(aG),
aG += 2,
ee;
case 206:
return ee = eZ.getUint32(aG),
aG += 4,
ee;
case 207:
return "number" === aW.int64AsType ? ee = 4294967296 * eZ.getUint32(aG) + eZ.getUint32(aG + 4) : "string" === aW.int64AsType ? ee = eZ.getBigUint64(aG).toString() : "auto" === aW.int64AsType ? (ee = eZ.getBigUint64(aG)) <= BigInt(2) << BigInt(52) && (ee = Number(ee)) : ee = eZ.getBigUint64(aG),
aG += 8,
ee;
case 208:
return eZ.getInt8(aG++);
case 209:
return ee = eZ.getInt16(aG),
aG += 2,
ee;
case 210:
return ee = eZ.getInt32(aG),
aG += 4,
ee;
case 211:
return "number" === aW.int64AsType ? ee = 4294967296 * eZ.getInt32(aG) + eZ.getUint32(aG + 4) : "string" === aW.int64AsType ? ee = eZ.getBigInt64(aG).toString() : "auto" === aW.int64AsType ? (ee = eZ.getBigInt64(aG)) >= BigInt(-2) << BigInt(52) && ee <= BigInt(2) << BigInt(52) && (ee = Number(ee)) : ee = eZ.getBigInt64(aG),
aG += 8,
ee;
case 212:
if (114 == (ee = eI[aG++]))
return sC(63 & eI[aG++]);
var eg = aK[ee];
if (eg) {
if (eg.read)
return aG++,
eg.read(a5());
if (eg.noBuffer)
return aG++,
eg();
return eg(eI.subarray(aG, ++aG))
}
throw Error("Unknown extension " + ee);
case 213:
if (114 == (ee = eI[aG]))
return aG++,
sC(63 & eI[aG++], eI[aG++]);
return sh(2);
case 214:
return sh(4);
case 215:
return sh(8);
case 216:
return sh(16);
case 217:
if (ee = eI[aG++],
aX >= aG)
return eR.slice(aG - aq, (aG += ee) - aq);
return st(ee);
case 218:
if (ee = eZ.getUint16(aG),
aG += 2,
aX >= aG)
return eR.slice(aG - aq, (aG += ee) - aq);
return sn(ee);
case 219:
if (ee = eZ.getUint32(aG),
aG += 4,
aX >= aG)
return eR.slice(aG - aq, (aG += ee) - aq);
return sr(ee);
case 220:
return ee = eZ.getUint16(aG),
aG += 2,
si(ee);
case 221:
return ee = eZ.getUint32(aG),
aG += 4,
si(ee);
case 222:
return ee = eZ.getUint16(aG),
aG += 2,
ss(ee);
case 223:
return ee = eZ.getUint32(aG),
aG += 4,
ss(ee);
default:
if (et >= 224)
return et - 256;
if (void 0 === et) {
var eC = Error("Unexpected end of MessagePack data");
throw eC.incomplete = !0,
eC
}
throw Error("Unknown MessagePack token " + et)
}
}
sn = so
var a6 = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
const decrypt = (ee) => {
for (var et, en, eo = r9(ee), ei = eo.length, ec = new Uint8Array(ei), eu = 0; eu < ei; eu++) {
var ed = eo.charCodeAt(eu);
ec[eu] = ed
}
en = {}
et = ec;
et.buffer || et.constructor !== ArrayBuffer || (et = "undefined" != typeof Buffer ? Buffer.from(et) : new Uint8Array(et)),
"object" == typeof en ? (eO = en.end || et.length,
aG = en.start || 0) : (aG = 0,
eO = en > -1 ? en : et.length),
aX = 0,
eR = null,
eD = null,
eI = et;
eM = new TextDecoder("utf-8");
eL = null
eP = [];
eZ = et.dataView || (et.dataView = new DataView(et.buffer, et.byteOffset, et.byteLength))
res = a3(en)
// ec = ecc;
// rA = 0;
// rB = 0;
// ed = [];
// eu = ec.length;
// rj = {
// "useRecords": false,
// "mapsAsObjects": true
// }
// // ei 是 TextDecoder
// ei = new TextDecoder("utf-8");
// eh = new DataView(ec.buffer, ec.byteOffset, ec.byteLength);
// ec.dataView = eh;
// let res = rK()
const replacer = (key, value) => {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
};
res = JSON.stringify(res, replacer);
return res;
}
// console.log(generate_mid())
// console.log(generate_uuid())
// console.log(generate_device_id())
// console.log(generate_sign('5f65b00f83994987e334f97360d69557', '{"sessionTypes":"1,19"}'))
// let msg = "ggGLAYEBtTIyMDI2NDA5MTgwNzlAZ29vZmlzaAKzNDc4MTI4NzAwMDBAZ29vZmlzaAOxMzQwMjM5MTQ3MjUwMy5QTk0EAAXPAAABlYW04bIGggFlA4UBoAKjMTExA6AEAQXaADR7ImF0VXNlcnMiOltdLCJjb250ZW50VHlwZSI6MSwidGV4dCI6eyJ0ZXh0IjoiMTExIn19BwIIAQkACoupX3BsYXRmb3Jtp2FuZHJvaWSmYml6VGFn2gBBeyJzb3VyY2VJZCI6IlM6MSIsIm1lc3NhZ2VJZCI6ImYzNjkwMmVmZjQ1NDQ1YmRiMmQxYjBmZDE2OGY4MjY0In2sZGV0YWlsTm90aWNlozExMadleHRKc29u2gBLeyJxdWlja1JlcGx5IjoiMSIsIm1lc3NhZ2VJZCI6ImYzNjkwMmVmZjQ1NDQ1YmRiMmQxYjBmZDE2OGY4MjY0IiwidGFnIjoidSJ9r3JlbWluZGVyQ29udGVudKMxMTGucmVtaW5kZXJOb3RpY2W15Y+R5p2l5LiA5p2h5paw5raI5oGvrXJlbWluZGVyVGl0bGWmc2hh5L+uq3JlbWluZGVyVXJs2gCbZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9ODk3NzQyNzQ4MDExJnBlZXJVc2VySWQ9MjIwMjY0MDkxODA3OSZwZWVyVXNlck5pY2s9dCoqKjEmc2lkPTQ3ODEyODcwMDAwJm1lc3NhZ2VJZD1mMzY5MDJlZmY0NTQ0NWJkYjJkMWIwZmQxNjhmODI2NCZhZHY9bm+sc2VuZGVyVXNlcklkrTIyMDI2NDA5MTgwNzmuc2VuZGVyVXNlclR5cGWhMKtzZXNzaW9uVHlwZaExDAEDgahuZWVkUHVzaKR0cnVl";
//
// msg = "ggGLAYEBsjMxNDk2MzcwNjNAZ29vZmlzaAKzNDc5ODMzODkwOTZAZ29vZmlzaAOxMzQxNjU2NTI3NDU0Mi5QTk0EAAXPAAABlbKji20GggFlA4UBoAK6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl0DoAQaBdoEKnsiY29udGVudFR5cGUiOjI2LCJkeENhcmQiOnsiaXRlbSI6eyJtYWluIjp7ImNsaWNrUGFyYW0iOnsiYXJnMSI6Ik1zZ0NhcmQiLCJhcmdzIjp7InNvdXJjZSI6ImltIiwidGFza19pZCI6IjNleFFKSE9UbVBVMSIsIm1zZ19pZCI6ImNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczIn19LCJleENvbnRlbnQiOnsiYmdDb2xvciI6IiNGRkZGRkYiLCJidXR0b24iOnsiYmdDb2xvciI6IiNGRkU2MEYiLCJib3JkZXJDb2xvciI6IiNGRkU2MEYiLCJjbGlja1BhcmFtIjp7ImFyZzEiOiJNc2dDYXJkQWN0aW9uIiwiYXJncyI6eyJzb3VyY2UiOiJpbSIsInRhc2tfaWQiOiIzZXhRSkhPVG1QVTEiLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9fSwiZm9udENvbG9yIjoiIzMzMzMzMyIsInRhcmdldFVybCI6ImZsZWFtYXJrZXQ6Ly9hZGp1c3RfcHJpY2U/Zmx1dHRlcj10cnVlJmJpek9yZGVySWQ9MjUwMzY4ODEyNjM1NjYzNjM3MCIsInRleHQiOiLkv67mlLnku7fmoLwifSwiZGVzYyI6Iuivt+WPjOaWueayn+mAmuWPiuaXtuehruiupOS7t+agvCIsImRlc2NDb2xvciI6IiNBM0EzQTMiLCJ0aXRsZSI6IuaIkeW3suaLjeS4i++8jOW+heS7mOasviIsInVwZ3JhZGUiOnsidGFyZ2V0VXJsIjoiaHR0cHM6Ly9oNS5tLmdvb2Zpc2guY29tL2FwcC9pZGxlRmlzaC1GMmUvZm0tZG93bmxhb2QvaG9tZS5odG1sP25vUmVkcmllY3Q9dHJ1ZSZjYW5CYWNrPXRydWUmY2hlY2tWZXJzaW9uPXRydWUiLCJ2ZXJzaW9uIjoiNy43LjkwIn19LCJ0YXJnZXRVcmwiOiJmbGVhbWFya2V0Oi8vb3JkZXJfZGV0YWlsP2lkPTI1MDM2ODgxMjYzNTY2MzYzNzAmcm9sZT1zZWxsZXIifX0sInRlbXBsYXRlIjp7Im5hbWUiOiJpZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZCIsInVybCI6Imh0dHBzOi8vZGluYW1pY3guYWxpYmFiYXVzZXJjb250ZW50LmNvbS9wdWIvaWRsZWZpc2hfbWVzc2FnZV90cmFkZV9jaGF0X2NhcmQvMTY2NzIyMjA1Mjc2Ny9pZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZC56aXAiLCJ2ZXJzaW9uIjoiMTY2NzIyMjA1Mjc2NyJ9fX0HAQgBCQAK3gAQpmJpelRhZ9oAe3sic291cmNlSWQiOiJDMkM6M2V4UUpIT1RtUFUxIiwidGFza05hbWUiOiLlt7Lmi43kuItf5pyq5LuY5qy+X+WNluWutiIsIm1hdGVyaWFsSWQiOiIzZXhRSkhPVG1QVTEiLCJ0YXNrSWQiOiIzZXhRSkhPVG1QVTEifbFjbG9zZVB1c2hSZWNlaXZlcqVmYWxzZbFjbG9zZVVucmVhZE51bWJlcqVmYWxzZaxkZXRhaWxOb3RpY2W6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2nZXh0SnNvbtoBr3sibXNnQXJncyI6eyJ0YXNrX2lkIjoiM2V4UUpIT1RtUFUxIiwic291cmNlIjoiaW0iLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9LCJxdWlja1JlcGx5IjoiMSIsIm1zZ0FyZzEiOiJNc2dDYXJkIiwidXBkYXRlS2V5IjoiNDc5ODMzODkwOTY6MjUwMzY4ODEyNjM1NjYzNjM3MDoxX25vdF9wYXlfc2VsbGVyIiwibWVzc2FnZUlkIjoiY2M4YmMyZGY3YzkzNGRmMDg2ZTA1NjdjYjY5ZjE1NzMiLCJtdWx0aUNoYW5uZWwiOnsiaHVhd2VpIjoiRVhQUkVTUyIsInhpYW9taSI6IjEwODAwMCIsIm9wcG8iOiJFWFBSRVNTIiwiaG9ub3IiOiJOT1JNQUwiLCJhZ29vIjoicHJvZHVjdCIsInZpdm8iOiJPUkRFUiJ9LCJjb250ZW50VHlwZSI6IjI2IiwiY29ycmVsYXRpb25Hcm91cElkIjoiM2V4UUpIT1RtUFUxX0ZGcjRHT1NuOE9RbyJ9qHJlY2VpdmVyrTIyMDI2NDA5MTgwNzmrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMa9yZW1pbmRlckNvbnRlbnS6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2ucmVtaW5kZXJOb3RpY2W75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+rXJlbWluZGVyVGl0bGW75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+q3JlbWluZGVyVXJs2gCaZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9OTAwMDUyNjQ0Mjc3JnBlZXJVc2VySWQ9MzE0OTYzNzA2MyZwZWVyVXNlck5pY2s955S3KioqeSZzaWQ9NDc5ODMzODkwOTYmbWVzc2FnZUlkPWNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczJmFkdj1ub6xzZW5kZXJVc2VySWSqMzE0OTYzNzA2M65zZW5kZXJVc2VyVHlwZaEwq3Nlc3Npb25UeXBloTGqdXBkYXRlSGVhZKR0cnVlDAEDgahuZWVkUHVzaKR0cnVl"
// msg = "hAGzNDc5ODMzODkwOTZAZ29vZmlzaAIBA4KrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMQTPAAABlbMlNng="
// res = decrypt(msg);
// console.log(res);
+569
View File
@@ -0,0 +1,569 @@
"""
阿奇索API客户端 - Playwright自动化版本
通过浏览器自动化操作阿奇索平台,无需逆向API
"""
import asyncio
import json
import os
import tempfile
import base64
from typing import Optional, Dict, Any, List
from loguru import logger
from PIL import Image
try:
from playwright.async_api import async_playwright, Page, Browser, BrowserContext
PLAYWRIGHT_AVAILABLE = True
except ImportError:
PLAYWRIGHT_AVAILABLE = False
logger.warning("Playwright 未安装")
class AgisoClient:
"""阿奇索API客户端 - 基于Playwright自动化"""
def __init__(self, cookie: str, authorization: str):
"""
初始化阿奇索客户端
Args:
cookie: 阿奇索网站的Cookie字符串
authorization: 阿奇索网站的Authorization头
"""
self.cookie = cookie
self.authorization = authorization
self.base_url = "https://aldsidle.agiso.com"
self.browser: Optional[Browser] = None
self.context: Optional[BrowserContext] = None
self.page: Optional[Page] = None
async def _init_browser(self):
"""初始化浏览器"""
if not PLAYWRIGHT_AVAILABLE:
raise RuntimeError("Playwright 未安装,无法使用浏览器自动化")
playwright = await async_playwright().start()
self.browser = await playwright.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-blink-features=AutomationControlled"
]
)
self.context = await self.browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
viewport={"width": 1920, "height": 1080}
)
# 设置Cookie
await self._set_cookies()
# 创建页面
self.page = await self.context.new_page()
# 设置Authorization头
await self.page.set_extra_http_headers({
"Authorization": self.authorization
})
async def _set_cookies(self):
"""设置浏览器Cookie"""
if not self.cookie:
return
cookies = []
for item in self.cookie.split(";"):
item = item.strip()
if "=" in item:
name, value = item.split("=", 1)
cookies.append({
"name": name.strip(),
"value": value.strip(),
"domain": ".agiso.com",
"path": "/"
})
if cookies:
await self.context.add_cookies(cookies)
logger.info(f"设置Cookie成功: {len(cookies)}个")
async def close(self):
"""关闭浏览器"""
if self.browser:
await self.browser.close()
self.browser = None
self.context = None
self.page = None
async def __aenter__(self):
await self._init_browser()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
async def verify_account(self) -> Dict[str, Any]:
"""
验证账户有效性 - 通过设置Cookie访问阿奇索网站
Returns:
dict: {"success": bool, "message": str, "data": dict}
"""
try:
if not self.page:
await self._init_browser()
# 访问阿奇索首页
logger.info("验证阿奇索账户...")
await self.page.goto(self.base_url, wait_until="domcontentloaded", timeout=30000)
await asyncio.sleep(3)
# 获取当前URL,检查是否被重定向到登录页
current_url = self.page.url
logger.info(f"当前页面: {current_url}")
# 如果URL包含login相关路径,说明未登录
if "login" in current_url.lower() and "home" not in current_url.lower():
return {
"success": False,
"message": "账户验证失败:Cookie或Authorization无效,请重新获取",
"data": None
}
# 尝试访问仪表盘
try:
await self.page.goto(f"{self.base_url}/#/home/dashboard", wait_until="domcontentloaded", timeout=15000)
await asyncio.sleep(2)
# 再次检查URL
current_url = self.page.url
if "login" in current_url.lower() and "home" not in current_url.lower():
return {
"success": False,
"message": "账户验证失败:Cookie或Authorization无效",
"data": None
}
logger.info("阿奇索账户验证成功")
return {
"success": True,
"message": "账户验证成功",
"data": {"url": current_url}
}
except Exception as e:
logger.warning(f"访问仪表盘失败: {e}")
# 即使访问失败,只要不跳转到登录页就算成功
return {
"success": True,
"message": "账户验证成功",
"data": {"url": self.page.url}
}
except Exception as e:
logger.error(f"验证阿奇索账户异常: {e}")
return {
"success": False,
"message": f"验证异常: {str(e)}",
"data": None
}
async def upload_image(self, image_path: str) -> Dict[str, Any]:
"""
上传图片到阿奇索
Args:
image_path: 本地图片路径
Returns:
dict: {"success": bool, "message": str, "url": str}
"""
temp_path = None
try:
if not self.page:
await self._init_browser()
# 压缩图片
temp_path = self._compress_image(image_path)
if not temp_path:
return {"success": False, "message": "图片压缩失败", "url": None}
# 读取图片并转换为base64
with open(temp_path, "rb") as f:
image_data = f.read()
image_base64 = base64.b64encode(image_data).decode()
# TODO: 根据阿奇索实际页面结构实现图片上传
# 这里需要知道阿奇索的图片上传界面是什么样的
logger.info(f"图片上传功能待实现: {image_path}")
return {
"success": False,
"message": "图片上传功能需要根据阿奇索页面结构调整",
"url": None
}
except Exception as e:
logger.error(f"上传图片异常: {e}")
return {"success": False, "message": f"上传异常: {str(e)}", "url": None}
finally:
if temp_path and os.path.exists(temp_path):
try:
os.remove(temp_path)
except:
pass
def _compress_image(self, image_path: str, max_size: int = 5 * 1024 * 1024, quality: int = 85) -> Optional[str]:
"""压缩图片"""
try:
with Image.open(image_path) as img:
# 转换为RGB模式
if img.mode in ("RGBA", "LA", "P"):
background = Image.new("RGB", img.size, (255, 255, 255))
if img.mode == "P":
img = img.convert("RGBA")
background.paste(img, mask=img.split()[-1] if img.mode in ("RGBA", "LA") else None)
img = background
elif img.mode != "RGB":
img = img.convert("RGB")
# 调整尺寸
max_dimension = 1920
original_width, original_height = img.size
if original_width > max_dimension or original_height > max_dimension:
if original_width > original_height:
new_width = max_dimension
new_height = int((original_height * max_dimension) / original_width)
else:
new_height = max_dimension
new_width = int((original_width * max_dimension) / original_height)
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# 保存到临时文件
temp_fd, temp_path = tempfile.mkstemp(suffix=".jpg")
os.close(temp_fd)
img.save(temp_path, "JPEG", quality=quality, optimize=True)
# 检查文件大小
file_size = os.path.getsize(temp_path)
if file_size > max_size:
quality = max(30, quality - 20)
img.save(temp_path, "JPEG", quality=quality, optimize=True)
logger.info(f"图片压缩完成: {os.path.getsize(temp_path) / 1024:.1f}KB")
return temp_path
except Exception as e:
logger.error(f"图片压缩失败: {e}")
return None
async def publish_item(self, item_data: Dict[str, Any]) -> Dict[str, Any]:
"""
发布商品到阿奇索 - 完整复制原商品信息
Args:
item_data: 完整的原商品数据,包含:
- title: 商品标题
- description: 商品描述
- price: 商品价格
- stock: 库存数量
- images: 图片URL列表
- main_image: 主图URL
- item_url: 原商品链接
- seller_name: 卖家名称
- area: 地区
- tags: 标签列表
Returns:
dict: {"success": bool, "message": str, "item_id": str}
"""
try:
if not self.page:
await self._init_browser()
publish_url = f"{self.base_url}/#/goodsManage/goodsList/goodsRelease"
logger.info(f"开始发布商品,访问: {publish_url}")
# 访问发布页面
await self.page.goto(publish_url, wait_until="networkidle", timeout=30000)
await asyncio.sleep(3)
# 检查是否跳转到登录页
if "login" in self.page.url.lower():
return {
"success": False,
"message": "发布失败:未登录或Cookie已过期,请重新添加账户",
"item_id": None
}
logger.info(f"已进入发布页面: {self.page.url}")
# 等待页面加载完成
await asyncio.sleep(2)
# 获取完整商品信息
title = item_data.get("title", "")
description = item_data.get("description", "") or title
price = item_data.get("price", "0")
stock = item_data.get("stock", 1)
main_image = item_data.get("main_image", "")
item_url = item_data.get("item_url", "")
seller_name = item_data.get("seller_name", "")
area = item_data.get("area", "")
tags = item_data.get("tags", [])
# 清理价格字符串
clean_price = str(price).replace("¥", "").replace("¥", "").strip()
logger.info(f"商品信息: 标题={title[:30]}..., 价格={clean_price}, 库存={stock}")
# 分析页面结构,找到所有输入框
all_inputs = await self.page.query_selector_all('input, textarea')
logger.info(f"找到 {len(all_inputs)} 个输入框")
for i, inp in enumerate(all_inputs):
try:
placeholder = await inp.get_attribute('placeholder') or ''
name = await inp.get_attribute('name') or ''
input_type = await inp.get_attribute('type') or ''
logger.info(f"输入框 {i}: placeholder='{placeholder}', name='{name}', type='{input_type}'")
except:
pass
# 分析页面中的按钮
all_buttons = await self.page.query_selector_all('button')
logger.info(f"找到 {len(all_buttons)} 个按钮")
for i, btn in enumerate(all_buttons):
try:
btn_text = await btn.inner_text()
btn_type = await btn.get_attribute('type') or ''
logger.info(f"按钮 {i}: text='{btn_text}', type='{btn_type}'")
except:
pass
# 尝试填写表单 - 使用更智能的方式
# 1. 先尝试通过placeholder匹配
field_mappings = {
'标题': title,
'商品名称': title,
'商品标题': title,
'价格': clean_price,
'售价': clean_price,
'库存': str(stock),
'数量': str(stock),
'描述': description,
'商品描述': description,
'详情': description
}
for placeholder_text, value in field_mappings.items():
try:
# 通过placeholder查找
selector = f'input[placeholder*="{placeholder_text}"], textarea[placeholder*="{placeholder_text}"]'
element = await self.page.query_selector(selector)
if element:
await element.fill(value)
logger.info(f"通过placeholder填写成功: {placeholder_text}={value[:20]}...")
continue
# 通过label文本查找
label = await self.page.query_selector(f'label:has-text("{placeholder_text}")')
if label:
input_el = await label.query_selector('input, textarea')
if input_el:
await input_el.fill(value)
logger.info(f"通过label填写成功: {placeholder_text}={value[:20]}...")
except Exception as e:
continue
# 2. 尝试填写所有可见的输入框
for inp in all_inputs:
try:
placeholder = await inp.get_attribute('placeholder') or ''
name = await inp.get_attribute('name') or ''
input_type = await inp.get_attribute('type') or ''
# 跳过隐藏的输入框
if input_type == 'hidden':
continue
# 根据placeholder或name猜测字段
if '标题' in placeholder or '名称' in placeholder or 'title' in name.lower():
await inp.fill(title)
elif '价格' in placeholder or 'price' in name.lower():
await inp.fill(clean_price)
elif '库存' in placeholder or '数量' in placeholder or 'stock' in name.lower():
await inp.fill(str(stock))
elif '描述' in placeholder or '详情' in placeholder or 'desc' in name.lower():
await inp.fill(description)
except Exception as e:
continue
# 3. 填写textarea
textareas = await self.page.query_selector_all('textarea')
for textarea in textareas:
try:
placeholder = await textarea.get_attribute('placeholder') or ''
if '描述' in placeholder or '详情' in placeholder or not placeholder:
await textarea.fill(description)
logger.info(f"填写textarea成功: {placeholder}")
except:
continue
# 4. 尝试填写富文本编辑器
editors = await self.page.query_selector_all('.ql-editor, [contenteditable="true"], .ProseMirror')
for editor in editors:
try:
await editor.click()
await editor.fill(description)
logger.info("填写富文本编辑器成功")
except:
continue
# 等待一下让页面处理
await asyncio.sleep(1)
# 5. 点击发布按钮
submit_selectors = [
'button:has-text("发布")',
'button:has-text("提交")',
'button:has-text("保存并上架")',
'button:has-text("确认发布")',
'button[type="submit"]',
'.ant-btn-primary',
'button.ant-btn-primary'
]
submitted = False
for selector in submit_selectors:
try:
button = await self.page.query_selector(selector)
if button:
# 检查按钮是否可见和可点击
is_visible = await button.is_visible()
is_enabled = await button.is_enabled()
if is_visible and is_enabled:
await button.click()
submitted = True
logger.info(f"点击发布按钮成功: {selector}")
break
except Exception as e:
continue
if not submitted:
logger.warning("未找到发布按钮")
# 截图保存以便调试
screenshot_path = await self.get_page_screenshot()
return {
"success": False,
"message": "未找到发布按钮,可能页面结构已变化",
"item_id": None,
"screenshot": screenshot_path
}
# 等待发布结果
await asyncio.sleep(3)
# 检查是否有错误提示
error_selectors = [
'.ant-message-error',
'.error-message',
'.alert-danger',
'.ant-notification-notice-error'
]
for selector in error_selectors:
try:
error_el = await self.page.query_selector(selector)
if error_el:
error_text = await error_el.inner_text()
if error_text:
return {
"success": False,
"message": f"发布失败: {error_text}",
"item_id": None
}
except:
continue
# 检查是否成功(通过检测成功提示或页面跳转)
success_selectors = [
'.ant-message-success',
'.ant-notification-notice-success',
'.success-message'
]
for selector in success_selectors:
try:
success_el = await self.page.query_selector(selector)
if success_el:
logger.info("检测到发布成功提示")
break
except:
continue
# 如果没有找到错误,认为发布成功
logger.info("商品发布成功")
return {
"success": True,
"message": "商品发布成功",
"item_id": None
}
except Exception as e:
logger.error(f"发布商品异常: {e}")
# 截图保存以便调试
try:
screenshot_path = await self.get_page_screenshot()
except:
screenshot_path = None
return {
"success": False,
"message": f"发布异常: {str(e)}",
"item_id": None,
"screenshot": screenshot_path
}
async def get_page_screenshot(self) -> Optional[str]:
"""获取当前页面截图(调试用)"""
try:
if not self.page:
return None
screenshot = await self.page.screenshot(full_page=True)
# 保存到临时文件
temp_fd, temp_path = tempfile.mkstemp(suffix=".png")
os.close(temp_fd)
with open(temp_path, "wb") as f:
f.write(screenshot)
return temp_path
except Exception as e:
logger.error(f"获取截图失败: {e}")
return None
async def intercept_api_calls(self) -> List[Dict[str, Any]]:
"""
拦截页面API调用(用于逆向分析)
Returns:
list: 拦截到的API调用列表
"""
api_calls = []
async def handle_response(response):
url = response.url
if "api" in url.lower() or "agiso" in url.lower():
try:
body = await response.text()
api_calls.append({
"url": url,
"status": response.status,
"method": response.request.method,
"headers": dict(response.request.headers),
"body": body[:1000] if body else None
})
except:
pass
self.page.on("response", handle_response)
return api_calls
+216
View File
@@ -0,0 +1,216 @@
"""
图片上传器 - 负责将图片上传到闲鱼CDN
"""
import aiohttp
import asyncio
import json
import os
import tempfile
from typing import Optional, Dict, Any
from loguru import logger
from PIL import Image
import io
class ImageUploader:
"""图片上传器 - 上传图片到闲鱼CDN"""
def __init__(self, cookies_str: str):
self.cookies_str = cookies_str
self.upload_url = "https://stream-upload.goofish.com/api/upload.api?floderId=0&appkey=xy_chat&_input_charset=utf-8"
self.session = None
async def create_session(self):
"""创建HTTP会话"""
if not self.session:
connector = aiohttp.TCPConnector(limit=100, limit_per_host=30)
timeout = aiohttp.ClientTimeout(total=30)
self.session = aiohttp.ClientSession(
connector=connector,
timeout=timeout,
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
)
async def close_session(self):
"""关闭HTTP会话"""
if self.session:
await self.session.close()
self.session = None
def _compress_image(self, image_path: str, max_size: int = 5 * 1024 * 1024, quality: int = 85) -> Optional[str]:
"""压缩图片"""
try:
with Image.open(image_path) as img:
# 转换为RGB模式(如果是RGBA或其他模式)
if img.mode in ('RGBA', 'LA', 'P'):
# 创建白色背景
background = Image.new('RGB', img.size, (255, 255, 255))
if img.mode == 'P':
img = img.convert('RGBA')
background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
img = background
elif img.mode != 'RGB':
img = img.convert('RGB')
# 获取原始尺寸
original_width, original_height = img.size
# 如果图片太大,调整尺寸
max_dimension = 1920
if original_width > max_dimension or original_height > max_dimension:
if original_width > original_height:
new_width = max_dimension
new_height = int((original_height * max_dimension) / original_width)
else:
new_height = max_dimension
new_width = int((original_width * max_dimension) / original_height)
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
logger.info(f"图片尺寸调整: {original_width}x{original_height} -> {new_width}x{new_height}")
# 创建临时文件
temp_fd, temp_path = tempfile.mkstemp(suffix='.jpg')
os.close(temp_fd)
# 保存压缩后的图片
img.save(temp_path, 'JPEG', quality=quality, optimize=True)
# 检查文件大小
file_size = os.path.getsize(temp_path)
if file_size > max_size:
# 如果还是太大,降低质量
quality = max(30, quality - 20)
img.save(temp_path, 'JPEG', quality=quality, optimize=True)
file_size = os.path.getsize(temp_path)
logger.info(f"图片质量调整为 {quality}%,文件大小: {file_size / 1024:.1f}KB")
logger.info(f"图片压缩完成: {file_size / 1024:.1f}KB")
return temp_path
except Exception as e:
logger.error(f"图片压缩失败: {e}")
return None
async def upload_image(self, image_path: str) -> Optional[str]:
"""上传图片到闲鱼CDN"""
temp_path = None
try:
if not self.session:
await self.create_session()
# 压缩图片
temp_path = self._compress_image(image_path)
if not temp_path:
logger.error("图片压缩失败")
return None
# 读取压缩后的图片数据
with open(temp_path, 'rb') as f:
image_data = f.read()
# 构造文件名
filename = os.path.basename(image_path)
if not filename.lower().endswith(('.jpg', '.jpeg')):
filename = os.path.splitext(filename)[0] + '.jpg'
# 构造请求头
headers = {
'cookie': self.cookies_str,
'Referer': 'https://www.goofish.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'x-requested-with': 'XMLHttpRequest',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-site'
}
# 构造multipart/form-data
data = aiohttp.FormData()
data.add_field('file', image_data, filename=filename, content_type='image/jpeg')
# 发送上传请求
logger.info(f"开始上传图片到闲鱼CDN: {filename}")
async with self.session.post(self.upload_url, data=data, headers=headers) as response:
if response.status == 200:
response_text = await response.text()
logger.debug(f"上传响应: {response_text}")
# 解析响应获取图片URL
image_url = self._parse_upload_response(response_text)
if image_url:
logger.info(f"图片上传成功: {image_url}")
return image_url
else:
logger.error("解析上传响应失败")
return None
else:
logger.error(f"图片上传失败: HTTP {response.status}")
return None
except Exception as e:
logger.error(f"图片上传异常: {e}")
return None
finally:
# 清理临时文件
if temp_path and os.path.exists(temp_path):
try:
os.remove(temp_path)
except:
pass
def _parse_upload_response(self, response_text: str) -> Optional[str]:
"""解析上传响应获取图片URL"""
try:
# 尝试解析JSON响应
response_data = json.loads(response_text)
# 方式1: 标准响应格式
if 'data' in response_data and 'url' in response_data['data']:
return response_data['data']['url']
# 方式2: 在object字段中(闲鱼CDN的响应格式)
if 'object' in response_data and isinstance(response_data['object'], dict):
obj = response_data['object']
if 'url' in obj:
logger.info(f"从object.url提取到图片URL: {obj['url']}")
return obj['url']
# 方式3: 直接在根级别
if 'url' in response_data:
return response_data['url']
# 方式4: 在result中
if 'result' in response_data and 'url' in response_data['result']:
return response_data['result']['url']
# 方式5: 检查是否有文件信息
if 'data' in response_data and isinstance(response_data['data'], dict):
data = response_data['data']
if 'fileUrl' in data:
return data['fileUrl']
if 'file_url' in data:
return data['file_url']
logger.error(f"无法从响应中提取图片URL: {response_data}")
return None
except json.JSONDecodeError:
# 如果不是JSON格式,尝试其他解析方式
logger.error(f"响应不是有效的JSON格式: {response_text}")
return None
except Exception as e:
logger.error(f"解析上传响应异常: {e}")
return None
async def __aenter__(self):
await self.create_session()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close_session()
+256
View File
@@ -0,0 +1,256 @@
import os
import uuid
import hashlib
from PIL import Image
from typing import Optional, Tuple
from loguru import logger
class ImageManager:
"""图片管理器,负责图片的保存、压缩和访问"""
def __init__(self, upload_dir: str = "static/uploads/images"):
"""初始化图片管理器
Args:
upload_dir: 图片上传目录
"""
self.upload_dir = upload_dir
self.max_size = 5 * 1024 * 1024 # 5MB
self.max_width = 1920
self.max_height = 1080
self.allowed_formats = {'JPEG', 'PNG', 'GIF', 'WEBP'}
# 确保上传目录存在
self._ensure_upload_dir()
def _ensure_upload_dir(self):
"""确保上传目录存在"""
try:
os.makedirs(self.upload_dir, exist_ok=True)
logger.info(f"图片上传目录已准备: {self.upload_dir}")
except Exception as e:
logger.error(f"创建图片上传目录失败: {e}")
raise
def save_image(self, image_data: bytes, original_filename: str = None) -> Optional[str]:
"""保存图片文件
Args:
image_data: 图片二进制数据
original_filename: 原始文件名(可选)
Returns:
保存成功返回相对路径,失败返回None
"""
try:
logger.info(f"开始保存图片,数据大小: {len(image_data)} bytes")
# 验证图片数据
if not self._validate_image_data(image_data):
logger.error("图片数据验证失败")
return None
# 生成唯一文件名
file_hash = hashlib.md5(image_data).hexdigest()
file_extension = self._get_image_extension(image_data)
filename = f"{file_hash}_{uuid.uuid4().hex[:8]}.{file_extension}"
# 完整文件路径
file_path = os.path.join(self.upload_dir, filename)
# 检查文件是否已存在
if os.path.exists(file_path):
logger.info(f"图片文件已存在,跳过保存: {filename}")
return self._get_relative_path(file_path)
# 处理和保存图片
processed_image_data = self._process_image(image_data)
with open(file_path, 'wb') as f:
f.write(processed_image_data)
logger.info(f"图片保存成功: {filename}")
return self._get_relative_path(file_path)
except Exception as e:
logger.error(f"保存图片失败: {e}")
return None
def _validate_image_data(self, image_data: bytes) -> bool:
"""验证图片数据"""
try:
# 检查文件大小
if len(image_data) > self.max_size:
logger.warning(f"图片文件过大: {len(image_data)} bytes > {self.max_size} bytes")
return False
# 尝试打开图片验证格式
from io import BytesIO
with Image.open(BytesIO(image_data)) as img:
if img.format not in self.allowed_formats:
logger.warning(f"不支持的图片格式: {img.format}")
return False
# 检查图片尺寸(允许更大的尺寸,特别是手机长截图)
width, height = img.size
max_dimension = 4096 # 最大边长4096像素
if width > max_dimension or height > max_dimension:
logger.warning(f"图片尺寸过大: {width}x{height},最大允许: {max_dimension}x{max_dimension}")
return False
# 检查图片像素总数(防止过大的图片占用太多内存)
total_pixels = width * height
max_pixels = 8 * 1024 * 1024 # 8M像素
if total_pixels > max_pixels:
logger.warning(f"图片像素总数过大: {total_pixels},最大允许: {max_pixels}")
return False
return True
except Exception as e:
logger.error(f"图片验证失败: {e}")
return False
def _get_image_extension(self, image_data: bytes) -> str:
"""获取图片扩展名"""
try:
from io import BytesIO
with Image.open(BytesIO(image_data)) as img:
format_to_ext = {
'JPEG': 'jpg',
'PNG': 'png',
'GIF': 'gif',
'WEBP': 'webp'
}
return format_to_ext.get(img.format, 'jpg')
except:
return 'jpg'
def _process_image(self, image_data: bytes) -> bytes:
"""处理图片(压缩、调整尺寸等)"""
try:
from io import BytesIO
with Image.open(BytesIO(image_data)) as img:
# 转换为RGB模式(如果需要)
if img.mode in ('RGBA', 'LA', 'P'):
# 创建白色背景
background = Image.new('RGB', img.size, (255, 255, 255))
if img.mode == 'P':
img = img.convert('RGBA')
background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
img = background
elif img.mode != 'RGB':
img = img.convert('RGB')
# 调整尺寸(如果需要)- 允许更大的尺寸
width, height = img.size
max_output_dimension = 2048 # 输出最大边长2048像素
if width > max_output_dimension or height > max_output_dimension:
# 计算缩放比例,保持宽高比
ratio = min(max_output_dimension / width, max_output_dimension / height)
new_width = int(width * ratio)
new_height = int(height * ratio)
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
logger.info(f"图片已调整尺寸: {width}x{height} -> {new_width}x{new_height}")
else:
logger.info(f"图片尺寸合适,无需调整: {width}x{height}")
# 保存为JPEG格式,适度压缩
output = BytesIO()
img.save(output, format='JPEG', quality=85, optimize=True)
return output.getvalue()
except Exception as e:
logger.error(f"图片处理失败: {e}")
# 如果处理失败,返回原始数据
return image_data
def _get_relative_path(self, file_path: str) -> str:
"""获取相对于项目根目录的路径"""
# 将绝对路径转换为相对路径
rel_path = os.path.relpath(file_path)
# 统一使用正斜杠
return rel_path.replace('\\', '/')
def delete_image(self, image_path: str) -> bool:
"""删除图片文件
Args:
image_path: 图片相对路径
Returns:
删除成功返回True,失败返回False
"""
try:
# 构建完整路径
if not image_path.startswith(self.upload_dir):
full_path = os.path.join(os.getcwd(), image_path)
else:
full_path = image_path
if os.path.exists(full_path):
os.remove(full_path)
logger.info(f"图片删除成功: {image_path}")
return True
else:
logger.warning(f"图片文件不存在: {image_path}")
return False
except Exception as e:
logger.error(f"删除图片失败: {e}")
return False
def get_image_info(self, image_path: str) -> Optional[dict]:
"""获取图片信息
Args:
image_path: 图片相对路径
Returns:
图片信息字典或None
"""
try:
# 构建完整路径
if not image_path.startswith(self.upload_dir):
full_path = os.path.join(os.getcwd(), image_path)
else:
full_path = image_path
if not os.path.exists(full_path):
return None
with Image.open(full_path) as img:
return {
'width': img.width,
'height': img.height,
'format': img.format,
'mode': img.mode,
'size': os.path.getsize(full_path)
}
except Exception as e:
logger.error(f"获取图片信息失败: {e}")
return None
def get_image_size(self, image_path: str) -> tuple:
"""获取图片尺寸
Args:
image_path: 图片相对路径
Returns:
(width, height) 或 (None, None)
"""
try:
info = self.get_image_info(image_path)
if info:
return info['width'], info['height']
return None, None
except Exception as e:
logger.error(f"获取图片尺寸失败: {e}")
return None, None
# 创建全局图片管理器实例
image_manager = ImageManager()
+333
View File
@@ -0,0 +1,333 @@
"""
商品转卖发布器
处理从闲鱼搜索结果转卖到阿奇索平台的完整流程
"""
import asyncio
import aiohttp
import os
import tempfile
from typing import Optional, Dict, Any, List
from loguru import logger
from utils.agiso_client import AgisoClient
class ItemPublisher:
"""商品转卖发布器"""
def __init__(self):
"""初始化发布器"""
self._active_tasks: Dict[int, asyncio.Task] = {}
async def resell_item(
self,
source_item: Dict[str, Any],
agiso_account: Dict[str, Any],
resell_price: str,
stock: int = 1,
description: str = "",
user_id: int = None
) -> Dict[str, Any]:
"""
执行转卖流程
Args:
source_item: 搜索结果中的商品数据
agiso_account: 阿奇索账户信息(包含cookie和authorization)
resell_price: 转卖价格
stock: 库存数量
description: 商品描述(为空时使用原标题)
user_id: 用户ID
Returns:
dict: {"success": bool, "message": str, "record_id": int}
"""
record_id = None
try:
# 1. 创建转卖记录
from db_manager import db_manager
record_id = db_manager.add_resell_record(
user_id=user_id,
agiso_account_id=agiso_account["id"],
source_item_id=source_item.get("item_id", ""),
source_title=source_item.get("title", ""),
source_price=source_item.get("price", ""),
source_image=source_item.get("main_image", ""),
resell_price=resell_price,
resell_stock=stock,
resell_description=description
)
if record_id == -1:
return {"success": False, "message": "创建转卖记录失败", "record_id": None}
# 2. 更新状态为处理中
db_manager.update_resell_record_status(record_id, "processing")
# 3. 下载并上传图片
images = await self._process_images(source_item)
if not images:
db_manager.update_resell_record_status(record_id, "failed", error_message="图片处理失败")
return {"success": False, "message": "图片处理失败", "record_id": record_id}
# 4. 调用阿奇索发布API
async with AgisoClient(agiso_account["cookie"], agiso_account["authorization"]) as client:
# 验证账户
verify_result = await client.verify_account()
if not verify_result.get("success"):
db_manager.update_resell_record_status(
record_id, "failed",
error_message=f"阿奇索账户验证失败: {verify_result.get('message')}"
)
return {
"success": False,
"message": f"阿奇索账户验证失败: {verify_result.get('message')}",
"record_id": record_id
}
# 构建完整的商品数据 - 直接使用原商品信息
item_data = {
"title": source_item.get("title", ""),
"description": description or source_item.get("title", ""),
"price": resell_price if resell_price else source_item.get("price", "0"),
"stock": stock,
"images": images,
"main_image": source_item.get("main_image", ""),
"item_url": source_item.get("item_url", ""),
"seller_name": source_item.get("seller_name", ""),
"area": source_item.get("area", ""),
"tags": source_item.get("tags", []),
"source_item_id": source_item.get("item_id", ""),
"publish_time": source_item.get("publish_time", ""),
"want_count": source_item.get("want_count", 0),
}
# 发布商品
publish_result = await client.publish_item(item_data)
if publish_result.get("success"):
# 发布成功后,尝试收藏原商品
favorited = await self._favorite_original_item(source_item)
db_manager.update_resell_record_status(
record_id, "success",
agiso_item_id=publish_result.get("item_id")
)
logger.info(f"转卖成功: record_id={record_id}, agiso_item_id={publish_result.get('item_id')}")
message = "转卖成功"
if favorited:
message += ",原商品已收藏"
return {
"success": True,
"message": message,
"record_id": record_id,
"agiso_item_id": publish_result.get("item_id"),
"favorited": favorited
}
else:
db_manager.update_resell_record_status(
record_id, "failed",
error_message=publish_result.get("message")
)
return {
"success": False,
"message": f"发布失败: {publish_result.get('message')}",
"record_id": record_id
}
except Exception as e:
logger.error(f"转卖异常: {e}")
if record_id:
from db_manager import db_manager
db_manager.update_resell_record_status(record_id, "failed", error_message=str(e))
return {"success": False, "message": f"转卖异常: {str(e)}", "record_id": record_id}
async def _process_images(self, source_item: Dict[str, Any]) -> List[str]:
"""
处理商品图片:下载 → 压缩 → 上传到阿奇索
Args:
source_item: 商品数据,包含main_image字段
Returns:
list: 上传后的图片URL列表
"""
images = []
main_image = source_item.get("main_image", "")
if not main_image:
logger.warning("商品没有主图")
return images
# 确保图片URL有协议前缀
if main_image.startswith("//"):
main_image = f"https:{main_image}"
elif not main_image.startswith("http"):
main_image = f"https://{main_image}"
try:
# 下载图片
temp_path = await self._download_image(main_image)
if not temp_path:
logger.error(f"下载图片失败: {main_image}")
return images
# 上传到阿奇索(这里需要阿奇索账户信息,但图片上传在resell_item中处理)
# 这里只返回下载的临时文件路径,实际上传在resell_item中完成
images.append(temp_path)
except Exception as e:
logger.error(f"处理图片异常: {e}")
return images
async def _download_image(self, image_url: str) -> Optional[str]:
"""
下载图片到临时文件
Args:
image_url: 图片URL
Returns:
str: 临时文件路径
"""
try:
async with aiohttp.ClientSession() as session:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": "https://www.goofish.com/"
}
async with session.get(image_url, headers=headers, timeout=aiohttp.ClientTimeout(total=30)) as response:
if response.status == 200:
# 创建临时文件
temp_fd, temp_path = tempfile.mkstemp(suffix=".jpg")
os.close(temp_fd)
# 写入数据
data = await response.read()
with open(temp_path, "wb") as f:
f.write(data)
logger.info(f"下载图片成功: {image_url} -> {temp_path}")
return temp_path
else:
logger.error(f"下载图片失败: HTTP {response.status}")
return None
except Exception as e:
logger.error(f"下载图片异常: {e}")
return None
async def _favorite_original_item(self, source_item: Dict[str, Any]) -> bool:
"""
收藏原商品到闲鱼
Args:
source_item: 原商品数据
Returns:
bool: 是否成功收藏
"""
try:
item_id = source_item.get("item_id", "")
if not item_id:
logger.warning("没有商品ID,无法收藏")
return False
# 获取闲鱼Cookie
from db_manager import db_manager
cookies = db_manager.get_all_cookies()
if not cookies:
logger.warning("没有可用的闲鱼Cookie,无法收藏")
return False
# 使用第一个有效的Cookie
cookie_value = None
for cid, cval in cookies.items():
if len(cval) > 50:
cookie_value = cval
break
if not cookie_value:
logger.warning("没有有效的闲鱼Cookie")
return False
# 尝试调用收藏API
# 闲鱼收藏API: mtop.idle.web.xyh.item.favorite
import aiohttp
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": "https://www.goofish.com/",
"Cookie": cookie_value,
"Content-Type": "application/x-www-form-urlencoded"
}
# 生成签名(使用现有的签名方法)
from utils.xianyu_utils import generate_sign
import time
timestamp = str(int(time.time() * 1000))
sign = generate_sign(timestamp, "", f'"itemId":"{item_id}"')
# 构建请求
api_url = f"https://h5api.m.goofish.com/h5/mtop.idle.web.xyh.item.favorite/1.0/"
params = {
"jsv": "2.7.4",
"appKey": "34839810",
"t": timestamp,
"sign": sign,
"api": "mtop.idle.web.xyh.item.favorite",
"v": "1.0",
"type": "jsonp",
"dataType": "jsonp",
"callback": "mtopjsonp1",
"data": f'{{"itemId":"{item_id}"}}'
}
async with aiohttp.ClientSession() as session:
async with session.post(api_url, headers=headers, data=params, timeout=aiohttp.ClientTimeout(total=10)) as response:
if response.status == 200:
result = await response.text()
if "success" in result.lower() or "收藏成功" in result:
logger.info(f"收藏原商品成功: {item_id}")
return True
else:
logger.warning(f"收藏原商品返回: {result[:200]}")
else:
logger.warning(f"收藏原商品失败: HTTP {response.status}")
return False
except Exception as e:
logger.error(f"收藏原商品异常: {e}")
return False
def cancel_task(self, record_id: int) -> bool:
"""
取消转卖任务
Args:
record_id: 记录ID
Returns:
bool: 是否成功取消
"""
if record_id in self._active_tasks:
task = self._active_tasks[record_id]
if not task.done():
task.cancel()
logger.info(f"取消转卖任务: record_id={record_id}")
del self._active_tasks[record_id]
return True
return False
def get_active_tasks(self) -> List[int]:
"""获取所有活跃的任务ID"""
return [rid for rid, task in self._active_tasks.items() if not task.done()]
# 全局实例
item_publisher = ItemPublisher()
+1179
View File
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
import time
from typing import Dict, Any
def format_message(message_data: Dict[str, Any], is_outgoing: bool = False, is_manual: bool = False) -> str:
"""格式化消息输出"""
try:
# 获取消息内容
content = message_data.get('content', '')
if not content:
return ''
# 获取发送时间
timestamp = message_data.get('time', time.time() * 1000)
time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp / 1000))
# 确定消息方向
direction = '【发出】' if is_outgoing else '【收到】'
if is_manual:
direction = '【手动发出】'
# 格式化输出
return f"{time_str} {direction} {content}"
except Exception as e:
return f"消息格式化错误: {str(e)}"
def format_system_message(message: str) -> str:
"""格式化系统消息输出"""
time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
return f"{time_str} 【系统】 {message}"
+752
View File
@@ -0,0 +1,752 @@
"""
闲鱼订单详情获取工具
基于Playwright实现订单详情页面访问和数据提取
"""
import asyncio
import time
import sys
import os
from typing import Optional, Dict, Any
from playwright.async_api import async_playwright, Browser, BrowserContext, Page
from loguru import logger
import re
import json
from threading import Lock
from collections import defaultdict
# 修复Docker环境中的asyncio事件循环策略问题
if sys.platform.startswith('linux') or os.getenv('DOCKER_ENV'):
try:
# 在Linux/Docker环境中设置事件循环策略
asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
except Exception as e:
logger.warning(f"设置事件循环策略失败: {e}")
# 确保在Docker环境中使用正确的事件循环
if os.getenv('DOCKER_ENV'):
try:
# 强制使用SelectorEventLoop(在Docker中更稳定)
if hasattr(asyncio, 'SelectorEventLoop'):
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
except Exception as e:
logger.warning(f"设置SelectorEventLoop失败: {e}")
class OrderDetailFetcher:
"""闲鱼订单详情获取器"""
# 类级别的锁字典,为每个order_id维护一个锁
_order_locks = defaultdict(lambda: asyncio.Lock())
def __init__(self, cookie_string: str = None, headless: bool = True):
self.browser: Optional[Browser] = None
self.context: Optional[BrowserContext] = None
self.page: Optional[Page] = None
self.headless = headless # 保存headless设置
# 请求头配置
self.headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"accept-language": "en,zh-CN;q=0.9,zh;q=0.8,ru;q=0.7",
"cache-control": "no-cache",
"pragma": "no-cache",
"priority": "u=0, i",
"sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1"
}
# Cookie配置 - 支持动态传入
self.cookie = cookie_string
async def init_browser(self, headless: bool = None):
"""初始化浏览器"""
try:
# 如果没有传入headless参数,使用实例的设置
if headless is None:
headless = self.headless
logger.info(f"开始初始化浏览器,headless模式: {headless}")
playwright = await async_playwright().start()
# 启动浏览器(Docker环境优化)
browser_args = [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'--disable-features=TranslateUI',
'--disable-ipc-flooding-protection',
'--disable-extensions',
'--disable-default-apps',
'--disable-sync',
'--disable-translate',
'--hide-scrollbars',
'--mute-audio',
'--no-default-browser-check',
'--no-pings'
]
# 只在Docker环境中使用单进程模式
if os.getenv('DOCKER_ENV'):
browser_args.append('--single-process')
# 在Docker环境中添加额外参数
if os.getenv('DOCKER_ENV'):
browser_args.extend([
'--disable-background-networking',
'--disable-background-timer-throttling',
'--disable-client-side-phishing-detection',
'--disable-default-apps',
'--disable-hang-monitor',
'--disable-popup-blocking',
'--disable-prompt-on-repost',
'--disable-sync',
'--disable-web-resources',
'--metrics-recording-only',
'--no-first-run',
'--safebrowsing-disable-auto-update',
'--enable-automation',
'--password-store=basic',
'--use-mock-keychain'
])
logger.info(f"启动浏览器,参数: {browser_args}")
self.browser = await playwright.chromium.launch(
headless=headless,
args=browser_args
)
logger.info("浏览器启动成功,创建上下文...")
# 创建浏览器上下文
self.context = await self.browser.new_context(
viewport={'width': 1920, 'height': 1080},
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
)
logger.info("浏览器上下文创建成功,设置HTTP头...")
# 设置额外的HTTP头
await self.context.set_extra_http_headers(self.headers)
logger.info("创建页面...")
# 创建页面
self.page = await self.context.new_page()
logger.info("页面创建成功,设置Cookie...")
# 设置Cookie
await self._set_cookies()
# 等待一段时间确保浏览器完全初始化
await asyncio.sleep(1)
logger.info("浏览器初始化成功")
return True
except Exception as e:
logger.error(f"浏览器初始化失败: {e}")
return False
async def _set_cookies(self):
"""设置Cookie"""
try:
# 解析Cookie字符串
cookies = []
for cookie_pair in self.cookie.split('; '):
if '=' in cookie_pair:
name, value = cookie_pair.split('=', 1)
cookies.append({
'name': name.strip(),
'value': value.strip(),
'domain': '.goofish.com',
'path': '/'
})
# 添加Cookie到上下文
await self.context.add_cookies(cookies)
logger.info(f"已设置 {len(cookies)} 个Cookie")
except Exception as e:
logger.error(f"设置Cookie失败: {e}")
async def fetch_order_detail(self, order_id: str, timeout: int = 30) -> Optional[Dict[str, Any]]:
"""
获取订单详情(带锁机制和数据库缓存)
Args:
order_id: 订单ID
timeout: 超时时间(秒)
Returns:
包含订单详情的字典,失败时返回None
"""
# 获取该订单ID的锁
order_lock = self._order_locks[order_id]
async with order_lock:
logger.info(f"🔒 获取订单 {order_id} 的锁,开始处理...")
try:
# 首先查询数据库中是否已存在该订单(在初始化浏览器之前)
from db_manager import db_manager
existing_order = db_manager.get_order_by_id(order_id)
if existing_order:
# 检查金额字段是否有效(不为空且不为0)
amount = existing_order.get('amount', '')
amount_valid = False
if amount:
# 移除可能的货币符号和空格,检查是否为有效数字
amount_clean = str(amount).replace('¥', '').replace('¥', '').replace('$', '').strip()
try:
amount_value = float(amount_clean)
amount_valid = amount_value > 0
except (ValueError, TypeError):
amount_valid = False
if amount_valid:
logger.info(f"📋 订单 {order_id} 已存在于数据库中且金额有效({amount}),直接返回缓存数据")
print(f"✅ 订单 {order_id} 使用缓存数据,跳过浏览器获取")
# 构建返回格式,与浏览器获取的格式保持一致
result = {
'order_id': existing_order['order_id'],
'url': f"https://www.goofish.com/order-detail?orderId={order_id}&role=seller",
'title': f"订单详情 - {order_id}",
'sku_info': {
'spec_name': existing_order.get('spec_name', ''),
'spec_value': existing_order.get('spec_value', ''),
'quantity': existing_order.get('quantity', ''),
'amount': existing_order.get('amount', '')
},
'spec_name': existing_order.get('spec_name', ''),
'spec_value': existing_order.get('spec_value', ''),
'quantity': existing_order.get('quantity', ''),
'amount': existing_order.get('amount', ''),
'timestamp': time.time(),
'from_cache': True # 标记数据来源
}
return result
else:
logger.info(f"📋 订单 {order_id} 存在于数据库中但金额无效({amount}),需要重新获取")
print(f"⚠️ 订单 {order_id} 金额无效,重新获取详情...")
# 只有在数据库中没有有效数据时才初始化浏览器
logger.info(f"🌐 订单 {order_id} 需要浏览器获取,开始初始化浏览器...")
print(f"🔍 订单 {order_id} 开始浏览器获取详情...")
# 确保浏览器准备就绪
if not await self._ensure_browser_ready():
logger.error("浏览器初始化失败,无法获取订单详情")
return None
# 构建订单详情URL
url = f"https://www.goofish.com/order-detail?orderId={order_id}&role=seller"
logger.info(f"开始访问订单详情页面: {url}")
# 访问页面(带重试机制)
max_retries = 2
response = None
for retry in range(max_retries + 1):
try:
response = await self.page.goto(url, wait_until='networkidle', timeout=timeout * 1000)
if response and response.status == 200:
break
else:
logger.warning(f"页面访问失败,状态码: {response.status if response else 'None'},重试 {retry + 1}/{max_retries + 1}")
except Exception as e:
logger.warning(f"页面访问异常: {e},重试 {retry + 1}/{max_retries + 1}")
# 如果是浏览器连接问题,尝试重新初始化
if "Target page, context or browser has been closed" in str(e):
logger.info("检测到浏览器连接断开,尝试重新初始化...")
if await self._ensure_browser_ready():
logger.info("浏览器重新初始化成功,继续重试...")
continue
else:
logger.error("浏览器重新初始化失败")
return None
if retry == max_retries:
logger.error(f"页面访问最终失败: {e}")
return None
await asyncio.sleep(1) # 重试前等待1秒
if not response or response.status != 200:
logger.error(f"页面访问最终失败,状态码: {response.status if response else 'None'}")
return None
logger.info("页面加载成功,等待内容渲染...")
# 等待页面完全加载
try:
await self.page.wait_for_load_state('networkidle')
except Exception as e:
logger.warning(f"等待页面加载状态失败: {e}")
# 继续执行,不中断流程
# 额外等待确保动态内容加载完成
await asyncio.sleep(3)
# 获取并解析SKU信息
sku_info = await self._get_sku_content()
# 获取页面标题
try:
title = await self.page.title()
except Exception as e:
logger.warning(f"获取页面标题失败: {e}")
title = f"订单详情 - {order_id}"
result = {
'order_id': order_id,
'url': url,
'title': title,
'sku_info': sku_info, # 包含解析后的规格信息
'spec_name': sku_info.get('spec_name', '') if sku_info else '',
'spec_value': sku_info.get('spec_value', '') if sku_info else '',
'quantity': sku_info.get('quantity', '') if sku_info else '', # 数量
'amount': sku_info.get('amount', '') if sku_info else '', # 金额
'timestamp': time.time(),
'from_cache': False # 标记数据来源
}
logger.info(f"订单详情获取成功: {order_id}")
if sku_info:
logger.info(f"规格信息 - 名称: {result['spec_name']}, 值: {result['spec_value']}")
logger.info(f"数量: {result['quantity']}, 金额: {result['amount']}")
return result
except Exception as e:
logger.error(f"获取订单详情失败: {e}")
return None
def _parse_sku_content(self, sku_content: str) -> Dict[str, str]:
"""
解析SKU内容,根据冒号分割规格名称和规格值
Args:
sku_content: 原始SKU内容字符串
Returns:
包含规格名称和规格值的字典,如果解析失败则返回空字典
"""
try:
if not sku_content or ':' not in sku_content:
logger.warning(f"SKU内容格式无效或不包含冒号: {sku_content}")
return {}
# 根据冒号分割
parts = sku_content.split(':', 1) # 只分割第一个冒号
if len(parts) == 2:
spec_name = parts[0].strip()
spec_value = parts[1].strip()
if spec_name and spec_value:
result = {
'spec_name': spec_name,
'spec_value': spec_value
}
logger.info(f"SKU解析成功 - 规格名称: {spec_name}, 规格值: {spec_value}")
return result
else:
logger.warning(f"SKU解析失败,规格名称或值为空: 名称='{spec_name}', 值='{spec_value}'")
return {}
else:
logger.warning(f"SKU内容分割失败: {sku_content}")
return {}
except Exception as e:
logger.error(f"解析SKU内容异常: {e}")
return {}
async def _get_sku_content(self) -> Optional[Dict[str, str]]:
"""获取并解析SKU内容,包括规格、数量和金额"""
try:
# 检查浏览器状态
if not await self._check_browser_status():
logger.error("浏览器状态异常,无法获取SKU内容")
return {}
result = {}
# 获取所有 sku--u_ddZval 元素
sku_selector = '.sku--u_ddZval'
sku_elements = await self.page.query_selector_all(sku_selector)
logger.info(f"找到 {len(sku_elements)} 个 sku--u_ddZval 元素")
print(f"🔍 找到 {len(sku_elements)} 个 sku--u_ddZval 元素")
# 获取金额信息
amount_selector = '.boldNum--JgEOXfA3'
amount_element = await self.page.query_selector(amount_selector)
amount = ''
if amount_element:
amount_text = await amount_element.text_content()
if amount_text:
amount = amount_text.strip()
logger.info(f"找到金额: {amount}")
print(f"💰 金额: {amount}")
result['amount'] = amount
else:
logger.warning("未找到金额元素")
print("⚠️ 未找到金额信息")
# 处理 sku--u_ddZval 元素
if len(sku_elements) == 2:
# 有两个元素:第一个是规格,第二个是数量
logger.info("检测到两个 sku--u_ddZval 元素,第一个为规格,第二个为数量")
print("📋 检测到两个元素:第一个为规格,第二个为数量")
# 处理规格(第一个元素)
spec_content = await sku_elements[0].text_content()
if spec_content:
spec_content = spec_content.strip()
logger.info(f"规格原始内容: {spec_content}")
print(f"🛍️ 规格原始内容: {spec_content}")
# 解析规格内容
parsed_spec = self._parse_sku_content(spec_content)
if parsed_spec:
result.update(parsed_spec)
print(f"📋 规格名称: {parsed_spec['spec_name']}")
print(f"📝 规格值: {parsed_spec['spec_value']}")
# 处理数量(第二个元素)
quantity_content = await sku_elements[1].text_content()
if quantity_content:
quantity_content = quantity_content.strip()
logger.info(f"数量原始内容: {quantity_content}")
print(f"📦 数量原始内容: {quantity_content}")
# 从数量内容中提取数量值(使用冒号分割,取后面的值)
if ':' in quantity_content:
quantity_value = quantity_content.split(':', 1)[1].strip()
# 去掉数量值前面的 'x' 符号(如 "x2" -> "2")
if quantity_value.startswith('x'):
quantity_value = quantity_value[1:]
result['quantity'] = quantity_value
logger.info(f"提取到数量: {quantity_value}")
print(f"🔢 数量: {quantity_value}")
else:
# 去掉数量值前面的 'x' 符号(如 "x2" -> "2")
if quantity_content.startswith('x'):
quantity_content = quantity_content[1:]
result['quantity'] = quantity_content
logger.info(f"数量内容无冒号,直接使用: {quantity_content}")
print(f"🔢 数量: {quantity_content}")
elif len(sku_elements) == 1:
# 只有一个元素:判断是否包含"数量"
logger.info("检测到一个 sku--u_ddZval 元素,判断是规格还是数量")
print("📋 检测到一个元素,判断是规格还是数量")
content = await sku_elements[0].text_content()
if content:
content = content.strip()
logger.info(f"元素原始内容: {content}")
print(f"🛍️ 元素原始内容: {content}")
if '数量' in content:
# 这是数量信息
logger.info("判断为数量信息")
print("📦 判断为数量信息")
if ':' in content:
quantity_value = content.split(':', 1)[1].strip()
# 去掉数量值前面的 'x' 符号(如 "x2" -> "2")
if quantity_value.startswith('x'):
quantity_value = quantity_value[1:]
result['quantity'] = quantity_value
logger.info(f"提取到数量: {quantity_value}")
print(f"🔢 数量: {quantity_value}")
else:
# 去掉数量值前面的 'x' 符号(如 "x2" -> "2")
if content.startswith('x'):
content = content[1:]
result['quantity'] = content
logger.info(f"数量内容无冒号,直接使用: {content}")
print(f"🔢 数量: {content}")
else:
# 这是规格信息
logger.info("判断为规格信息")
print("📋 判断为规格信息")
parsed_spec = self._parse_sku_content(content)
if parsed_spec:
result.update(parsed_spec)
print(f"📋 规格名称: {parsed_spec['spec_name']}")
print(f"📝 规格值: {parsed_spec['spec_value']}")
else:
logger.warning(f"未找到或找到异常数量的 sku--u_ddZval 元素: {len(sku_elements)}")
print(f"⚠️ 未找到或找到异常数量的元素: {len(sku_elements)}")
# 如果没有找到sku--u_ddZval元素,设置默认数量为1
if len(sku_elements) == 0:
result['quantity'] = '1'
logger.info("未找到sku--u_ddZval元素,数量默认设置为1")
print("📦 数量默认设置为: 1")
# 尝试获取页面的所有class包含sku的元素进行调试
all_sku_elements = await self.page.query_selector_all('[class*="sku"]')
if all_sku_elements:
logger.info(f"找到 {len(all_sku_elements)} 个包含'sku'的元素")
for i, element in enumerate(all_sku_elements):
class_name = await element.get_attribute('class')
text_content = await element.text_content()
logger.info(f"SKU元素 {i+1}: class='{class_name}', text='{text_content}'")
# 确保数量字段存在,如果不存在则设置为1
if 'quantity' not in result:
result['quantity'] = '1'
logger.info("未获取到数量信息,默认设置为1")
print("📦 数量默认设置为: 1")
# 打印最终结果
if result:
logger.info(f"最终解析结果: {result}")
print("✅ 解析结果:")
for key, value in result.items():
print(f" {key}: {value}")
return result
else:
logger.warning("未能解析到任何有效信息")
print("❌ 未能解析到任何有效信息")
# 即使没有其他信息,也要返回默认数量
return {'quantity': '0'}
except Exception as e:
logger.error(f"获取SKU内容失败: {e}")
return {}
async def _check_browser_status(self) -> bool:
"""检查浏览器状态是否正常"""
try:
if not self.browser or not self.context or not self.page:
logger.warning("浏览器组件不完整")
return False
# 检查浏览器是否已连接
if self.browser.is_connected():
# 尝试获取页面标题来验证页面是否可用
await self.page.title()
return True
else:
logger.warning("浏览器连接已断开")
return False
except Exception as e:
logger.warning(f"浏览器状态检查失败: {e}")
return False
async def _ensure_browser_ready(self) -> bool:
"""确保浏览器准备就绪,如果不可用则重新初始化"""
try:
if await self._check_browser_status():
return True
logger.info("浏览器状态异常,尝试重新初始化...")
# 先尝试关闭现有的浏览器实例
await self._force_close_browser()
# 重新初始化浏览器
await self.init_browser()
# 等待更长时间确保浏览器完全就绪
await asyncio.sleep(2)
# 再次检查状态
if await self._check_browser_status():
logger.info("浏览器重新初始化成功")
return True
else:
logger.error("浏览器重新初始化失败")
return False
except Exception as e:
logger.error(f"确保浏览器就绪失败: {e}")
return False
async def _force_close_browser(self):
"""强制关闭浏览器,忽略所有错误"""
try:
if self.page:
try:
await self.page.close()
except:
pass
self.page = None
if self.context:
try:
await self.context.close()
except:
pass
self.context = None
if self.browser:
try:
await self.browser.close()
except:
pass
self.browser = None
except Exception as e:
logger.debug(f"强制关闭浏览器过程中的异常(可忽略): {e}")
async def close(self):
"""关闭浏览器"""
try:
if self.page:
await self.page.close()
if self.context:
await self.context.close()
if self.browser:
await self.browser.close()
logger.info("浏览器已关闭")
except Exception as e:
logger.error(f"关闭浏览器失败: {e}")
# 如果正常关闭失败,尝试强制关闭
await self._force_close_browser()
async def __aenter__(self):
"""异步上下文管理器入口"""
await self.init_browser()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""异步上下文管理器出口"""
await self.close()
# 便捷函数
async def fetch_order_detail_simple(order_id: str, cookie_string: str = None, headless: bool = True) -> Optional[Dict[str, Any]]:
"""
简单的订单详情获取函数(优化版:先检查数据库,再初始化浏览器)
Args:
order_id: 订单ID
cookie_string: Cookie字符串,如果不提供则使用默认值
headless: 是否无头模式
Returns:
订单详情字典,包含以下字段:
- order_id: 订单ID
- url: 订单详情页面URL
- title: 页面标题
- sku_info: 完整的SKU信息字典
- spec_name: 规格名称
- spec_value: 规格值
- quantity: 数量
- amount: 金额
- timestamp: 获取时间戳
失败时返回None
"""
# 先检查数据库中是否有有效数据
try:
from db_manager import db_manager
existing_order = db_manager.get_order_by_id(order_id)
if existing_order:
# 检查金额字段是否有效
amount = existing_order.get('amount', '')
amount_valid = False
if amount:
amount_clean = str(amount).replace('¥', '').replace('¥', '').replace('$', '').strip()
try:
amount_value = float(amount_clean)
amount_valid = amount_value > 0
except (ValueError, TypeError):
amount_valid = False
if amount_valid:
logger.info(f"📋 订单 {order_id} 已存在于数据库中且金额有效({amount}),直接返回缓存数据")
print(f"✅ 订单 {order_id} 使用缓存数据,跳过浏览器获取")
# 构建返回格式
result = {
'order_id': existing_order['order_id'],
'url': f"https://www.goofish.com/order-detail?orderId={order_id}&role=seller",
'title': f"订单详情 - {order_id}",
'sku_info': {
'spec_name': existing_order.get('spec_name', ''),
'spec_value': existing_order.get('spec_value', ''),
'quantity': existing_order.get('quantity', ''),
'amount': existing_order.get('amount', '')
},
'spec_name': existing_order.get('spec_name', ''),
'spec_value': existing_order.get('spec_value', ''),
'quantity': existing_order.get('quantity', ''),
'amount': existing_order.get('amount', ''),
'order_status': existing_order.get('order_status', 'unknown'), # 添加订单状态
'timestamp': time.time(),
'from_cache': True
}
return result
else:
logger.info(f"📋 订单 {order_id} 存在于数据库中但金额无效({amount}),需要重新获取")
print(f"⚠️ 订单 {order_id} 金额无效,重新获取详情...")
except Exception as e:
logger.warning(f"检查数据库缓存失败: {e}")
# 数据库中没有有效数据,使用浏览器获取
logger.info(f"🌐 订单 {order_id} 需要浏览器获取,开始初始化浏览器...")
print(f"🔍 订单 {order_id} 开始浏览器获取详情...")
fetcher = OrderDetailFetcher(cookie_string, headless)
try:
if await fetcher.init_browser(headless=headless):
return await fetcher.fetch_order_detail(order_id)
finally:
await fetcher.close()
return None
# 测试代码
if __name__ == "__main__":
async def test():
# 测试订单ID
test_order_id = "2856024697612814489"
print(f"🔍 开始获取订单详情: {test_order_id}")
result = await fetch_order_detail_simple(test_order_id, headless=False)
if result:
print("✅ 订单详情获取成功:")
print(f"📋 订单ID: {result['order_id']}")
print(f"🌐 URL: {result['url']}")
print(f"📄 页面标题: {result['title']}")
print(f"🛍️ 规格名称: {result.get('spec_name', '未获取到')}")
print(f"📝 规格值: {result.get('spec_value', '未获取到')}")
print(f"🔢 数量: {result.get('quantity', '未获取到')}")
print(f"💰 金额: {result.get('amount', '未获取到')}")
else:
print("❌ 订单详情获取失败")
# 运行测试
asyncio.run(test())
+451
View File
@@ -0,0 +1,451 @@
#!/usr/bin/env python3
"""
闲鱼扫码登录工具
基于API接口实现二维码生成和Cookie获取(参照myfish-main项目)
"""
import asyncio
import time
import uuid
import json
import re
from random import random
from typing import Optional, Dict, Any
import httpx
import qrcode
import qrcode.constants
from loguru import logger
import hashlib
def generate_headers():
"""生成请求头"""
return {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'Referer': 'https://passport.goofish.com/',
'Origin': 'https://passport.goofish.com',
}
class GetLoginParamsError(Exception):
"""获取登录参数错误"""
class GetLoginQRCodeError(Exception):
"""获取登录二维码失败"""
class NotLoginError(Exception):
"""未登录错误"""
class QRLoginSession:
"""二维码登录会话"""
def __init__(self, session_id: str):
self.session_id = session_id
self.status = 'waiting' # waiting, scanned, success, expired, cancelled, verification_required
self.qr_code_url = None
self.qr_content = None
self.cookies = {}
self.unb = None
self.created_time = time.time()
self.expire_time = 300 # 5分钟过期
self.params = {} # 存储登录参数
self.verification_url = None # 风控验证URL
def is_expired(self) -> bool:
"""检查是否过期"""
return time.time() - self.created_time > self.expire_time
def to_dict(self) -> Dict[str, Any]:
"""转换为字典"""
return {
'session_id': self.session_id,
'status': self.status,
'qr_code_url': self.qr_code_url,
'created_time': self.created_time,
'is_expired': self.is_expired()
}
class QRLoginManager:
"""二维码登录管理器"""
def __init__(self):
self.sessions: Dict[str, QRLoginSession] = {}
self.headers = generate_headers()
self.host = "https://passport.goofish.com"
self.api_mini_login = f"{self.host}/mini_login.htm"
self.api_generate_qr = f"{self.host}/newlogin/qrcode/generate.do"
self.api_scan_status = f"{self.host}/newlogin/qrcode/query.do"
self.api_h5_tk = "https://h5api.m.goofish.com/h5/mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get/1.0/"
# 配置代理(如果需要的话,取消注释并修改代理地址)
# self.proxy = "http://127.0.0.1:7890"
self.proxy = None
# 配置超时时间
self.timeout = httpx.Timeout(connect=30.0, read=60.0, write=30.0, pool=60.0)
def _cookie_marshal(self, cookies: dict) -> str:
"""将Cookie字典转换为字符串"""
return "; ".join([f"{k}={v}" for k, v in cookies.items()])
async def _get_mh5tk(self, session: QRLoginSession) -> dict:
"""获取m_h5_tk和m_h5_tk_enc"""
data = {"bizScene": "home"}
data_str = json.dumps(data, separators=(',', ':'))
t = str(int(time.time() * 1000))
app_key = "34839810"
# 先发一次 GET 请求,获取 cookie 中的 m_h5_tk
async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True, proxy=self.proxy) as client:
try:
resp = await client.get(self.api_h5_tk, headers=self.headers)
cookies = {k: v for k, v in resp.cookies.items()}
session.cookies.update(cookies)
m_h5_tk = cookies.get("m_h5_tk", "")
token = m_h5_tk.split("_")[0] if "_" in m_h5_tk else ""
# 生成签名
sign_input = f"{token}&{t}&{app_key}&{data_str}"
sign = hashlib.md5(sign_input.encode()).hexdigest()
# 构造最终请求参数
params = {
"jsv": "2.7.2",
"appKey": app_key,
"t": t,
"sign": sign,
"v": "1.0",
"type": "originaljson",
"dataType": "json",
"timeout": 20000,
"api": "mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get",
"data": data_str,
}
# 发请求正式获取数据,确保 token 有效
await client.post(self.api_h5_tk, params=params, headers=self.headers, cookies=session.cookies)
return cookies
except httpx.ConnectTimeout:
logger.error("获取m_h5_tk时连接超时")
raise
except httpx.ReadTimeout:
logger.error("获取m_h5_tk时读取超时")
raise
except httpx.ConnectError:
logger.error("获取m_h5_tk时连接错误")
raise
async def _get_login_params(self, session: QRLoginSession) -> dict:
"""获取二维码登录时需要的表单参数"""
params = {
"lang": "zh_cn",
"appName": "xianyu",
"appEntrance": "web",
"styleType": "vertical",
"bizParams": "",
"notLoadSsoView": False,
"notKeepLogin": False,
"isMobile": False,
"qrCodeFirst": False,
"stie": 77,
"rnd": random(),
}
async with httpx.AsyncClient(follow_redirects=True, timeout=self.timeout, proxy=self.proxy) as client:
try:
resp = await client.get(
self.api_mini_login,
params=params,
cookies=session.cookies,
headers=self.headers,
)
# 正则匹配需要的json数据
pattern = r"window\.viewData\s*=\s*(\{.*?\});"
match = re.search(pattern, resp.text)
if match:
json_string = match.group(1)
view_data = json.loads(json_string)
data = view_data.get("loginFormData")
if data:
data["umidTag"] = "SERVER"
session.params.update(data)
return data
else:
raise GetLoginParamsError("未找到loginFormData")
else:
raise GetLoginParamsError("获取登录参数失败")
except httpx.ConnectTimeout:
logger.error("获取登录参数时连接超时")
raise
except httpx.ReadTimeout:
logger.error("获取登录参数时读取超时")
raise
except httpx.ConnectError:
logger.error("获取登录参数时连接错误")
raise
async def generate_qr_code(self) -> Dict[str, Any]:
"""生成二维码"""
try:
# 创建新的会话
session_id = str(uuid.uuid4())
session = QRLoginSession(session_id)
# 1. 获取m_h5_tk
await self._get_mh5tk(session)
logger.info(f"获取m_h5_tk成功: {session_id}")
# 2. 获取登录参数
login_params = await self._get_login_params(session)
logger.info(f"获取登录参数成功: {session_id}")
# 3. 生成二维码
async with httpx.AsyncClient(follow_redirects=True, timeout=self.timeout, proxy=self.proxy) as client:
resp = await client.get(
self.api_generate_qr,
params=login_params,
headers=self.headers
)
logger.debug(f"[调试] 获取二维码接口原始响应: {resp.text}")
try:
results = resp.json()
logger.debug(f"[调试] 获取二维码接口解析后: {json.dumps(results, ensure_ascii=False)}")
except Exception as e:
logger.exception("二维码接口返回不是JSON")
raise GetLoginQRCodeError(f"二维码接口返回异常: {resp.text}")
if results.get("content", {}).get("success") == True:
# 更新会话参数
session.params.update({
"t": results["content"]["data"]["t"],
"ck": results["content"]["data"]["ck"],
})
# 获取二维码内容
qr_content = results["content"]["data"]["codeContent"]
session.qr_content = qr_content
# 生成二维码图片(base64格式)
qr = qrcode.QRCode(
version=5,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=2,
)
qr.add_data(qr_content)
qr.make()
# 将二维码转换为base64
from io import BytesIO
import base64
qr_img = qr.make_image()
buffer = BytesIO()
qr_img.save(buffer, format='PNG')
qr_base64 = base64.b64encode(buffer.getvalue()).decode()
qr_data_url = f"data:image/png;base64,{qr_base64}"
session.qr_code_url = qr_data_url
session.status = 'waiting'
# 保存会话
self.sessions[session_id] = session
# 启动状态检查任务
asyncio.create_task(self._monitor_qr_status(session_id))
logger.info(f"二维码生成成功: {session_id}")
return {
'success': True,
'session_id': session_id,
'qr_code_url': qr_data_url
}
else:
raise GetLoginQRCodeError("获取登录二维码失败")
except httpx.ConnectTimeout as e:
logger.error(f"连接超时: {e}")
return {'success': False, 'message': f'连接超时,请检查网络或尝试使用代理'}
except httpx.ReadTimeout as e:
logger.error(f"读取超时: {e}")
return {'success': False, 'message': f'读取超时,服务器响应过慢'}
except httpx.ConnectError as e:
logger.error(f"连接错误: {e}")
return {'success': False, 'message': f'连接错误,请检查网络或代理设置'}
except Exception as e:
logger.exception("二维码生成过程中发生异常")
return {'success': False, 'message': f'生成二维码失败: {str(e)}'}
async def _poll_qrcode_status(self, session: QRLoginSession) -> httpx.Response:
"""获取二维码扫描状态"""
async with httpx.AsyncClient(follow_redirects=True, timeout=self.timeout, proxy=self.proxy) as client:
resp = await client.post(
self.api_scan_status,
data=session.params,
cookies=session.cookies,
headers=self.headers,
)
return resp
async def _monitor_qr_status(self, session_id: str):
"""监控二维码状态"""
try:
session = self.sessions.get(session_id)
if not session:
return
logger.info(f"开始监控二维码状态: {session_id}")
# 监控登录状态
max_wait_time = 300 # 5分钟
start_time = time.time()
while time.time() - start_time < max_wait_time:
try:
# 检查会话是否还存在
if session_id not in self.sessions:
break
# 轮询二维码状态
resp = await self._poll_qrcode_status(session)
qrcode_status = (
resp.json()
.get("content", {})
.get("data", {})
.get("qrCodeStatus")
)
if qrcode_status == "CONFIRMED":
# 登录确认
if (
resp.json()
.get("content", {})
.get("data", {})
.get("iframeRedirect")
is True
):
# 账号被风控,需要手机验证
session.status = 'verification_required'
iframe_url = (
resp.json()
.get("content", {})
.get("data", {})
.get("iframeRedirectUrl")
)
session.verification_url = iframe_url
logger.warning(f"账号被风控,需要手机验证: {session_id}, URL: {iframe_url}")
break
else:
# 登录成功
session.status = 'success'
# 保存Cookie
for k, v in resp.cookies.items():
session.cookies[k] = v
if k == 'unb':
session.unb = v
logger.info(f"扫码登录成功: {session_id}, UNB: {session.unb}")
break
elif qrcode_status == "NEW":
# 二维码未被扫描,继续轮询
continue
elif qrcode_status == "EXPIRED":
# 二维码已过期
session.status = 'expired'
logger.info(f"二维码已过期: {session_id}")
break
elif qrcode_status == "SCANED":
# 二维码已被扫描,等待确认
if session.status == 'waiting':
session.status = 'scanned'
logger.info(f"二维码已扫描,等待确认: {session_id}")
else:
# 用户取消确认
session.status = 'cancelled'
logger.info(f"用户取消登录: {session_id}")
break
await asyncio.sleep(0.8) # 每0.8秒检查一次
except Exception as e:
logger.error(f"监控二维码状态异常: {e}")
await asyncio.sleep(2)
# 超时处理
if session.status not in ['success', 'expired', 'cancelled', 'verification_required']:
session.status = 'expired'
logger.info(f"二维码监控超时,标记为过期: {session_id}")
except Exception as e:
logger.error(f"监控二维码状态失败: {e}")
if session_id in self.sessions:
self.sessions[session_id].status = 'expired'
def get_session_status(self, session_id: str) -> Dict[str, Any]:
"""获取会话状态"""
session = self.sessions.get(session_id)
if not session:
return {'status': 'not_found'}
if session.is_expired() and session.status != 'success':
session.status = 'expired'
result = {
'status': session.status,
'session_id': session_id
}
# 如果需要验证,返回验证URL
if session.status == 'verification_required' and session.verification_url:
result['verification_url'] = session.verification_url
result['message'] = '账号被风控,需要手机验证'
# 如果登录成功,返回Cookie信息
if session.status == 'success' and session.cookies and session.unb:
result['cookies'] = self._cookie_marshal(session.cookies)
result['unb'] = session.unb
return result
def cleanup_expired_sessions(self):
"""清理过期会话"""
expired_sessions = []
for session_id, session in self.sessions.items():
if session.is_expired():
expired_sessions.append(session_id)
for session_id in expired_sessions:
del self.sessions[session_id]
logger.info(f"清理过期会话: {session_id}")
def get_session_cookies(self, session_id: str) -> Optional[Dict[str, str]]:
"""获取会话Cookie"""
session = self.sessions.get(session_id)
if session and session.status == 'success':
return {
'cookies': self._cookie_marshal(session.cookies),
'unb': session.unb
}
return None
# 全局二维码登录管理器实例
qr_login_manager = QRLoginManager()
+215
View File
@@ -0,0 +1,215 @@
#!/usr/bin/env python3
"""
闲鱼用户资料获取工具
用于获取用户昵称和头像
"""
import json
import time
import hashlib
from typing import Optional, Dict, Any
import httpx
from loguru import logger
from .xianyu_utils import trans_cookies, generate_sign
class UserProfileFetcher:
"""闲鱼用户资料获取器"""
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'Referer': 'https://www.goofish.com/',
'Origin': 'https://www.goofish.com',
}
self.timeout = httpx.Timeout(connect=30.0, read=60.0, write=30.0, pool=60.0)
async def get_user_profile(self, cookies_str: str) -> Optional[Dict[str, Any]]:
"""获取用户资料(昵称和头像)
Args:
cookies_str: Cookie字符串
Returns:
包含nickname和avatar_url的字典,失败返回None
"""
try:
# 解析Cookie
cookies_dict = trans_cookies(cookies_str)
unb = cookies_dict.get('unb')
if not unb:
logger.error("Cookie中缺少unb字段")
return None
# 获取m_h5_tk用于签名
m_h5_tk = cookies_dict.get('_m_h5_tk', '')
token = m_h5_tk.split('_')[0] if '_' in m_h5_tk else ''
if not token:
logger.warning("Cookie中缺少m_h5_tk,尝试获取...")
# 尝试获取m_h5_tk
token = await self._get_m_h5_tk(cookies_dict)
if not token:
logger.error("无法获取m_h5_tk")
return None
# 构造请求参数
t = str(int(time.time() * 1000))
app_key = "34839810"
# 尝试多个可能的API端点
api_endpoints = [
'mtop.idle.web.xyh.info',
'mtop.idle.user.profile',
'mtop.taobao.user.get',
]
for api_name in api_endpoints:
try:
result = await self._call_api(api_name, unb, t, token, app_key, cookies_dict)
if result:
logger.info(f"获取用户资料成功: {api_name}")
return result
except Exception as e:
logger.debug(f"API {api_name} 调用失败: {e}")
continue
logger.error("所有用户资料API都失败")
return None
except Exception as e:
logger.error(f"获取用户资料异常: {e}")
return None
async def _get_m_h5_tk(self, cookies_dict: Dict[str, str]) -> Optional[str]:
"""获取m_h5_tk"""
try:
api_url = "https://h5api.m.goofish.com/h5/mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get/1.0/"
async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True) as client:
# 先发一次请求获取cookie中的m_h5_tk
resp = await client.get(api_url, headers=self.headers, cookies=cookies_dict)
new_cookies = dict(resp.cookies)
m_h5_tk = new_cookies.get("m_h5_tk", "")
if m_h5_tk:
token = m_h5_tk.split("_")[0] if "_" in m_h5_tk else ""
return token
return None
except Exception as e:
logger.error(f"获取m_h5_tk失败: {e}")
return None
async def _call_api(self, api_name: str, unb: str, t: str, token: str, app_key: str, cookies_dict: Dict[str, str]) -> Optional[Dict[str, Any]]:
"""调用闲鱼API"""
api_url = f"https://h5api.m.goofish.com/h5/{api_name}/1.0/"
# 构造请求数据
data = {"userId": unb}
data_str = json.dumps(data, separators=(',', ':'))
# 生成签名
sign = generate_sign(t, token, data_str)
# 构造请求参数
params = {
'jsv': '2.7.2',
'appKey': app_key,
't': t,
'sign': sign,
'v': '1.0',
'type': 'originaljson',
'accountSite': 'xianyu',
'dataType': 'json',
'timeout': '20000',
'api': api_name,
'sessionOption': 'AutoLoginOnly',
}
async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True) as client:
resp = await client.post(
api_url,
params=params,
data={'data': data_str},
headers=self.headers,
cookies=cookies_dict
)
result = resp.json()
# 检查API响应
if result.get('ret', [])[0].startswith('SUCCESS'):
data = result.get('data', {})
# 尝试从不同的API响应格式中提取用户信息
user_info = self._extract_user_info(data)
if user_info:
return user_info
logger.debug(f"API {api_name} 响应: {result}")
return None
def _extract_user_info(self, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""从API响应中提取用户信息"""
# 尝试不同的数据结构
user_data = None
# 结构1: data.user
if 'user' in data:
user_data = data['user']
# 结构2: data.userInfo
elif 'userInfo' in data:
user_data = data['userInfo']
# 结构3: data.data.user
elif 'data' in data and 'user' in data['data']:
user_data = data['data']['user']
# 结构4: 直接在data中
elif 'nick' in data or 'nickname' in data:
user_data = data
if not user_data:
return None
# 提取昵称
nickname = (
user_data.get('nick') or
user_data.get('nickname') or
user_data.get('userName') or
user_data.get('name') or
''
)
# 提取头像
avatar_url = (
user_data.get('avatar') or
user_data.get('avatarUrl') or
user_data.get('headUrl') or
user_data.get('picUrl') or
''
)
if nickname or avatar_url:
return {
'nickname': nickname,
'avatar_url': avatar_url
}
return None
# 全局实例
user_profile_fetcher = UserProfileFetcher()
async def get_user_profile_from_cookies(cookies_str: str) -> Optional[Dict[str, Any]]:
"""从Cookie获取用户资料的便捷函数"""
return await user_profile_fetcher.get_user_profile(cookies_str)
+89
View File
@@ -0,0 +1,89 @@
import asyncio
import websockets
from typing import Optional, Dict, Any, Callable
from loguru import logger
class WebSocketClient:
def __init__(self, url: str, headers: Dict[str, str], on_message: Callable[[Dict[str, Any]], None]):
"""初始化WebSocket客户端"""
self.url = url
self.headers = headers
self.on_message = on_message
self.websocket: Optional[websockets.WebSocketClientProtocol] = None
self.is_connected = False
self.reconnect_delay = 5 # 重连延迟,单位秒
async def connect(self):
"""建立WebSocket连接"""
try:
self.websocket = await websockets.connect(
self.url,
extra_headers=self.headers,
ping_interval=None,
ping_timeout=None
)
self.is_connected = True
logger.info("WebSocket连接建立成功")
return True
except Exception as e:
logger.error(f"WebSocket连接失败: {e}")
return False
async def disconnect(self):
"""关闭WebSocket连接"""
if self.websocket:
await self.websocket.close()
self.is_connected = False
logger.info("WebSocket连接已关闭")
async def send(self, message: str):
"""发送消息"""
if not self.is_connected:
logger.warning("WebSocket未连接,无法发送消息")
return False
try:
await self.websocket.send(message)
return True
except Exception as e:
logger.error(f"消息发送失败: {e}")
self.is_connected = False
return False
async def receive(self):
"""接收消息"""
if not self.is_connected:
logger.warning("WebSocket未连接,无法接收消息")
return None
try:
message = await self.websocket.recv()
return message
except Exception as e:
logger.error(f"消息接收失败: {e}")
self.is_connected = False
return None
async def reconnect(self):
"""重新连接"""
logger.info(f"准备在{self.reconnect_delay}秒后重新连接...")
await asyncio.sleep(self.reconnect_delay)
return await self.connect()
async def run(self):
"""运行WebSocket客户端"""
while True:
if not self.is_connected:
success = await self.connect()
if not success:
await self.reconnect()
continue
try:
message = await self.receive()
if message:
await self.on_message(message)
except Exception as e:
logger.error(f"消息处理失败: {e}")
await self.disconnect()
await self.reconnect()
+379
View File
@@ -0,0 +1,379 @@
import base64
import json
import subprocess
from functools import partial
import time
import hashlib
import struct
import os
from typing import Any, Dict, List
import blackboxprotobuf
from loguru import logger
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
import execjs
def get_js_path():
"""获取JavaScript文件的路径"""
current_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(current_dir)
js_path = os.path.join(root_dir, 'static', 'xianyu_js_version_2.js')
return js_path
try:
# 检查JavaScript运行时是否可用
available_runtimes = execjs.runtime_names
logger.info(f"可用的JavaScript运行时: {available_runtimes}")
# 尝试获取默认运行时
current_runtime = execjs.get()
logger.info(f"当前JavaScript运行时: {current_runtime.name}")
xianyu_js = execjs.compile(open(get_js_path(), 'r', encoding='utf-8').read())
logger.info("JavaScript文件加载成功")
except Exception as e:
error_msg = str(e)
logger.error(f"JavaScript运行时错误: {error_msg}")
if "Could not find an available JavaScript runtime" in error_msg:
logger.error("解决方案:")
logger.error("1. 确保已安装Node.js: apt-get install nodejs")
logger.error("2. 或安装其他JS运行时: apt-get install nodejs npm")
logger.error("3. 检查PATH环境变量是否包含Node.js路径")
# 尝试检测系统中的JavaScript运行时
import subprocess
try:
result = subprocess.run(['node', '--version'], capture_output=True, text=True)
if result.returncode == 0:
logger.info(f"检测到Node.js版本: {result.stdout.strip()}")
else:
logger.error("Node.js未正确安装或不在PATH中")
except FileNotFoundError:
logger.error("未找到Node.js可执行文件")
raise RuntimeError(f"无法加载JavaScript文件: {error_msg}")
def trans_cookies(cookies_str: str) -> dict:
"""将cookies字符串转换为字典"""
if not cookies_str:
raise ValueError("cookies不能为空")
cookies = {}
for cookie in cookies_str.split("; "):
if "=" in cookie:
key, value = cookie.split("=", 1)
cookies[key] = value
return cookies
def generate_mid() -> str:
"""生成mid"""
import random
random_part = int(1000 * random.random())
timestamp = int(time.time() * 1000)
return f"{random_part}{timestamp} 0"
def generate_uuid() -> str:
"""生成uuid"""
timestamp = int(time.time() * 1000)
return f"-{timestamp}1"
def generate_device_id(user_id: str) -> str:
"""生成设备ID"""
import random
# 字符集
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
result = []
for i in range(36):
if i in [8, 13, 18, 23]:
result.append("-")
elif i == 14:
result.append("4")
else:
if i == 19:
# 对于位置19,需要特殊处理
rand_val = int(16 * random.random())
result.append(chars[(rand_val & 0x3) | 0x8])
else:
rand_val = int(16 * random.random())
result.append(chars[rand_val])
return ''.join(result) + "-" + user_id
def generate_sign(t: str, token: str, data: str) -> str:
"""生成签名"""
app_key = "34839810"
msg = f"{token}&{t}&{app_key}&{data}"
# 使用MD5生成签名
md5_hash = hashlib.md5()
md5_hash.update(msg.encode('utf-8'))
return md5_hash.hexdigest()
class MessagePackDecoder:
"""MessagePack解码器的纯Python实现"""
def __init__(self, data: bytes):
self.data = data
self.pos = 0
self.length = len(data)
def read_byte(self) -> int:
if self.pos >= self.length:
raise ValueError("Unexpected end of data")
byte = self.data[self.pos]
self.pos += 1
return byte
def read_bytes(self, count: int) -> bytes:
if self.pos + count > self.length:
raise ValueError("Unexpected end of data")
result = self.data[self.pos:self.pos + count]
self.pos += count
return result
def read_uint8(self) -> int:
return self.read_byte()
def read_uint16(self) -> int:
return struct.unpack('>H', self.read_bytes(2))[0]
def read_uint32(self) -> int:
return struct.unpack('>I', self.read_bytes(4))[0]
def read_uint64(self) -> int:
return struct.unpack('>Q', self.read_bytes(8))[0]
def read_int8(self) -> int:
return struct.unpack('>b', self.read_bytes(1))[0]
def read_int16(self) -> int:
return struct.unpack('>h', self.read_bytes(2))[0]
def read_int32(self) -> int:
return struct.unpack('>i', self.read_bytes(4))[0]
def read_int64(self) -> int:
return struct.unpack('>q', self.read_bytes(8))[0]
def read_float32(self) -> float:
return struct.unpack('>f', self.read_bytes(4))[0]
def read_float64(self) -> float:
return struct.unpack('>d', self.read_bytes(8))[0]
def read_string(self, length: int) -> str:
return self.read_bytes(length).decode('utf-8')
def decode_value(self) -> Any:
"""解码单个MessagePack值"""
if self.pos >= self.length:
raise ValueError("Unexpected end of data")
format_byte = self.read_byte()
# Positive fixint (0xxxxxxx)
if format_byte <= 0x7f:
return format_byte
# Fixmap (1000xxxx)
elif 0x80 <= format_byte <= 0x8f:
size = format_byte & 0x0f
return self.decode_map(size)
# Fixarray (1001xxxx)
elif 0x90 <= format_byte <= 0x9f:
size = format_byte & 0x0f
return self.decode_array(size)
# Fixstr (101xxxxx)
elif 0xa0 <= format_byte <= 0xbf:
size = format_byte & 0x1f
return self.read_string(size)
# nil
elif format_byte == 0xc0:
return None
# false
elif format_byte == 0xc2:
return False
# true
elif format_byte == 0xc3:
return True
# bin 8
elif format_byte == 0xc4:
size = self.read_uint8()
return self.read_bytes(size)
# bin 16
elif format_byte == 0xc5:
size = self.read_uint16()
return self.read_bytes(size)
# bin 32
elif format_byte == 0xc6:
size = self.read_uint32()
return self.read_bytes(size)
# float 32
elif format_byte == 0xca:
return self.read_float32()
# float 64
elif format_byte == 0xcb:
return self.read_float64()
# uint 8
elif format_byte == 0xcc:
return self.read_uint8()
# uint 16
elif format_byte == 0xcd:
return self.read_uint16()
# uint 32
elif format_byte == 0xce:
return self.read_uint32()
# uint 64
elif format_byte == 0xcf:
return self.read_uint64()
# int 8
elif format_byte == 0xd0:
return self.read_int8()
# int 16
elif format_byte == 0xd1:
return self.read_int16()
# int 32
elif format_byte == 0xd2:
return self.read_int32()
# int 64
elif format_byte == 0xd3:
return self.read_int64()
# str 8
elif format_byte == 0xd9:
size = self.read_uint8()
return self.read_string(size)
# str 16
elif format_byte == 0xda:
size = self.read_uint16()
return self.read_string(size)
# str 32
elif format_byte == 0xdb:
size = self.read_uint32()
return self.read_string(size)
# array 16
elif format_byte == 0xdc:
size = self.read_uint16()
return self.decode_array(size)
# array 32
elif format_byte == 0xdd:
size = self.read_uint32()
return self.decode_array(size)
# map 16
elif format_byte == 0xde:
size = self.read_uint16()
return self.decode_map(size)
# map 32
elif format_byte == 0xdf:
size = self.read_uint32()
return self.decode_map(size)
# Negative fixint (111xxxxx)
elif format_byte >= 0xe0:
return format_byte - 0x100
raise ValueError(f"Unknown format byte: {format_byte:02x}")
def decode_array(self, size: int) -> List[Any]:
"""解码数组"""
return [self.decode_value() for _ in range(size)]
def decode_map(self, size: int) -> Dict[Any, Any]:
"""解码字典"""
result = {}
for _ in range(size):
key = self.decode_value()
value = self.decode_value()
result[key] = value
return result
def decode(self) -> Any:
"""解码整个MessagePack数据"""
return self.decode_value()
def decrypt(data: str) -> str:
"""解密消息数据"""
import json as json_module # 使用别名避免作用域冲突
try:
# 确保输入数据是字符串类型
if not isinstance(data, str):
data = str(data)
# 清理数据,移除可能的非ASCII字符
try:
# 尝试编码为ASCII,如果失败则使用UTF-8编码后再解码
data.encode('ascii')
except UnicodeEncodeError:
# 如果包含非ASCII字符,先编码为UTF-8字节,再解码为ASCII兼容的字符串
data = data.encode('utf-8', errors='ignore').decode('ascii', errors='ignore')
# Base64解码
try:
decoded_data = base64.b64decode(data)
except Exception as decode_error:
# 如果base64解码失败,尝试添加填充
missing_padding = len(data) % 4
if missing_padding:
data += '=' * (4 - missing_padding)
decoded_data = base64.b64decode(data)
# 使用MessagePack解码器解码数据
decoder = MessagePackDecoder(decoded_data)
decoded_value = decoder.decode()
# 如果解码后的值是字典,转换为JSON字符串
if isinstance(decoded_value, dict):
def json_serializer(obj):
if isinstance(obj, bytes):
return obj.decode('utf-8', errors='ignore')
raise TypeError(f"Type {type(obj)} not serializable")
return json_module.dumps(decoded_value, default=json_serializer, ensure_ascii=False)
# 如果是其他类型,尝试转换为字符串
return str(decoded_value)
except Exception as e:
raise Exception(f"解密失败: {str(e)}")
if __name__ == '__main__':
msg = "ggGLAYEBsjMxNDk2MzcwNjNAZ29vZmlzaAKzNDc5ODMzODkwOTZAZ29vZmlzaAOxMzQxNjU2NTI3NDU0Mi5QTk0EAAXPAAABlbKji20GggFlA4UBoAK6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl0DoAQaBdoEKnsiY29udGVudFR5cGUiOjI2LCJkeENhcmQiOnsiaXRlbSI6eyJtYWluIjp7ImNsaWNrUGFyYW0iOnsiYXJnMSI6Ik1zZ0NhcmQiLCJhcmdzIjp7InNvdXJjZSI6ImltIiwidGFza19pZCI6IjNleFFKSE9UbVBVMSIsIm1zZ19pZCI6ImNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczIn19LCJleENvbnRlbnQiOnsiYmdDb2xvciI6IiNGRkZGRkYiLCJidXR0b24iOnsiYmdDb2xvciI6IiNGRkU2MEYiLCJib3JkZXJDb2xvciI6IiNGRkU2MEYiLCJjbGlja1BhcmFtIjp7ImFyZzEiOiJNc2dDYXJkQWN0aW9uIiwiYXJncyI6eyJzb3VyY2UiOiJpbSIsInRhc2tfaWQiOiIzZXhRSkhPVG1QVTEiLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9fSwiZm9udENvbG9yIjoiIzMzMzMzMyIsInRhcmdldFVybCI6ImZsZWFtYXJrZXQ6Ly9hZGp1c3RfcHJpY2U/Zmx1dHRlcj10cnVlJmJpek9yZGVySWQ9MjUwMzY4ODEyNjM1NjYzNjM3MCIsInRleHQiOiLkv67mlLnku7fmoLwifSwiZGVzYyI6Iuivt+WPjOaWueayn+mAmuWPiuaXtuehruiupOS7t+agvCIsImRlc2NDb2xvciI6IiNBM0EzQTMiLCJ0aXRsZSI6IuaIkeW3suaLjeS4i++8jOW+heS7mOasviIsInVwZ3JhZGUiOnsidGFyZ2V0VXJsIjoiaHR0cHM6Ly9oNS5tLmdvb2Zpc2guY29tL2FwcC9pZGxlRmlzaC1GMmUvZm0tZG93bmxhb2QvaG9tZS5odG1sP25vUmVkcmllY3Q9dHJ1ZSZjYW5CYWNrPXRydWUmY2hlY2tWZXJzaW9uPXRydWUiLCJ2ZXJzaW9uIjoiNy43LjkwIn19LCJ0YXJnZXRVcmwiOiJmbGVhbWFya2V0Oi8vb3JkZXJfZGV0YWlsP2lkPTI1MDM2ODgxMjYzNTY2MzYzNzAmcm9sZT1zZWxsZXIifX0sInRlbXBsYXRlIjp7Im5hbWUiOiJpZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZCIsInVybCI6Imh0dHBzOi8vZGluYW1pY3guYWxpYmFiYXVzZXJjb250ZW50LmNvbS9wdWIvaWRsZWZpc2hfbWVzc2FnZV90cmFkZV9jaGF0X2NhcmQvMTY2NzIyMjA1Mjc2Ny9pZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZC56aXAiLCJ2ZXJzaW9uIjoiMTY2NzIyMjA1Mjc2NyJ9fX0HAQgBCQAK3gAQpmJpelRhZ9oAe3sic291cmNlSWQiOiJDMkM6M2V4UUpIT1RtUFUxIiwidGFza05hbWUiOiLlt7Lmi43kuItf5pyq5LuY5qy+X+WNluWutiIsIm1hdGVyaWFsSWQiOiIzZXhRSkhPVG1QVTEiLCJ0YXNrSWQiOiIzZXhRSkhPVG1QVTEifbFjbG9zZVB1c2hSZWNlaXZlcqVmYWxzZbFjbG9zZVVucmVhZE51bWJlcqVmYWxzZaxkZXRhaWxOb3RpY2W6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2nZXh0SnNvbtoBr3sibXNnQXJncyI6eyJ0YXNrX2lkIjoiM2V4UUpIT1RtUFUxIiwic291cmNlIjoiaW0iLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9LCJxdWlja1JlcGx5IjoiMSIsIm1zZ0FyZzEiOiJNc2dDYXJkIiwidXBkYXRlS2V5IjoiNDc5ODMzODkwOTY6MjUwMzY4ODEyNjM1NjYzNjM3MDoxX25vdF9wYXlfc2VsbGVyIiwibWVzc2FnZUlkIjoiY2M4YmMyZGY3YzkzNGRmMDg2ZTA1NjdjYjY5ZjE1NzMiLCJtdWx0aUNoYW5uZWwiOnsiaHVhd2VpIjoiRVhQUkVTUyIsInhpYW9taSI6IjEwODAwMCIsIm9wcG8iOiJFWFBSRVNTIiwiaG9ub3IiOiJOT1JNQUwiLCJhZ29vIjoicHJvZHVjdCIsInZpdm8iOiJPUkRFUiJ9LCJjb250ZW50VHlwZSI6IjI2IiwiY29ycmVsYXRpb25Hcm91cElkIjoiM2V4UUpIT1RtUFUxX0ZGcjRHT1NuOE9RbyJ9qHJlY2VpdmVyrTIyMDI2NDA5MTgwNzmrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMa9yZW1pbmRlckNvbnRlbnS6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2ucmVtaW5kZXJOb3RpY2W75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+rXJlbWluZGVyVGl0bGW75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+q3JlbWluZGVyVXJs2gCaZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9OTAwMDUyNjQ0Mjc3JnBlZXJVc2VySWQ9MzE0OTYzNzA2MyZwZWVyVXNlck5pY2s955S3KioqeSZzaWQ9NDc5ODMzODkwOTYmbWVzc2FnZUlkPWNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczJmFkdj1ub6xzZW5kZXJVc2VySWSqMzE0OTYzNzA2M65zZW5kZXJVc2VyVHlwZaEwq3Nlc3Npb25UeXBloTGqdXBkYXRlSGVhZKR0cnVlDAEDgahuZWVkUHVzaKR0cnVl"
msg = "ggGLAYEBsjMxNDk2MzcwNjNAZ29vZmlzaAKzNDc5ODMzODkwOTZAZ29vZmlzaAOxMzQxNjU2NTI3NDU0Mi5QTk0EAAXPAAABlbKji20GggFlA4UBoAK6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl0DoAQaBdoEKnsiY29udGVudFR5cGUiOjI2LCJkeENhcmQiOnsiaXRlbSI6eyJtYWluIjp7ImNsaWNrUGFyYW0iOnsiYXJnMSI6Ik1zZ0NhcmQiLCJhcmdzIjp7InNvdXJjZSI6ImltIiwidGFza19pZCI6IjNleFFKSE9UbVBVMSIsIm1zZ19pZCI6ImNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczIn19LCJleENvbnRlbnQiOnsiYmdDb2xvciI6IiNGRkZGRkYiLCJidXR0b24iOnsiYmdDb2xvciI6IiNGRkU2MEYiLCJib3JkZXJDb2xvciI6IiNGRkU2MEYiLCJjbGlja1BhcmFtIjp7ImFyZzEiOiJNc2dDYXJkQWN0aW9uIiwiYXJncyI6eyJzb3VyY2UiOiJpbSIsInRhc2tfaWQiOiIzZXhRSkhPVG1QVTEiLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9fSwiZm9udENvbG9yIjoiIzMzMzMzMyIsInRhcmdldFVybCI6ImZsZWFtYXJrZXQ6Ly9hZGp1c3RfcHJpY2U/Zmx1dHRlcj10cnVlJmJpek9yZGVySWQ9MjUwMzY4ODEyNjM1NjYzNjM3MCIsInRleHQiOiLkv67mlLnku7fmoLwifSwiZGVzYyI6Iuivt+WPjOaWueayn+mAmuWPiuaXtuehruiupOS7t+agvCIsImRlc2NDb2xvciI6IiNBM0EzQTMiLCJ0aXRsZSI6IuaIkeW3suaLjeS4i++8jOW+heS7mOasviIsInVwZ3JhZGUiOnsidGFyZ2V0VXJsIjoiaHR0cHM6Ly9oNS5tLmdvb2Zpc2guY29tL2FwcC9pZGxlRmlzaC1GMmUvZm0tZG93bmxhb2QvaG9tZS5odG1sP25vUmVkcmllY3Q9dHJ1ZSZjYW5CYWNrPXRydWUmY2hlY2tWZXJzaW9uPXRydWUiLCJ2ZXJzaW9uIjoiNy43LjkwIn19LCJ0YXJnZXRVcmwiOiJmbGVhbWFya2V0Oi8vb3JkZXJfZGV0YWlsP2lkPTI1MDM2ODgxMjYzNTY2MzYzNzAmcm9sZT1zZWxsZXIifX0sInRlbXBsYXRlIjp7Im5hbWUiOiJpZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZCIsInVybCI6Imh0dHBzOi8vZGluYW1pY3guYWxpYmFiYXVzZXJjb250ZW50LmNvbS9wdWIvaWRsZWZpc2hfbWVzc2FnZV90cmFkZV9jaGF0X2NhcmQvMTY2NzIyMjA1Mjc2Ny9pZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZC56aXAiLCJ2ZXJzaW9uIjoiMTY2NzIyMjA1Mjc2NyJ9fX0HAQgBCQAK3gAQpmJpelRhZ9oAe3sic291cmNlSWQiOiJDMkM6M2V4UUpIT1RtUFUxIiwidGFza05hbWUiOiLlt7Lmi43kuItf5pyq5LuY5qy+X+WNluWutiIsIm1hdGVyaWFsSWQiOiIzZXhRSkhPVG1QVTEiLCJ0YXNrSWQiOiIzZXhRSkhPVG1QVTEifbFjbG9zZVB1c2hSZWNlaXZlcqVmYWxzZbFjbG9zZVVucmVhZE51bWJlcqVmYWxzZaxkZXRhaWxOb3RpY2W6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2nZXh0SnNvbtoBr3sibXNnQXJncyI6eyJ0YXNrX2lkIjoiM2V4UUpIT1RtUFUxIiwic291cmNlIjoiaW0iLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9LCJxdWlja1JlcGx5IjoiMSIsIm1zZ0FyZzEiOiJNc2dDYXJkIiwidXBkYXRlS2V5IjoiNDc5ODMzODkwOTY6MjUwMzY4ODEyNjM1NjYzNjM3MDoxX25vdF9wYXlfc2VsbGVyIiwibWVzc2FnZUlkIjoiY2M4YmMyZGY3YzkzNGRmMDg2ZTA1NjdjYjY5ZjE1NzMiLCJtdWx0aUNoYW5uZWwiOnsiaHVhd2VpIjoiRVhQUkVTUyIsInhpYW9taSI6IjEwODAwMCIsIm9wcG8iOiJFWFBSRVNTIiwiaG9ub3IiOiJOT1JNQUwiLCJhZ29vIjoicHJvZHVjdCIsInZpdm8iOiJPUkRFUiJ9LCJjb250ZW50VHlwZSI6IjI2IiwiY29ycmVsYXRpb25Hcm91cElkIjoiM2V4UUpIT1RtUFUxX0ZGcjRHT1NuOE9RbyJ9qHJlY2VpdmVyrTIyMDI2NDA5MTgwNzmrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMa9yZW1pbmRlckNvbnRlbnS6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2ucmVtaW5kZXJOb3RpY2W75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+rXJlbWluZGVyVGl0bGW75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+q3JlbWluZGVyVXJs2gCaZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9OTAwMDUyNjQ0Mjc3JnBlZXJVc2VySWQ9MzE0OTYzNzA2MyZwZWVyVXNlck5pY2s955S3KioqeSZzaWQ9NDc5ODMzODkwOTYmbWVzc2FnZUlkPWNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczJmFkdj1ub6xzZW5kZXJVc2VySWSqMzE0OTYzNzA2M65zZW5kZXJVc2VyVHlwZaEwq3Nlc3Npb25UeXBloTGqdXBkYXRlSGVhZKR0cnVlDAEDgahuZWVkUHVzaKR0cnVl"
res = decrypt(msg)
print(res)