diff --git a/ADMIN_FEATURES_SUMMARY.md b/ADMIN_FEATURES_SUMMARY.md deleted file mode 100644 index d65223b..0000000 --- a/ADMIN_FEATURES_SUMMARY.md +++ /dev/null @@ -1,264 +0,0 @@ -# 管理员功能总结 - -## 🎯 新增功能概述 - -为闲鱼自动回复系统新增了完整的管理员功能,包括用户管理和日志管理,这些功能只有admin用户可以访问。 - -## 📊 功能详情 - -### 1. 用户管理功能 - -#### 🔗 访问路径 -- **URL**: `/user_management.html` -- **权限**: 仅限admin用户 -- **菜单位置**: 主页侧边栏 → 管理员功能 → 用户管理 - -#### ✨ 主要功能 -1. **用户列表查看** - - 显示所有注册用户信息 - - 用户名、邮箱、注册时间 - - Cookie数量、卡券数量统计 - - 用户类型标识(管理员/普通用户) - -2. **用户删除功能** - - 删除普通用户账号 - - 级联删除用户所有数据: - - 所有Cookie账号 - - 所有卡券 - - 所有关键字和回复设置 - - 所有个人设置 - - 所有相关业务数据 - - 管理员账号保护(不可删除) - -3. **系统统计信息** - - 总用户数 - - 总Cookie数 - - 总卡券数 - - 系统运行状态 - -#### 🛡️ 安全特性 -- **权限验证**: 只有admin用户可以访问 -- **管理员保护**: 不能删除管理员自己 -- **确认机制**: 删除用户需要二次确认 -- **数据完整性**: 级联删除保证数据一致性 - -### 2. 日志管理功能 - -#### 🔗 访问路径 -- **URL**: `/log_management.html` -- **权限**: 仅限admin用户 -- **菜单位置**: 主页侧边栏 → 管理员功能 → 系统日志 - -#### ✨ 主要功能 -1. **日志查看** - - 实时查看系统运行日志 - - 支持50-1000行日志显示 - - 彩色日志级别显示 - - 用户操作追踪 - -2. **日志过滤** - - 按日志级别过滤(INFO、WARNING、ERROR、DEBUG) - - 快速切换过滤条件 - - 实时过滤结果 - -3. **自动刷新** - - 可开启5秒自动刷新 - - 实时监控系统状态 - - 自动滚动到最新日志 - -4. **日志导航** - - 快速跳转到顶部/底部 - - 日志文件信息显示 - - 最后更新时间显示 - -#### 🎨 界面特性 -- **终端风格**: 黑色背景,彩色文字 -- **级别颜色**: 不同日志级别不同颜色 -- **响应式设计**: 适配各种屏幕尺寸 -- **用户友好**: 直观的操作界面 - -## 🔧 技术实现 - -### 后端API接口 - -#### 用户管理接口 -```python -# 获取所有用户 -GET /admin/users -# 删除用户 -DELETE /admin/users/{user_id} -# 获取系统统计 -GET /admin/stats -``` - -#### 日志管理接口 -```python -# 获取系统日志 -GET /admin/logs?lines=100&level=info -``` - -#### 权限验证 -```python -def require_admin(current_user: Dict[str, Any] = Depends(get_current_user)): - """要求管理员权限""" - if current_user['username'] != 'admin': - raise HTTPException(status_code=403, detail="需要管理员权限") - return current_user -``` - -### 数据库支持 - -#### 新增方法 -```python -# 获取所有用户信息 -def get_all_users(self) - -# 根据ID获取用户 -def get_user_by_id(self, user_id: int) - -# 删除用户及所有相关数据 -def delete_user_and_data(self, user_id: int) -``` - -#### 级联删除逻辑 -1. 用户设置 (user_settings) -2. 卡券 (cards) -3. 发货规则 (delivery_rules) -4. 通知渠道 (notification_channels) -5. Cookie (cookies) -6. 关键字 (keywords) -7. 默认回复 (default_replies) -8. AI回复设置 (ai_reply_settings) -9. 消息通知 (message_notifications) -10. 用户本身 (users) - -### 前端实现 - -#### 权限检查 -```javascript -// 验证管理员权限 -function checkAdminPermission() { - // 检查token有效性 - // 验证用户名是否为admin - // 非管理员自动跳转 -} -``` - -#### 菜单显示控制 -```javascript -// 在主页面中动态显示管理员菜单 -if (result.username === 'admin') { - document.getElementById('adminMenuSection').style.display = 'block'; -} -``` - -## 📱 用户界面 - -### 用户管理页面 -- **现代化设计**: Bootstrap 5 + 渐变色彩 -- **卡片布局**: 每个用户一个卡片 -- **统计面板**: 顶部显示系统统计 -- **操作确认**: 删除操作需要确认 -- **响应式**: 适配手机和桌面 - -### 日志管理页面 -- **终端风格**: 模拟命令行界面 -- **实时更新**: 支持自动刷新 -- **过滤控制**: 直观的过滤按钮 -- **导航便利**: 快速跳转功能 - -## 🔒 安全机制 - -### 1. 权限验证 -- **后端验证**: 所有管理员接口都需要admin权限 -- **前端检查**: 页面加载时验证用户身份 -- **自动跳转**: 非管理员用户自动跳转到首页 - -### 2. 操作保护 -- **管理员保护**: 不能删除管理员自己 -- **确认机制**: 危险操作需要二次确认 -- **错误处理**: 完善的错误提示和处理 - -### 3. 数据安全 -- **事务处理**: 删除操作使用数据库事务 -- **级联删除**: 确保数据完整性 -- **日志记录**: 所有操作都有详细日志 - -## 📋 使用说明 - -### 1. 访问管理员功能 -1. 使用admin账号登录系统 -2. 在主页侧边栏查看"管理员功能"菜单 -3. 点击相应功能进入管理页面 - -### 2. 用户管理操作 -1. 查看用户列表和统计信息 -2. 点击"删除用户"按钮 -3. 在确认对话框中确认删除 -4. 系统自动删除用户及所有相关数据 - -### 3. 日志管理操作 -1. 选择显示行数(50-1000行) -2. 选择日志级别过滤 -3. 开启/关闭自动刷新 -4. 使用导航按钮快速跳转 - -## 🎯 应用场景 - -### 1. 用户管理 -- **清理无效用户**: 删除不活跃或测试用户 -- **用户统计分析**: 查看用户活跃度和资源使用 -- **系统维护**: 定期清理和优化用户数据 - -### 2. 日志监控 -- **故障排查**: 实时查看错误日志 -- **性能监控**: 监控系统运行状态 -- **用户行为分析**: 追踪用户操作记录 -- **安全审计**: 监控异常访问和操作 - -## 🚀 部署说明 - -### 1. 立即可用 -- 重启服务后功能立即生效 -- 无需额外配置 -- 兼容现有数据 - -### 2. 访问方式 -``` -用户管理: http://your-domain/user_management.html -日志管理: http://your-domain/log_management.html -``` - -### 3. 权限要求 -- 只有username为'admin'的用户可以访问 -- 其他用户访问会自动跳转到首页 - -## 📊 功能对比 - -| 功能 | 普通用户 | 管理员 | -|------|----------|--------| -| 查看自己的数据 | ✅ | ✅ | -| 管理自己的设置 | ✅ | ✅ | -| 查看所有用户 | ❌ | ✅ | -| 删除其他用户 | ❌ | ✅ | -| 查看系统日志 | ❌ | ✅ | -| 系统统计信息 | ❌ | ✅ | - -## 🎉 总结 - -通过本次更新,闲鱼自动回复系统现在具备了完整的管理员功能: - -### ✅ 主要成就 -1. **完整的用户管理**: 查看、删除用户及数据统计 -2. **强大的日志管理**: 实时查看、过滤、监控系统日志 -3. **严格的权限控制**: 只有admin用户可以访问 -4. **现代化界面**: 美观、易用的管理界面 -5. **安全的操作机制**: 完善的确认和保护机制 - -### 🎯 实用价值 -- **提升管理效率**: 集中化的用户和日志管理 -- **增强系统安全**: 严格的权限控制和操作保护 -- **便于故障排查**: 实时日志监控和过滤功能 -- **优化用户体验**: 直观的界面和操作流程 - -现在您的多用户闲鱼自动回复系统具备了企业级的管理功能!🎊 diff --git a/AI_REPLY_GUIDE.md b/AI回复指南.md similarity index 100% rename from AI_REPLY_GUIDE.md rename to AI回复指南.md diff --git a/COMPLETE_ISOLATION_ANALYSIS.md b/COMPLETE_ISOLATION_ANALYSIS.md deleted file mode 100644 index 3d7c6b0..0000000 --- a/COMPLETE_ISOLATION_ANALYSIS.md +++ /dev/null @@ -1,254 +0,0 @@ -# 多用户数据隔离完整分析报告 - -## 🚨 发现的问题 - -经过全面检查,发现以下模块**缺乏用户隔离**: - -### ❌ 完全未隔离的模块 - -#### 1. 卡券管理 -- **数据库表**: `cards` 表没有 `user_id` 字段 -- **API接口**: 所有卡券接口都是全局共享 -- **影响**: 所有用户共享同一套卡券库 - -#### 2. 自动发货规则 -- **数据库表**: `delivery_rules` 表没有 `user_id` 字段 -- **API接口**: 所有发货规则接口都是全局共享 -- **影响**: 所有用户共享同一套发货规则 - -#### 3. 通知渠道 -- **数据库表**: `notification_channels` 表没有 `user_id` 字段 -- **API接口**: 所有通知渠道接口都是全局共享 -- **影响**: 所有用户共享同一套通知渠道 - -#### 4. 系统设置 -- **数据库表**: `system_settings` 表没有用户区分 -- **API接口**: 系统设置接口是全局的 -- **影响**: 所有用户共享系统设置(包括主题颜色等) - -### ⚠️ 部分隔离的模块 - -#### 5. 商品管理 -- **已隔离**: 主要CRUD接口 -- **未隔离**: 批量操作接口 -- **影响**: 部分功能存在数据泄露风险 - -#### 6. 消息通知 -- **已隔离**: 主要配置接口 -- **未隔离**: 删除操作接口 -- **影响**: 删除操作可能影响其他用户 - -## 📊 详细分析 - -### 1. 卡券管理模块 - -#### 当前状态 -```sql --- 当前表结构(无用户隔离) -CREATE TABLE cards ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - type TEXT NOT NULL, - api_config TEXT, - text_content TEXT, - data_content TEXT, - description TEXT, - enabled BOOLEAN DEFAULT TRUE, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - -- 缺少 user_id 字段! -); -``` - -#### 未隔离的接口 -- `GET /cards` - 返回所有卡券 -- `POST /cards` - 创建卡券(未绑定用户) -- `GET /cards/{card_id}` - 获取卡券详情 -- `PUT /cards/{card_id}` - 更新卡券 -- `DELETE /cards/{card_id}` - 删除卡券 - -#### 安全风险 -- 用户A可以看到用户B创建的卡券 -- 用户A可以修改/删除用户B的卡券 -- 卡券数据完全暴露 - -### 2. 自动发货规则模块 - -#### 当前状态 -```sql --- 当前表结构(无用户隔离) -CREATE TABLE delivery_rules ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - keyword TEXT NOT NULL, - card_id INTEGER NOT NULL, - delivery_count INTEGER DEFAULT 1, - enabled BOOLEAN DEFAULT TRUE, - description TEXT, - delivery_times INTEGER DEFAULT 0, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (card_id) REFERENCES cards(id) - -- 缺少 user_id 字段! -); -``` - -#### 未隔离的接口 -- `GET /delivery-rules` - 返回所有发货规则 -- `POST /delivery-rules` - 创建发货规则(未绑定用户) -- `GET /delivery-rules/{rule_id}` - 获取规则详情 -- `PUT /delivery-rules/{rule_id}` - 更新规则 -- `DELETE /delivery-rules/{rule_id}` - 删除规则 - -#### 安全风险 -- 用户A可以看到用户B的发货规则 -- 用户A可以修改用户B的发货配置 -- 可能导致错误的自动发货 - -### 3. 通知渠道模块 - -#### 当前状态 -```sql --- 当前表结构(无用户隔离) -CREATE TABLE notification_channels ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - type TEXT NOT NULL, - config TEXT NOT NULL, - enabled BOOLEAN DEFAULT TRUE, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - -- 缺少 user_id 字段! -); -``` - -#### 未隔离的接口 -- `GET /notification-channels` - 返回所有通知渠道 -- `POST /notification-channels` - 创建通知渠道 -- `GET /notification-channels/{channel_id}` - 获取渠道详情 -- `PUT /notification-channels/{channel_id}` - 更新渠道 -- `DELETE /notification-channels/{channel_id}` - 删除渠道 - -#### 安全风险 -- 用户A可以看到用户B的通知配置 -- 用户A可以修改用户B的通知渠道 -- 通知可能发送到错误的接收者 - -### 4. 系统设置模块 - -#### 当前状态 -```sql --- 当前表结构(全局设置) -CREATE TABLE system_settings ( - key TEXT PRIMARY KEY, - value TEXT, - description TEXT, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - -- 没有用户区分! -); -``` - -#### 未隔离的接口 -- `GET /system-settings` - 获取系统设置 -- `PUT /system-settings/password` - 更新管理员密码 -- `PUT /system-settings/{key}` - 更新系统设置 - -#### 安全风险 -- 所有用户共享系统设置 -- 主题颜色等个人偏好无法独立设置 -- 可能存在权限提升风险 - -## 🔧 修复方案 - -### 方案A: 完全用户隔离(推荐) - -#### 1. 数据库结构修改 -```sql --- 为所有表添加 user_id 字段 -ALTER TABLE cards ADD COLUMN user_id INTEGER REFERENCES users(id); -ALTER TABLE delivery_rules ADD COLUMN user_id INTEGER REFERENCES users(id); -ALTER TABLE notification_channels ADD COLUMN user_id INTEGER REFERENCES users(id); - --- 创建用户设置表 -CREATE TABLE user_settings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL, - key TEXT NOT NULL, - value TEXT, - description TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, - UNIQUE(user_id, key) -); -``` - -#### 2. API接口修改 -- 所有接口添加用户权限验证 -- 数据查询添加用户过滤条件 -- 创建操作自动绑定当前用户 - -#### 3. 数据迁移 -- 将现有数据绑定到admin用户 -- 提供数据迁移脚本 - -### 方案B: 混合隔离策略 - -#### 1. 用户隔离模块 -- **卡券管理**: 完全用户隔离 -- **自动发货规则**: 完全用户隔离 - -#### 2. 全局共享模块 -- **通知渠道**: 保持全局共享(管理员配置) -- **系统设置**: 区分全局设置和用户设置 - -## 🚀 实施计划 - -### 阶段1: 数据库结构升级 -1. 创建数据库迁移脚本 -2. 添加用户隔离字段 -3. 创建用户设置表 -4. 数据迁移和验证 - -### 阶段2: API接口修复 -1. 修复卡券管理接口 -2. 修复自动发货规则接口 -3. 修复通知渠道接口(如选择隔离) -4. 创建用户设置接口 - -### 阶段3: 测试和验证 -1. 单元测试 -2. 集成测试 -3. 安全测试 -4. 性能测试 - -### 阶段4: 文档和部署 -1. 更新API文档 -2. 更新用户手册 -3. 部署和监控 - -## 📋 优先级建议 - -### 高优先级(安全风险) -1. **卡券管理** - 直接影响业务数据 -2. **自动发货规则** - 可能导致错误发货 - -### 中优先级(功能完整性) -3. **通知渠道** - 影响通知准确性 -4. **用户设置** - 影响用户体验 - -### 低优先级(系统管理) -5. **系统设置** - 主要影响管理功能 - -## 🎯 建议采用方案A - -**理由**: -1. **安全性最高** - 完全的数据隔离 -2. **一致性最好** - 所有模块统一的隔离策略 -3. **扩展性最强** - 便于后续功能扩展 -4. **维护性最好** - 统一的权限管理模式 - -**实施成本**: -- 数据库迁移:中等 -- 代码修改:中等 -- 测试验证:高 -- 总体可控 diff --git a/DATABASE_BACKUP_SUMMARY.md b/DATABASE_BACKUP_SUMMARY.md deleted file mode 100644 index 0de6ff7..0000000 --- a/DATABASE_BACKUP_SUMMARY.md +++ /dev/null @@ -1,301 +0,0 @@ -# 数据库备份和恢复功能总结 - -## 🎯 功能概述 - -为闲鱼自动回复系统添加了直接的数据库文件备份和恢复功能,支持一键下载完整数据库文件和直接上传替换数据库,实现最简单有效的备份方案。 - -## ✨ 主要特性 - -### 🔽 数据库备份下载 -- **一键下载**:直接下载完整的SQLite数据库文件 -- **自动命名**:备份文件自动添加时间戳 -- **完整备份**:包含所有用户数据、设置、Cookie、卡券等 -- **快速简单**:无需复杂的导出过程 - -### 🔼 数据库恢复上传 -- **直接替换**:上传数据库文件直接替换当前数据库 -- **自动验证**:验证文件格式和完整性 -- **安全备份**:替换前自动备份当前数据库 -- **自动重载**:替换后自动重新初始化数据库连接 - -### 🛡️ 安全机制 -- **权限控制**:只有admin用户可以访问 -- **文件验证**:严格验证上传文件的格式和完整性 -- **大小限制**:限制上传文件大小(100MB) -- **回滚机制**:失败时自动恢复原数据库 - -## 🔧 技术实现 - -### 后端API接口 - -#### 1. 数据库下载接口 -```python -@app.get('/admin/backup/download') -def download_database_backup(admin_user: Dict[str, Any] = Depends(require_admin)): - """下载数据库备份文件(管理员专用)""" -``` - -**功能**: -- 检查数据库文件存在性 -- 生成带时间戳的文件名 -- 返回FileResponse供下载 - -#### 2. 数据库上传接口 -```python -@app.post('/admin/backup/upload') -async def upload_database_backup(admin_user: Dict[str, Any] = Depends(require_admin), - backup_file: UploadFile = File(...)): - """上传并恢复数据库备份文件(管理员专用)""" -``` - -**功能**: -- 验证文件类型和大小 -- 验证SQLite数据库完整性 -- 备份当前数据库 -- 替换数据库文件 -- 重新初始化数据库连接 - -#### 3. 备份文件列表接口 -```python -@app.get('/admin/backup/list') -def list_backup_files(admin_user: Dict[str, Any] = Depends(require_admin)): - """列出服务器上的备份文件(管理员专用)""" -``` - -**功能**: -- 扫描服务器上的备份文件 -- 返回文件信息(大小、创建时间等) - -### 前端界面 - -#### 1. 系统设置页面集成 -位置:主页 → 系统设置 → 备份管理 - -#### 2. 数据库备份区域 -```html - -
-
- 数据库备份 -
- -
- - -
-
- 数据库恢复 -
- - -
-``` - -#### 3. JavaScript函数 - -**下载数据库备份**: -```javascript -async function downloadDatabaseBackup() { - // 调用API下载数据库文件 - // 自动触发浏览器下载 -} -``` - -**上传数据库备份**: -```javascript -async function uploadDatabaseBackup() { - // 验证文件选择和格式 - // 确认操作风险 - // 上传文件并处理结果 -} -``` - -## 🎨 用户界面 - -### 备份管理布局 -``` -┌─────────────────────────────────────────────────────────────┐ -│ 备份管理 │ -├─────────────────────────┬───────────────────────────────────┤ -│ 数据库备份 │ 数据库恢复 │ -│ │ │ -│ 直接下载完整的数据库文件 │ 上传数据库文件直接替换当前数据库 │ -│ │ │ -│ [下载数据库] │ [选择文件] [恢复数据库] │ -│ │ │ -│ 推荐方式:完整备份,恢复简单│ 警告:将覆盖所有当前数据! │ -└─────────────────────────┴───────────────────────────────────┘ - -┌─────────────────────────────────────────────────────────────┐ -│ JSON格式备份(兼容模式) │ -├─────────────────────────┬───────────────────────────────────┤ -│ 导出JSON格式备份 │ 导入JSON格式备份 │ -│ │ │ -│ [导出JSON备份] │ [选择文件] [导入JSON备份] │ -└─────────────────────────┴───────────────────────────────────┘ -``` - -## 🔄 备份流程 - -### 备份流程 -``` -用户点击"下载数据库" - ↓ -前端调用 /admin/backup/download - ↓ -后端检查权限和文件存在性 - ↓ -生成带时间戳的文件名 - ↓ -返回FileResponse - ↓ -浏览器自动下载文件 - ↓ -备份完成 -``` - -### 恢复流程 -``` -用户选择.db文件 - ↓ -用户点击"恢复数据库" - ↓ -前端验证文件格式和大小 - ↓ -用户确认操作风险 - ↓ -前端上传文件到 /admin/backup/upload - ↓ -后端验证文件完整性 - ↓ -备份当前数据库 - ↓ -关闭当前数据库连接 - ↓ -替换数据库文件 - ↓ -重新初始化数据库连接 - ↓ -验证新数据库 - ↓ -返回恢复结果 - ↓ -前端提示刷新页面 - ↓ -恢复完成 -``` - -## 🛡️ 安全特性 - -### 1. 权限验证 -- 所有备份API都需要admin权限 -- 前端页面自动检查用户身份 -- 非管理员无法访问备份功能 - -### 2. 文件验证 -- 严格验证文件扩展名(.db) -- 验证SQLite数据库格式 -- 检查必要的数据表存在性 -- 限制文件大小(100MB) - -### 3. 操作保护 -- 恢复前自动备份当前数据库 -- 失败时自动回滚到原数据库 -- 用户确认机制防止误操作 -- 详细的操作日志记录 - -### 4. 错误处理 -- 完善的异常捕获和处理 -- 清晰的错误信息提示 -- 自动清理临时文件 -- 数据库连接状态管理 - -## 💡 使用方法 - -### 备份数据库 -1. 使用admin账号登录系统 -2. 进入"系统设置"页面 -3. 在"备份管理"区域点击"下载数据库" -4. 浏览器会自动下载数据库文件 - -### 恢复数据库 -1. 在"备份管理"区域点击"选择文件" -2. 选择之前下载的.db文件 -3. 点击"恢复数据库"按钮 -4. 确认操作风险 -5. 等待恢复完成 -6. 刷新页面加载新数据 - -## 📊 优势对比 - -| 特性 | 数据库文件备份 | JSON格式备份 | -|------|---------------|-------------| -| 备份速度 | ⚡ 极快 | 🐌 较慢 | -| 文件大小 | 📦 最小 | 📦 较大 | -| 恢复速度 | ⚡ 极快 | 🐌 较慢 | -| 数据完整性 | ✅ 100% | ✅ 99% | -| 操作复杂度 | 🟢 简单 | 🟡 中等 | -| 兼容性 | 🟢 原生 | 🟡 需要处理 | -| 推荐程度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | - -## 🎯 应用场景 - -### 1. 日常备份 -- 定期下载数据库文件作为备份 -- 简单快速,无需复杂操作 -- 适合自动化脚本调用 - -### 2. 系统迁移 -- 从一个服务器迁移到另一个服务器 -- 直接复制数据库文件即可 -- 保持数据完整性 - -### 3. 版本回滚 -- 升级前备份数据库 -- 出现问题时快速回滚 -- 最小化停机时间 - -### 4. 数据同步 -- 在多个环境间同步数据 -- 开发、测试、生产环境数据一致 -- 便于问题复现和调试 - -## 🚀 部署说明 - -### 立即可用 -- 重启服务后功能立即生效 -- 无需额外配置 -- 兼容现有数据 - -### 文件权限 -确保服务器有足够的文件读写权限: -```bash -# 确保数据库文件可读写 -chmod 644 xianyu_data.db - -# 确保目录可写(用于备份文件) -chmod 755 . -``` - -### 磁盘空间 -- 备份文件会占用额外磁盘空间 -- 建议定期清理旧的备份文件 -- 监控磁盘使用情况 - -## 🎉 总结 - -数据库备份和恢复功能为闲鱼自动回复系统提供了: - -### ✅ 核心价值 -- **简单高效**:一键备份和恢复,操作简单 -- **完整可靠**:100%数据完整性保证 -- **安全稳定**:完善的验证和保护机制 -- **快速便捷**:最快的备份和恢复速度 - -### 🎯 实用性 -- **日常维护**:定期备份保障数据安全 -- **系统迁移**:轻松迁移到新服务器 -- **问题恢复**:快速回滚到正常状态 -- **开发测试**:便于环境数据同步 - -现在您的多用户闲鱼自动回复系统具备了企业级的数据备份和恢复能力!🎊 diff --git a/DOCKER_MULTIUSER_UPDATE.md b/DOCKER_MULTIUSER_UPDATE.md deleted file mode 100644 index 331887c..0000000 --- a/DOCKER_MULTIUSER_UPDATE.md +++ /dev/null @@ -1,235 +0,0 @@ -# Docker多用户系统部署更新 - -## 🎯 更新概述 - -为支持多用户系统和图形验证码功能,Docker部署配置已更新。 - -## 📦 新增依赖 - -### Python依赖 -- **Pillow>=10.0.0** - 图像处理库,用于生成图形验证码 - -### 系统依赖 -- **libjpeg-dev** - JPEG图像支持 -- **libpng-dev** - PNG图像支持 -- **libfreetype6-dev** - 字体渲染支持 -- **fonts-dejavu-core** - 默认字体包 - -## 🔧 配置文件更新 - -### 1. requirements.txt -```diff -# AI回复相关 -openai>=1.65.5 -python-dotenv>=1.0.1 - -+ # 图像处理(图形验证码) -+ Pillow>=10.0.0 -``` - -### 2. Dockerfile -```diff -# 安装系统依赖 -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - nodejs \ - npm \ - tzdata \ - curl \ -+ libjpeg-dev \ -+ libpng-dev \ -+ libfreetype6-dev \ -+ fonts-dejavu-core \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* -``` - -### 3. docker-compose.yml -```diff -environment: - - 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} -``` - -## 🚀 部署步骤 - -### 1. 更新代码 -```bash -# 拉取最新代码 -git pull origin main - -# 检查更新的文件 -git status -``` - -### 2. 重新构建镜像 -```bash -# 停止现有容器 -docker-compose down - -# 重新构建镜像(包含新依赖) -docker-compose build --no-cache - -# 启动服务 -docker-compose up -d -``` - -### 3. 验证部署 -```bash -# 检查容器状态 -docker-compose ps - -# 查看日志 -docker-compose logs -f xianyu-app - -# 健康检查 -curl http://localhost:8080/health -``` - -## 🧪 功能测试 - -### 1. 访问注册页面 -```bash -# 打开浏览器访问 -http://localhost:8080/register.html -``` - -### 2. 测试图形验证码 -- 页面应该自动显示图形验证码 -- 点击图片可以刷新验证码 -- 输入4位验证码应该能够验证 - -### 3. 测试用户注册 -- 输入用户名和邮箱 -- 验证图形验证码 -- 发送邮箱验证码 -- 完成注册流程 - -### 4. 测试数据隔离 -- 注册多个用户 -- 分别登录添加不同的Cookie -- 验证用户只能看到自己的数据 - -## 🔍 故障排除 - -### 1. 图形验证码不显示 -```bash -# 检查Pillow是否正确安装 -docker-compose exec xianyu-app python -c "from PIL import Image; print('Pillow OK')" - -# 检查字体是否可用 -docker-compose exec xianyu-app ls /usr/share/fonts/ -``` - -### 2. 容器启动失败 -```bash -# 查看详细错误日志 -docker-compose logs xianyu-app - -# 检查依赖安装 -docker-compose exec xianyu-app pip list | grep -i pillow -``` - -### 3. 权限问题 -```bash -# 检查数据目录权限 -ls -la ./data/ -ls -la ./logs/ - -# 修复权限(如需要) -sudo chown -R 1000:1000 ./data ./logs -``` - -## 📊 资源使用 - -### 更新后的资源需求 -- **内存**: 512MB → 768MB(推荐) -- **磁盘**: 1GB → 1.5GB(推荐) -- **CPU**: 0.5核 → 0.5核(无变化) - -### 调整资源限制 -```yaml -# docker-compose.yml -deploy: - resources: - limits: - memory: 768M # 增加内存限制 - cpus: '0.5' - reservations: - memory: 384M # 增加内存预留 - cpus: '0.25' -``` - -## 🔐 安全配置 - -### 1. 环境变量安全 -```bash -# 创建 .env 文件 -cat > .env << EOF -# 修改默认密码 -ADMIN_PASSWORD=your-secure-password - -# 使用强JWT密钥 -JWT_SECRET_KEY=your-very-long-and-random-secret-key - -# 配置多用户功能 -MULTIUSER_ENABLED=true -USER_REGISTRATION_ENABLED=true -EMAIL_VERIFICATION_ENABLED=true -CAPTCHA_ENABLED=true -EOF -``` - -### 2. 网络安全 -```bash -# 如果不需要外部访问注册功能,可以禁用 -USER_REGISTRATION_ENABLED=false - -# 或者使用Nginx进行访问控制 -# 参考 nginx/nginx.conf 配置 -``` - -## 📋 迁移检查清单 - -- [ ] 更新 requirements.txt -- [ ] 更新 Dockerfile -- [ ] 更新 docker-compose.yml -- [ ] 重新构建镜像 -- [ ] 测试图形验证码功能 -- [ ] 测试用户注册流程 -- [ ] 验证数据隔离 -- [ ] 检查资源使用 -- [ ] 更新监控配置 - -## 🎉 升级完成 - -升级完成后,您的系统将支持: - -1. **多用户注册和登录** -2. **图形验证码保护** -3. **邮箱验证码验证** -4. **完整的数据隔离** -5. **企业级安全保护** - -现在可以安全地支持多个用户同时使用系统,每个用户的数据完全独立! - -## 📞 技术支持 - -如果在部署过程中遇到问题: - -1. 查看容器日志:`docker-compose logs -f` -2. 检查健康状态:`docker-compose ps` -3. 验证网络连接:`curl http://localhost:8080/health` -4. 测试功能:访问 `http://localhost:8080/register.html` - ---- - -**注意**: 首次部署多用户系统后,建议运行数据迁移脚本将历史数据绑定到admin用户。 diff --git a/DOCKER_QUICK_START.md b/Docker快速启动指南.md similarity index 98% rename from DOCKER_QUICK_START.md rename to Docker快速启动指南.md index c6a8181..cc02de8 100644 --- a/DOCKER_QUICK_START.md +++ b/Docker快速启动指南.md @@ -4,7 +4,7 @@ ### 1. 克隆项目 ```bash -git clone +git clone https://github.com/zhinianboke/xianyu-auto-reply.git cd xianyu-auto-reply ``` diff --git a/Docker部署说明.md b/Docker部署说明.md deleted file mode 100644 index 29feda9..0000000 --- a/Docker部署说明.md +++ /dev/null @@ -1,375 +0,0 @@ -# 🐳 Docker 部署说明 - -## 📋 部署概述 - -本项目支持完整的Docker容器化部署,包含所有必要的依赖和配置。支持单容器部署和多容器编排部署。 - -## 🆕 多用户系统支持 - -系统现已支持多用户功能: -- **用户注册**: 支持邮箱验证码注册 -- **图形验证码**: 防止自动化注册 -- **数据隔离**: 每个用户的数据完全独立 -- **权限管理**: 严格的用户权限控制 -- **安全认证**: JWT Token + 图形验证码双重保护 - -### 新增依赖 -- **Pillow**: 用于生成图形验证码 -- **系统字体**: 支持验证码文字渲染 - -## 🚀 快速开始 - -### 方式一:使用 Docker Compose(推荐) - -1. **克隆项目** - ```bash - git clone - cd xianyuapis - ``` - -2. **配置环境变量** - ```bash - # 复制环境变量模板 - cp .env.example .env - - # 编辑配置文件(可选) - nano .env - ``` - -3. **启动服务** - ```bash - # 启动基础服务 - docker-compose up -d - - # 或者启动包含Nginx的完整服务 - docker-compose --profile with-nginx up -d - ``` - -4. **访问系统** - - 基础部署:http://localhost:8080 - - 带Nginx:http://localhost - -### 方式二:使用 Docker 命令 - -1. **构建镜像** - ```bash - docker build -t xianyu-auto-reply:latest . - ``` - -2. **运行容器** - ```bash - docker run -d \ - --name xianyu-auto-reply \ - -p 8080:8080 \ - -v $(pwd)/data:/app/data \ - -v $(pwd)/logs:/app/logs \ - -v $(pwd)/global_config.yml:/app/global_config.yml:ro \ - -e ADMIN_USERNAME=admin \ - -e ADMIN_PASSWORD=admin123 \ - xianyu-auto-reply:latest - ``` - -## 📦 依赖说明 - -### 新增依赖 -- `python-multipart>=0.0.6` - 文件上传支持(商品管理功能需要) - -### 完整依赖列表 -``` -# Web框架和API相关 -fastapi>=0.111 -uvicorn[standard]>=0.29 -pydantic>=2.7 -python-multipart>=0.0.6 - -# 日志记录 -loguru>=0.7 - -# 网络通信 -websockets>=10.0,<13.0 -aiohttp>=3.9 - -# 配置文件处理 -PyYAML>=6.0 - -# JavaScript执行引擎 -PyExecJS>=1.5.1 - -# 协议缓冲区解析 -blackboxprotobuf>=1.0.1 - -# 系统监控 -psutil>=5.9.0 - -# HTTP客户端(用于测试) -requests>=2.31.0 -``` - -## 🔧 配置说明 - -### 环境变量配置 - -#### 基础配置 -```bash -# 时区设置 -TZ=Asia/Shanghai - -# 服务端口 -WEB_PORT=8080 - -# 管理员账号(建议修改) -ADMIN_USERNAME=admin -ADMIN_PASSWORD=admin123 - -# JWT密钥(建议修改) -JWT_SECRET_KEY=your-secret-key-here -``` - -#### 多用户系统配置 -```bash -# 多用户功能开关 -MULTIUSER_ENABLED=true - -# 用户注册开关 -USER_REGISTRATION_ENABLED=true - -# 邮箱验证开关 -EMAIL_VERIFICATION_ENABLED=true - -# 图形验证码开关 -CAPTCHA_ENABLED=true - -# Token过期时间(秒,默认24小时) -TOKEN_EXPIRE_TIME=86400 -``` - -#### 功能配置 -```bash -# 自动回复 -AUTO_REPLY_ENABLED=true - -# 自动发货 -AUTO_DELIVERY_ENABLED=true -AUTO_DELIVERY_TIMEOUT=30 - -# 商品管理(新功能) -ENABLE_ITEM_MANAGEMENT=true -``` - -### 数据持久化 - -#### 重要目录 -- `/app/data` - 数据库文件 -- `/app/logs` - 日志文件 -- `/app/backups` - 备份文件 - -#### 挂载配置 -```yaml -volumes: - - ./data:/app/data:rw # 数据库持久化 - - ./logs:/app/logs:rw # 日志持久化 - - ./backups:/app/backups:rw # 备份持久化 - - ./global_config.yml:/app/global_config.yml:ro # 配置文件 -``` - -## 🏗️ 架构说明 - -### 容器架构 -``` -┌─────────────────────────────────────┐ -│ Nginx (可选) │ -│ 反向代理 + SSL │ -└─────────────┬───────────────────────┘ - │ -┌─────────────▼───────────────────────┐ -│ Xianyu App Container │ -│ ┌─────────────────────────────────┐ │ -│ │ FastAPI Server │ │ -│ │ (Port 8080) │ │ -│ └─────────────────────────────────┘ │ -│ ┌─────────────────────────────────┐ │ -│ │ XianyuAutoAsync │ │ -│ │ (WebSocket Client) │ │ -│ └─────────────────────────────────┘ │ -│ ┌─────────────────────────────────┐ │ -│ │ SQLite Database │ │ -│ │ (商品信息 + 配置) │ │ -│ └─────────────────────────────────┘ │ -└─────────────────────────────────────┘ -``` - -### 新功能支持 -- ✅ 商品信息管理 -- ✅ 商品详情编辑 -- ✅ 文件上传功能 -- ✅ 消息通知格式化 - -## 🔍 健康检查 - -### 内置健康检查 -```bash -# 检查容器状态 -docker ps - -# 查看健康状态 -docker inspect xianyu-auto-reply | grep Health -A 10 - -# 手动健康检查 -curl -f http://localhost:8080/health -``` - -### 健康检查端点 -- `GET /health` - 基础健康检查 -- `GET /api/status` - 详细状态信息 - -## 📊 监控和日志 - -### 日志查看 -```bash -# 查看容器日志 -docker logs xianyu-auto-reply - -# 实时查看日志 -docker logs -f xianyu-auto-reply - -# 查看应用日志文件 -docker exec xianyu-auto-reply tail -f /app/logs/xianyu_$(date +%Y%m%d).log -``` - -### 性能监控 -```bash -# 查看资源使用 -docker stats xianyu-auto-reply - -# 进入容器 -docker exec -it xianyu-auto-reply bash - -# 查看进程状态 -docker exec xianyu-auto-reply ps aux -``` - -## 🔒 安全配置 - -### 生产环境建议 -1. **修改默认密码** - ```bash - ADMIN_USERNAME=your-admin - ADMIN_PASSWORD=your-strong-password - ``` - -2. **使用强JWT密钥** - ```bash - JWT_SECRET_KEY=$(openssl rand -base64 32) - ``` - -3. **启用HTTPS** - ```yaml - # 使用Nginx配置SSL - docker-compose --profile with-nginx up -d - ``` - -4. **限制网络访问** - ```yaml - # 仅允许本地访问 - ports: - - "127.0.0.1:8080:8080" - ``` - -## 🚨 故障排除 - -### 常见问题 - -1. **容器启动失败** - ```bash - # 查看详细错误 - docker logs xianyu-auto-reply - - # 检查端口占用 - netstat -tlnp | grep 8080 - ``` - -2. **数据库初始化失败** - ```bash - # 数据库会在应用启动时自动初始化 - # 如果需要重新初始化,可以删除数据库文件后重启容器 - docker exec xianyu-auto-reply rm -f /app/data/xianyu_data.db - docker restart xianyu-auto-reply - ``` - -3. **权限问题** - ```bash - # 修复目录权限 - sudo chown -R 1000:1000 ./data ./logs ./backups - ``` - -4. **依赖安装失败** - ```bash - # 重新构建镜像 - docker-compose build --no-cache - ``` - -### 调试模式 -```bash -# 启用调试模式 -docker-compose -f docker-compose.yml -f docker-compose.debug.yml up -d - -# 或设置环境变量 -docker run -e DEBUG=true -e LOG_LEVEL=DEBUG ... -``` - -## 🔄 更新部署 - -### 更新步骤 -1. **停止服务** - ```bash - docker-compose down - ``` - -2. **拉取最新代码** - ```bash - git pull origin main - ``` - -3. **重新构建** - ```bash - docker-compose build --no-cache - ``` - -4. **启动服务** - ```bash - docker-compose up -d - ``` - -### 数据备份 -```bash -# 备份数据库 -docker exec xianyu-auto-reply cp /app/data/xianyu_data.db /app/backups/ - -# 备份配置 -cp .env .env.backup -cp global_config.yml global_config.yml.backup -``` - -## 📈 性能优化 - -### 资源限制 -```yaml -deploy: - resources: - limits: - memory: 512M # 内存限制 - cpus: '0.5' # CPU限制 - reservations: - memory: 256M # 内存预留 - cpus: '0.25' # CPU预留 -``` - -### 优化建议 -1. **调整内存限制**:根据实际使用情况调整 -2. **使用SSD存储**:提高数据库性能 -3. **配置日志轮转**:避免日志文件过大 -4. **定期清理**:清理旧的备份文件 - ---- - -🎉 **Docker部署配置完善,支持所有新功能!** diff --git a/FINAL_ISOLATION_STATUS.md b/FINAL_ISOLATION_STATUS.md deleted file mode 100644 index b8b8fb0..0000000 --- a/FINAL_ISOLATION_STATUS.md +++ /dev/null @@ -1,217 +0,0 @@ -# 多用户数据隔离最终状态报告 - -## 🎯 总体状态 - -**当前进度**: 核心功能已完成用户隔离,部分功能需要策略确认 - -**数据库状态**: ✅ 已完成数据库结构升级和数据迁移 - -**API状态**: ✅ 核心接口已修复,部分接口待完善 - -## 📊 详细隔离状态 - -### ✅ 已完全隔离的模块 - -#### 1. 账号管理 (Cookie管理) -- ✅ **数据库**: cookies表已添加user_id字段 -- ✅ **API接口**: 所有Cookie相关接口已实现用户隔离 -- ✅ **权限验证**: 跨用户访问被严格禁止 -- ✅ **数据迁移**: 历史数据已绑定到admin用户 - -#### 2. 自动回复管理 -- ✅ **关键字管理**: 完全隔离 -- ✅ **默认回复设置**: 完全隔离 -- ✅ **权限验证**: 只能操作自己的回复规则 - -#### 3. 商品管理 -- ✅ **主要CRUD接口**: 已实现用户隔离 -- ✅ **权限验证**: Cookie所有权验证 -- ⚠️ **批量操作**: 部分接口需要进一步修复 - -#### 4. AI回复设置 -- ✅ **配置管理**: 完全隔离 -- ✅ **权限验证**: 只能配置自己的AI回复 - -#### 5. 消息通知 -- ✅ **配置管理**: 主要接口已隔离 -- ⚠️ **删除操作**: 部分接口需要修复 - -#### 6. 卡券管理 (新增隔离) -- ✅ **数据库**: cards表已添加user_id字段 -- ✅ **API接口**: 主要接口已实现用户隔离 -- ✅ **权限验证**: 跨用户访问被禁止 -- ✅ **数据迁移**: 历史数据已绑定到admin用户 - -#### 7. 用户设置 (新增功能) -- ✅ **数据库**: 新建user_settings表 -- ✅ **API接口**: 完整的用户设置管理 -- ✅ **主题颜色**: 每个用户独立的主题设置 -- ✅ **个人偏好**: 支持各种用户个性化设置 - -### ❓ 需要策略确认的模块 - -#### 1. 自动发货规则 -- **数据库**: ✅ delivery_rules表已添加user_id字段 -- **API接口**: ❌ 仍使用旧认证方式 -- **建议**: 实现用户隔离(每个用户独立的发货规则) - -#### 2. 通知渠道 -- **数据库**: ✅ notification_channels表已添加user_id字段 -- **API接口**: ❌ 仍使用旧认证方式 -- **策略选择**: - - 选项A: 实现用户隔离(每个用户独立配置) - - 选项B: 保持全局共享(管理员统一配置) - -#### 3. 系统设置 -- **当前状态**: 全局共享 -- **策略选择**: - - 全局设置: 保持共享(如系统配置) - - 用户设置: 已实现隔离(如主题颜色) - -## 🔧 已完成的修复 - -### 数据库结构升级 -```sql --- 为相关表添加用户隔离字段 -ALTER TABLE cards ADD COLUMN user_id INTEGER REFERENCES users(id); -ALTER TABLE delivery_rules ADD COLUMN user_id INTEGER REFERENCES users(id); -ALTER TABLE notification_channels ADD COLUMN user_id INTEGER REFERENCES users(id); - --- 创建用户设置表 -CREATE TABLE user_settings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL, - key TEXT NOT NULL, - value TEXT, - description TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, - UNIQUE(user_id, key) -); -``` - -### API接口修复 -- ✅ 卡券管理接口: 从`require_auth`升级到`get_current_user` -- ✅ 用户设置接口: 新增完整的用户设置管理 -- ✅ 数据库方法: 支持用户隔离的查询和操作 - -### 数据迁移 -- ✅ 历史卡券数据绑定到admin用户 -- ✅ 历史发货规则数据绑定到admin用户 -- ✅ 历史通知渠道数据绑定到admin用户 -- ✅ 为现有用户创建默认设置 - -## 📋 待修复的接口 - -### 高优先级(安全风险) -1. **自动发货规则接口** (5个接口) - - `GET /delivery-rules` - - `POST /delivery-rules` - - `GET /delivery-rules/{rule_id}` - - `PUT /delivery-rules/{rule_id}` - - `DELETE /delivery-rules/{rule_id}` - -2. **卡券管理剩余接口** (2个接口) - - `PUT /cards/{card_id}` - - `DELETE /cards/{card_id}` - -### 中优先级(功能完整性) -3. **通知渠道接口** (6个接口) - 需要策略确认 - - `GET /notification-channels` - - `POST /notification-channels` - - `GET /notification-channels/{channel_id}` - - `PUT /notification-channels/{channel_id}` - - `DELETE /notification-channels/{channel_id}` - -4. **消息通知删除接口** (2个接口) - - `DELETE /message-notifications/account/{cid}` - - `DELETE /message-notifications/{notification_id}` - -5. **商品管理批量接口** (3个接口) - - `DELETE /items/batch` - - `POST /items/get-all-from-account` - - `POST /items/get-by-page` - -## 🧪 测试验证 - -### 已通过的测试 -- ✅ 用户注册和登录 -- ✅ Cookie数据隔离 -- ✅ 卡券管理隔离 -- ✅ 用户设置隔离 -- ✅ 跨用户访问拒绝 - -### 测试脚本 -- `test_complete_isolation.py` - 完整的隔离测试 -- `fix_complete_isolation.py` - 数据库修复脚本 - -## 🎯 建议的隔离策略 - -### 完全用户隔离(推荐) -- **自动发货规则**: 每个用户独立的发货规则 -- **卡券管理**: 每个用户独立的卡券库 -- **用户设置**: 每个用户独立的个性化设置 - -### 混合策略(可选) -- **通知渠道**: 管理员统一配置,用户选择使用 -- **系统设置**: 区分全局设置和用户设置 - -## 🚀 下一步行动 - -### 立即执行(高优先级) -1. **修复自动发货规则接口** - ```bash - # 需要修复的接口模式 - @app.get("/delivery-rules") - def get_delivery_rules(current_user: Dict[str, Any] = Depends(get_current_user)): - # 添加用户权限验证 - ``` - -2. **修复卡券管理剩余接口** - ```bash - # 需要添加用户权限验证 - if card.user_id != current_user['user_id']: - raise HTTPException(status_code=403, detail="无权限操作") - ``` - -### 策略确认(中优先级) -3. **确认通知渠道策略** - - 与产品团队确认是否需要用户隔离 - - 如需隔离,按照卡券管理模式修复 - -4. **完善商品管理** - - 修复批量操作接口的用户权限验证 - -### 测试和部署(低优先级) -5. **完整测试** - - 运行所有隔离测试 - - 验证数据完整性 - -6. **文档更新** - - 更新API文档 - - 更新用户手册 - -## 📊 当前隔离覆盖率 - -- **已隔离模块**: 6/8 (75%) -- **已修复接口**: 约70% -- **数据库隔离**: 100% -- **核心功能隔离**: 100% - -## 🎉 总结 - -多用户数据隔离项目已基本完成,核心功能已实现完全隔离: - -### 主要成就 -- ✅ **数据库层面**: 完整的用户隔离支持 -- ✅ **核心业务**: Cookie、回复、商品、AI设置完全隔离 -- ✅ **新增功能**: 卡券管理和用户设置支持 -- ✅ **安全保障**: 跨用户访问被严格禁止 - -### 待完善项目 -- ⚠️ **自动发货规则**: 需要修复API接口 -- ❓ **通知渠道**: 需要确认隔离策略 -- 🔧 **批量操作**: 需要完善权限验证 - -**总体评估**: 系统已具备企业级的多用户数据隔离能力,可以安全地支持多个用户同时使用,剩余工作主要是完善和策略确认。 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 4501f64..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 肥极喵 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/LOG_IMPROVEMENT_SUMMARY.md b/LOG_IMPROVEMENT_SUMMARY.md deleted file mode 100644 index 612ec8b..0000000 --- a/LOG_IMPROVEMENT_SUMMARY.md +++ /dev/null @@ -1,196 +0,0 @@ -# 日志显示改进总结 - -## 🎯 改进目标 - -在多用户系统中,原有的日志无法区分不同用户的操作,导致调试和监控困难。本次改进为所有重要日志添加了Cookie ID标识。 - -## 📊 改进对比 - -### 改进前的日志格式 -``` -2025-07-25 14:23:47.770 | INFO | XianyuAutoAsync:init:1360 - 获取初始token... -2025-07-25 14:23:47.771 | INFO | XianyuAutoAsync:refresh_token:134 - 开始刷新token... -2025-07-25 14:23:48.269 | INFO | XianyuAutoAsync:refresh_token:200 - Token刷新成功 -2025-07-25 14:23:49.286 | INFO | XianyuAutoAsync:init:1407 - 连接注册完成 -2025-07-25 14:23:49.288 | INFO | XianyuAutoAsync:handle_message:1663 - [2025-07-25 14:23:49] 【系统】小闲鱼智能提示: -``` - -### 改进后的日志格式 -``` -2025-07-25 14:23:47.770 | INFO | XianyuAutoAsync:init:1360 - 【user1_cookie】获取初始token... -2025-07-25 14:23:47.771 | INFO | XianyuAutoAsync:refresh_token:134 - 【user1_cookie】开始刷新token... -2025-07-25 14:23:48.269 | INFO | XianyuAutoAsync:refresh_token:200 - 【user1_cookie】Token刷新成功 -2025-07-25 14:23:49.286 | INFO | XianyuAutoAsync:init:1407 - 【user1_cookie】连接注册完成 -2025-07-25 14:23:49.288 | INFO | XianyuAutoAsync:handle_message:1663 - [2025-07-25 14:23:49] 【user1_cookie】【系统】小闲鱼智能提示: -``` - -## 🔧 修改的日志类型 - -### 1. Token管理相关 -- ✅ `【{cookie_id}】开始刷新token...` -- ✅ `【{cookie_id}】Token刷新成功` -- ✅ `【{cookie_id}】Token刷新失败: {error}` -- ✅ `【{cookie_id}】获取初始token...` -- ✅ `【{cookie_id}】Token刷新成功,准备重新建立连接...` - -### 2. 连接管理相关 -- ✅ `【{cookie_id}】连接注册完成` -- ✅ `【{cookie_id}】message: {message}` -- ✅ `【{cookie_id}】send message` - -### 3. 系统消息相关 -- ✅ `[{time}] 【{cookie_id}】【系统】小闲鱼智能提示:` -- ✅ `[{time}] 【{cookie_id}】【系统】其他类型消息: {content}` -- ✅ `[{time}] 【{cookie_id}】系统消息不处理` -- ✅ `[{time}] 【{cookie_id}】【系统】买家已付款,准备自动发货` -- ✅ `[{time}] 【{cookie_id}】【系统】自动回复已禁用` -- ✅ `[{time}] 【{cookie_id}】【系统】未找到匹配的回复规则,不回复` - -### 4. 商品和发货相关 -- ✅ `【{cookie_id}】从消息内容中提取商品ID: {item_id}` -- ✅ `【{cookie_id}】准备自动发货: item_id={item_id}, item_title={title}` - -### 5. 回复生成相关 -- ✅ `【{cookie_id}】使用默认回复: {reply}` -- ✅ `【{cookie_id}】AI回复生成成功: {reply}` - -## 📁 修改的文件 - -### XianyuAutoAsync.py -- **修改行数**: 约20处日志输出 -- **影响范围**: 所有核心功能的日志 -- **修改方式**: 在日志消息前添加 `【{self.cookie_id}】` 标识 - -## 🎯 改进效果 - -### 1. 问题定位能力 -- **改进前**: 无法区分不同用户的操作,调试困难 -- **改进后**: 一眼就能看出是哪个用户的操作 - -### 2. 监控分析能力 -- **改进前**: 无法按用户统计操作情况 -- **改进后**: 可以轻松按用户过滤和统计 - -### 3. 运维管理能力 -- **改进前**: 多用户问题排查复杂 -- **改进后**: 快速定位特定用户的问题 - -## 💡 日志分析技巧 - -### 1. 按用户过滤日志 -```bash -# 查看特定用户的所有操作 -grep '【user1_cookie】' logs/xianyu_2025-07-25.log - -# 查看特定用户的错误日志 -grep 'ERROR.*【user1_cookie】' logs/xianyu_2025-07-25.log -``` - -### 2. 监控Token状态 -```bash -# 查看所有用户的Token刷新情况 -grep '【.*】.*Token' logs/xianyu_2025-07-25.log - -# 查看Token刷新失败的情况 -grep '【.*】.*Token刷新失败' logs/xianyu_2025-07-25.log -``` - -### 3. 统计用户活跃度 -```bash -# 统计各用户的操作次数 -grep -o '【[^】]*】' logs/xianyu_2025-07-25.log | sort | uniq -c - -# 查看最活跃的用户 -grep -o '【[^】]*】' logs/xianyu_2025-07-25.log | sort | uniq -c | sort -nr -``` - -### 4. 监控系统消息 -```bash -# 查看所有系统级别的消息 -grep '【系统】' logs/xianyu_2025-07-25.log - -# 查看自动发货相关的消息 -grep '准备自动发货' logs/xianyu_2025-07-25.log -``` - -### 5. 分析回复情况 -```bash -# 查看AI回复的使用情况 -grep 'AI回复生成成功' logs/xianyu_2025-07-25.log - -# 查看默认回复的使用情况 -grep '使用默认回复' logs/xianyu_2025-07-25.log -``` - -## 🔍 实时监控命令 - -### 1. 实时查看特定用户的日志 -```bash -tail -f logs/xianyu_2025-07-25.log | grep '【user1_cookie】' -``` - -### 2. 实时监控所有错误 -```bash -tail -f logs/xianyu_2025-07-25.log | grep 'ERROR.*【.*】' -``` - -### 3. 实时监控Token刷新 -```bash -tail -f logs/xianyu_2025-07-25.log | grep '【.*】.*Token' -``` - -## 📈 监控仪表板建议 - -基于新的日志格式,可以构建以下监控指标: - -### 1. 用户活跃度指标 -- 每个用户的操作频率 -- 用户在线时长统计 -- 用户操作成功率 - -### 2. 系统健康指标 -- Token刷新成功率(按用户) -- 连接稳定性(按用户) -- 错误发生频率(按用户) - -### 3. 业务指标 -- 自动回复使用率(按用户) -- AI回复成功率(按用户) -- 自动发货成功率(按用户) - -## 🚀 部署建议 - -### 1. 重启服务 -```bash -# 停止当前服务 -docker-compose down - -# 重新启动服务 -docker-compose up -d - -# 查看新的日志格式 -docker-compose logs -f -``` - -### 2. 日志轮转配置 -确保日志轮转配置能够处理增加的日志内容: -```yaml -# loguru配置示例 -rotation: "100 MB" -retention: "7 days" -compression: "zip" -``` - -### 3. 监控工具配置 -如果使用ELK、Grafana等监控工具,需要更新日志解析规则以识别新的Cookie ID字段。 - -## 🎉 总结 - -通过本次改进,多用户系统的日志现在具备了: - -- ✅ **清晰的用户标识**: 每条日志都能明确标识操作用户 -- ✅ **高效的问题定位**: 快速定位特定用户的问题 -- ✅ **精准的监控分析**: 支持按用户维度的监控和分析 -- ✅ **便捷的运维管理**: 简化多用户环境的运维工作 - -这为多用户系统的稳定运行和高效管理奠定了坚实的基础! diff --git a/MULTIUSER_ISOLATION_STATUS.md b/MULTIUSER_ISOLATION_STATUS.md deleted file mode 100644 index d5eaeb9..0000000 --- a/MULTIUSER_ISOLATION_STATUS.md +++ /dev/null @@ -1,216 +0,0 @@ -# 多用户数据隔离状态报告 - -## 🎯 总体状态 - -**当前进度**: 核心功能已实现用户隔离,部分管理功能待完善 - -**测试结果**: ✅ 核心数据隔离测试全部通过 - -## 📊 功能模块隔离状态 - -### ✅ 已完成隔离的模块 - -#### 1. 账号管理 (Cookie管理) -- ✅ 获取Cookie列表 - 只显示当前用户的Cookie -- ✅ 添加Cookie - 自动绑定到当前用户 -- ✅ 更新Cookie - 权限验证 -- ✅ 删除Cookie - 权限验证 -- ✅ Cookie状态管理 - 权限验证 - -#### 2. 自动回复管理 -- ✅ 关键字管理 - 完全隔离 -- ✅ 默认回复设置 - 完全隔离 -- ✅ 获取所有默认回复 - 只返回当前用户数据 - -#### 3. 商品管理 (部分完成) -- ✅ 获取所有商品 - 只返回当前用户商品 -- ✅ 按Cookie获取商品 - 权限验证 -- ✅ 获取商品详情 - 权限验证 -- ✅ 更新商品详情 - 权限验证 -- ✅ 删除商品信息 - 权限验证 - -#### 4. AI回复设置 -- ✅ 获取AI回复设置 - 权限验证 -- ✅ 更新AI回复设置 - 权限验证 -- ✅ 获取所有AI回复设置 - 只返回当前用户数据 - -#### 5. 消息通知 (部分完成) -- ✅ 获取所有消息通知 - 只返回当前用户数据 -- ✅ 获取账号消息通知 - 权限验证 -- ✅ 设置消息通知 - 权限验证 - -#### 6. 数据备份 -- ✅ 导出备份 - 只导出当前用户数据 -- ✅ 导入备份 - 只导入到当前用户 - -### ❓ 需要确认隔离策略的模块 - -#### 1. 卡券管理 -**当前状态**: 未隔离(全局共享) -**建议**: -- 选项A: 保持全局共享(所有用户共用卡券库) -- 选项B: 实现用户隔离(每个用户独立的卡券) - -#### 2. 通知渠道 -**当前状态**: 未隔离(全局共享) -**建议**: -- 选项A: 保持全局共享(管理员统一配置) -- 选项B: 实现用户隔离(每个用户独立配置) - -#### 3. 系统设置 -**当前状态**: 部分隔离 -**建议**: -- 全局设置: 保持共享(如系统配置) -- 用户设置: 实现隔离(如个人偏好) - -### ❌ 待修复的接口 - -#### 商品管理剩余接口 -- `batch_delete_items` - 批量删除商品 -- `get_all_items_from_account` - 从账号获取所有商品 -- `get_items_by_page` - 分页获取商品 - -#### 消息通知剩余接口 -- `delete_account_notifications` - 删除账号通知 -- `delete_message_notification` - 删除消息通知 - -#### 卡券管理接口 (如需隔离) -- `get_cards` - 获取卡券列表 -- `create_card` - 创建卡券 -- `get_card` - 获取卡券详情 -- `update_card` - 更新卡券 -- `delete_card` - 删除卡券 - -#### 自动发货接口 (如需隔离) -- `get_delivery_rules` - 获取发货规则 -- `create_delivery_rule` - 创建发货规则 -- `get_delivery_rule` - 获取发货规则详情 -- `update_delivery_rule` - 更新发货规则 -- `delete_delivery_rule` - 删除发货规则 - -#### 通知渠道接口 (如需隔离) -- `get_notification_channels` - 获取通知渠道 -- `create_notification_channel` - 创建通知渠道 -- `get_notification_channel` - 获取通知渠道详情 -- `update_notification_channel` - 更新通知渠道 -- `delete_notification_channel` - 删除通知渠道 - -## 🧪 测试结果 - -### ✅ 通过的测试 - -1. **用户注册和登录** - - 图形验证码生成和验证 - - 邮箱验证码发送和验证 - - 用户注册流程 - - 用户登录认证 - -2. **数据隔离** - - Cookie数据完全隔离 - - 用户只能看到自己的数据 - - 跨用户访问被正确拒绝 - -3. **权限验证** - - API层面权限检查 - - 403错误正确返回 - - 用户身份验证 - -### 📊 测试统计 - -- **已修复接口**: 25个 (使用新认证方式) -- **待修复接口**: 28个 (仍使用旧认证方式) -- **权限检查接口**: 23个 (包含用户权限验证) - -## 🔒 安全特性 - -### ✅ 已实现的安全特性 - -1. **用户认证** - - JWT Token认证 - - 图形验证码防护 - - 邮箱验证码验证 - -2. **数据隔离** - - 数据库层面用户绑定 - - API层面权限验证 - - 跨用户访问拒绝 - -3. **权限控制** - - 基于用户ID的数据过滤 - - Cookie所有权验证 - - 操作权限检查 - -### 🛡️ 安全机制 - -```python -# 标准的用户权限检查模式 -def api_function(cid: str, current_user: Dict[str, Any] = Depends(get_current_user)): - # 1. 获取当前用户ID - user_id = current_user['user_id'] - - # 2. 获取用户的Cookie列表 - user_cookies = db_manager.get_all_cookies(user_id) - - # 3. 验证Cookie所有权 - if cid not in user_cookies: - raise HTTPException(status_code=403, detail="无权限访问该Cookie") - - # 4. 执行业务逻辑 - # ... -``` - -## 📋 建议的隔离策略 - -### 核心业务数据 (必须隔离) -- ✅ Cookie/账号数据 -- ✅ 商品信息 -- ✅ 关键字和回复 -- ✅ AI回复设置 -- ✅ 消息通知配置 - -### 配置数据 (建议策略) -- **卡券管理**: 建议保持全局共享 -- **通知渠道**: 建议保持全局共享(管理员配置) -- **发货规则**: 建议实现用户隔离 -- **系统设置**: 区分全局设置和用户设置 - -### 管理功能 (特殊处理) -- **系统监控**: 管理员专用 -- **用户管理**: 管理员专用 -- **系统配置**: 管理员专用 - -## 🚀 下一步行动计划 - -### 优先级1: 完成核心功能隔离 -1. 修复剩余的商品管理接口 -2. 修复剩余的消息通知接口 -3. 完善AI回复相关接口 - -### 优先级2: 确认隔离策略 -1. 与产品团队确认卡券管理策略 -2. 确认通知渠道管理策略 -3. 确认自动发货规则策略 - -### 优先级3: 完善管理功能 -1. 实现管理员用户管理界面 -2. 添加用户数据统计功能 -3. 完善系统监控功能 - -### 优先级4: 测试和文档 -1. 编写完整的API测试用例 -2. 更新API文档 -3. 编写用户使用指南 - -## 🎉 总结 - -**当前状态**: 多用户系统的核心功能已经实现,数据隔离测试全部通过。 - -**主要成就**: -- ✅ 用户注册和认证系统完整 -- ✅ 核心业务数据完全隔离 -- ✅ 安全权限验证机制完善 -- ✅ 数据库层面支持多用户 - -**待完善项目**: 主要是一些管理功能和配置功能的隔离策略确认。 - -**安全性**: 系统已具备企业级的多用户数据隔离能力,可以安全地支持多个用户同时使用。 diff --git a/MULTIUSER_SYSTEM_README.md b/MULTIUSER_SYSTEM_README.md deleted file mode 100644 index f7bbdbb..0000000 --- a/MULTIUSER_SYSTEM_README.md +++ /dev/null @@ -1,277 +0,0 @@ -# 多用户系统升级指南 - -## 🎯 功能概述 - -本次升级将闲鱼自动回复系统从单用户模式升级为多用户模式,实现以下功能: - -### ✨ 新增功能 - -1. **用户注册系统** - - 邮箱注册,支持验证码验证 - - 用户名唯一性检查 - - 密码安全存储(SHA256哈希) - -2. **数据隔离** - - 每个用户只能看到自己的数据 - - Cookie、关键字、备份等完全隔离 - - 历史数据自动绑定到admin用户 - -3. **邮箱验证** - - 集成邮件发送API - - 6位数字验证码 - - 10分钟有效期 - - 防重复使用 - -## 🚀 升级步骤 - -### 1. 备份数据 -```bash -# 备份数据库文件 -cp xianyu_data.db xianyu_data.db.backup -``` - -### 2. 运行迁移脚本 -```bash -# 迁移历史数据到admin用户 -python migrate_to_multiuser.py - -# 检查迁移状态 -python migrate_to_multiuser.py check -``` - -### 3. 重启应用 -```bash -# 重启应用程序 -python Start.py -``` - -### 4. 验证功能 -```bash -# 运行功能测试 -python test_multiuser_system.py -``` - -## 📋 API变更 - -### 新增接口 - -| 接口 | 方法 | 说明 | -|------|------|------| -| `/register` | POST | 用户注册 | -| `/send-verification-code` | POST | 发送验证码 | -| `/verify` | GET | 验证token(返回用户信息) | - -### 修改的接口 - -所有需要认证的接口现在都支持用户隔离: - -- `/cookies` - 只返回当前用户的cookies -- `/cookies/details` - 只返回当前用户的cookie详情 -- `/backup/export` - 只导出当前用户的数据 -- `/backup/import` - 只导入到当前用户 - -## 🔐 认证系统 - -### Token格式变更 -```javascript -// 旧格式 -SESSION_TOKENS[token] = timestamp - -// 新格式 -SESSION_TOKENS[token] = { - user_id: 1, - username: 'admin', - timestamp: 1234567890 -} -``` - -### 登录响应变更 -```json -{ - "success": true, - "token": "abc123...", - "message": "登录成功", - "user_id": 1 -} -``` - -## 🗄️ 数据库变更 - -### 新增表 - -1. **users** - 用户表 - ```sql - CREATE TABLE users ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT UNIQUE NOT NULL, - email TEXT UNIQUE NOT NULL, - password_hash TEXT NOT NULL, - is_active BOOLEAN DEFAULT TRUE, - created_at REAL NOT NULL, - updated_at REAL NOT NULL - ); - ``` - -2. **email_verifications** - 邮箱验证码表 - ```sql - CREATE TABLE email_verifications ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - email TEXT NOT NULL, - code TEXT NOT NULL, - expires_at REAL NOT NULL, - used BOOLEAN DEFAULT FALSE, - created_at REAL DEFAULT (strftime('%s', 'now')) - ); - ``` - -### 修改的表 - -1. **cookies** - 添加user_id字段 - ```sql - ALTER TABLE cookies ADD COLUMN user_id INTEGER; - ``` - -## 🎨 前端变更 - -### 新增页面 - -1. **注册页面** (`/register.html`) - - 用户名、邮箱、密码输入 - - 邮箱验证码发送和验证 - - 表单验证和错误提示 - - 响应式设计 - -### 修改的页面 - -1. **登录页面** (`/login.html`) - - 添加注册链接 - - 保持向后兼容 - -## 📧 邮件系统 - -### 邮件API配置 -``` -API地址: https://dy.zhinianboke.com/api/emailSend -参数: -- subject: 邮件主题 -- receiveUser: 收件人邮箱 -- sendHtml: 邮件内容(HTML格式) -``` - -### 邮件模板 -- 响应式HTML设计 -- 品牌化样式 -- 验证码突出显示 -- 安全提醒信息 - -## 🔒 安全特性 - -1. **密码安全** - - SHA256哈希存储 - - 不可逆加密 - -2. **验证码安全** - - 6位随机数字 - - 10分钟有效期 - - 一次性使用 - - 防暴力破解 - -3. **数据隔离** - - 用户级别完全隔离 - - API层面权限检查 - - 数据库层面用户绑定 - -## 🧪 测试指南 - -### 功能测试 -```bash -# 运行完整测试套件 -python test_multiuser_system.py -``` - -### 手动测试步骤 - -1. **注册测试** - - 访问 `/register.html` - - 输入用户信息 - - 验证邮箱验证码 - - 完成注册 - -2. **登录测试** - - 使用新注册的账号登录 - - 验证只能看到自己的数据 - -3. **数据隔离测试** - - 创建多个用户账号 - - 分别添加不同的cookies - - 验证数据完全隔离 - -## 🐛 故障排除 - -### 常见问题 - -1. **迁移失败** - ```bash - # 检查数据库文件权限 - ls -la xianyu_data.db - - # 检查迁移状态 - python migrate_to_multiuser.py check - ``` - -2. **邮件发送失败** - - 检查网络连接 - - 验证邮箱地址格式 - - 查看应用日志 - -3. **用户无法登录** - - 检查用户名和密码 - - 确认用户状态为激活 - - 查看认证日志 - -### 回滚方案 - -如果升级出现问题,可以回滚到单用户模式: - -1. 恢复数据库备份 - ```bash - cp xianyu_data.db.backup xianyu_data.db - ``` - -2. 使用旧版本代码 -3. 重启应用 - -## 📈 性能影响 - -- **数据库查询**: 增加了user_id过滤条件,对性能影响微小 -- **内存使用**: CookieManager仍加载所有数据,API层面进行过滤 -- **响应时间**: 增加了用户验证步骤,延迟增加<10ms - -## 🔮 未来规划 - -1. **用户管理** - - 管理员用户管理界面 - - 用户权限控制 - - 用户状态管理 - -2. **高级功能** - - 用户组和权限 - - 数据共享机制 - - 审计日志 - -3. **性能优化** - - 用户级别的CookieManager - - 数据库索引优化 - - 缓存策略 - -## 📞 技术支持 - -如有问题,请: -1. 查看应用日志 -2. 运行测试脚本诊断 -3. 检查数据库状态 -4. 联系技术支持 - ---- - -**升级完成后,您的闲鱼自动回复系统将支持多用户使用,每个用户的数据完全隔离,提供更好的安全性和可扩展性!** 🎉 diff --git a/README.md b/README.md index ce4260f..f16ea20 100644 --- a/README.md +++ b/README.md @@ -1,173 +1,332 @@ -# 🐟 XianYuAutoDeliveryX - 闲鱼虚拟商品商自动发货&聊天对接大模型 +# 🐟 闲鱼自动回复系统 -[![Python Version](https://img.shields.io/badge/python-3.7%2B-blue)](https://www.python.org/) -[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE) +[![GitHub](https://img.shields.io/badge/GitHub-zhinianboke%2Fxianyu--auto--reply-blue?logo=github)](https://github.com/zhinianboke/xianyu-auto-reply) +[![Docker](https://img.shields.io/badge/Docker-一键部署-blue?logo=docker)](https://github.com/zhinianboke/xianyu-auto-reply#-快速开始) -**✨ 基于闲鱼API的自动发货系统,支持虚拟商品商品聊天窗口自动发货、消息自动回复等功能。** -**⚠️ 注意:本项目仅供学习交流使用,请勿用于商业用途。** +一个功能完整的闲鱼自动回复和管理系统,支持多用户、多账号管理,具备智能回复、自动发货、商品管理等企业级功能。 -## 🌟 核心特性 +## ✨ 核心特性 -- 🔐 **用户认证系统** - 安全的登录认证,保护管理界面 -- 👥 **多账号管理** - 支持同时管理多个闲鱼账号 -- 🎯 **智能关键词回复** - 每个账号独立的关键词回复设置 -- 💾 **数据持久化** - SQLite数据库存储账号和关键词数据 -- 🌐 **美观Web界面** - 响应式设计,操作简单直观 -- 📡 **API接口** - 完整的RESTful API支持 -- 🔄 **实时消息处理** - 基于WebSocket的实时消息监控 -- 📊 **订单状态监控** - 实时跟踪订单状态变化 -- 📝 **完善的日志系统** - 详细的操作日志记录 +### 🔐 多用户系统 +- **用户注册登录** - 支持邮箱验证码注册,图形验证码保护 +- **数据完全隔离** - 每个用户的数据独立存储,互不干扰 +- **权限管理** - 严格的用户权限控制和JWT认证 +- **安全保护** - 防暴力破解、会话管理、安全日志 -## 🛠️ 快速开始 +### 📱 多账号管理 +- **无限账号支持** - 每个用户可管理多个闲鱼账号 +- **独立运行** - 每个账号独立监控,互不影响 +- **实时状态** - 账号连接状态实时监控 +- **批量操作** - 支持批量启动、停止账号任务 -### ⛳ 运行环境 -- Python 3.7+ +### 🤖 智能回复系统 +- **关键词匹配** - 支持精确关键词匹配回复 +- **AI智能回复** - 集成OpenAI API,支持上下文理解 +- **变量替换** - 回复内容支持动态变量(用户名、商品信息等) +- **优先级策略** - 关键词回复优先,AI回复兜底 + +### 🚚 自动发货功能 +- **智能匹配** - 基于商品信息自动匹配发货规则 +- **多种触发** - 支持付款消息、小刀消息等多种触发条件 +- **防重复发货** - 智能防重复机制,避免重复发货 +- **卡密发货** - 支持文本内容和卡密文件发货 + +### 🛍️ 商品管理 +- **自动收集** - 消息触发时自动收集商品信息 +- **API获取** - 通过闲鱼API获取完整商品详情 +- **批量管理** - 支持批量查看、编辑商品信息 +- **智能去重** - 自动去重,避免重复存储 + +### 📊 系统监控 +- **实时日志** - 完整的操作日志记录和查看 +- **性能监控** - 系统资源使用情况监控 +- **健康检查** - 服务状态健康检查 +- **数据备份** - 自动数据备份和恢复 + +## 🚀 快速开始 + +### 方式一:Docker 一键部署(最简单) -### 🎯 安装依赖 ```bash +# 创建数据目录 +mkdir -p xianyu-auto-reply + +# 一键启动容器 +docker run -d \ + -p 8080:8080 \ + -v $PWD/xianyu-auto-reply/:/app/data/ \ + --name xianyu-auto-reply \ + --privileged=true \ + registry.cn-shanghai.aliyuncs.com/zhinian-software/xianyu-auto-reply:1.0 + +# 访问系统 +# http://localhost:8080 +``` + +### 方式二:Docker Compose 部署(推荐) + +```bash +# 1. 克隆项目 +git clone https://github.com/zhinianboke/xianyu-auto-reply.git +cd xianyu-auto-reply + +# 2. 一键部署 +./docker-deploy.sh + +# 3. 访问系统 +# http://localhost:8080 +``` + +### 方式三:本地部署 + +```bash +# 1. 克隆项目 +git clone https://github.com/zhinianboke/xianyu-auto-reply.git +cd xianyu-auto-reply + +# 2. 安装依赖 pip install -r requirements.txt -``` -### 🎨 配置说明 -1. 在 `global_config.yml` 中配置基本参数 -2. 系统支持多账号管理,可通过Web界面添加多个闲鱼账号Cookie - -### 🚀 运行项目 -```bash +# 3. 启动系统 python Start.py + +# 4. 访问系统 +# http://localhost:8080 ``` -### 🔐 登录系统 -1. 启动后访问 `http://localhost:8080` -2. 默认登录账号: - - 用户名:`admin` - - 密码:`admin123` -3. 登录后可进入管理界面进行操作 +### 🐳 Docker 部署说明 + +#### 一键部署特点 +- **无需配置** - 使用预构建镜像,开箱即用 +- **数据持久化** - 自动挂载数据目录,数据不丢失 +- **快速启动** - 30秒内完成部署 +- **生产就绪** - 包含所有依赖和优化配置 + +#### 容器管理命令 +```bash +# 查看容器状态 +docker ps + +# 查看容器日志 +docker logs -f xianyu-auto-reply + +# 停止容器 +docker stop xianyu-auto-reply + +# 重启容器 +docker restart xianyu-auto-reply + +# 删除容器 +docker rm -f xianyu-auto-reply +``` + +## 📋 系统使用 + +### 1. 用户注册 +- 访问 `http://localhost:8080/register.html` +- 填写用户信息,完成邮箱验证 +- 输入图形验证码完成注册 + +### 2. 添加闲鱼账号 +- 登录系统后进入主界面 +- 点击"添加新账号" +- 输入账号ID和完整的Cookie值 +- 系统自动启动账号监控任务 + +### 3. 配置自动回复 +- **关键词回复**:设置关键词和对应回复内容 +- **AI回复**:配置OpenAI API密钥启用智能回复 +- **默认回复**:设置未匹配时的默认回复 + +### 4. 设置自动发货 +- 添加发货规则,设置商品关键词和发货内容 +- 支持文本内容和卡密文件两种发货方式 +- 系统检测到付款消息时自动发货 + +## 🏗️ 系统架构 + +``` +┌─────────────────────────────────────┐ +│ Web界面 (FastAPI) │ +│ 用户管理 + 功能界面 │ +└─────────────┬───────────────────────┘ + │ +┌─────────────▼───────────────────────┐ +│ CookieManager │ +│ 多账号任务管理 │ +└─────────────┬───────────────────────┘ + │ +┌─────────────▼───────────────────────┐ +│ XianyuLive (多实例) │ +│ WebSocket连接 + 消息处理 │ +└─────────────┬───────────────────────┘ + │ +┌─────────────▼───────────────────────┐ +│ SQLite数据库 │ +│ 用户数据 + 商品信息 + 配置数据 │ +└─────────────────────────────────────┘ +``` ## 📁 项目结构 + ``` -├── Start.py # 项目启动入口 -├── XianyuAutoAsync.py # 核心业务逻辑 -├── config.py # 配置管理 -├── cookie_manager.py # Cookie管理器 -├── db_manager.py # 数据库管理 -├── reply_server.py # FastAPI服务器 -├── utils/ # 工具函数目录 -│ ├── xianyu_utils.py # 闲鱼相关工具 -│ ├── message_utils.py # 消息处理工具 -│ └── ws_utils.py # WebSocket工具 -├── static/ # 静态资源 -│ ├── index.html # 管理界面 -│ └── login.html # 登录页面 -├── logs/ # 日志文件 -├── global_config.yml # 全局配置文件 -├── xianyu_data.db # SQLite数据库 -└── requirements.txt # Python依赖 +xianyu-auto-reply/ +├── Start.py # 主启动文件 +├── XianyuAutoAsync.py # 闲鱼WebSocket客户端核心 +├── reply_server.py # FastAPI Web服务器 +├── db_manager.py # 数据库管理模块 +├── cookie_manager.py # Cookie和任务管理 +├── ai_reply_engine.py # AI回复引擎 +├── config.py # 配置管理 +├── file_log_collector.py # 日志收集器 +├── global_config.yml # 全局配置文件 +├── requirements.txt # Python依赖 +├── docker-compose.yml # Docker编排配置 +├── Dockerfile # Docker镜像构建 +├── static/ # 前端静态文件 +│ ├── index.html # 主界面 +│ ├── login.html # 登录页面 +│ ├── register.html # 注册页面 +│ └── ... # 其他页面和资源 +├── logs/ # 日志文件目录 +├── data/ # 数据库文件目录 +└── backups/ # 备份文件目录 ``` -## 🎯 主要功能 +## ⚙️ 配置说明 -### 1. 用户认证系统 -- 安全的登录认证机制 -- Session token管理 -- 自动登录状态检查 -- 登出功能 +### 环境变量配置 +系统支持通过环境变量或 `.env` 文件进行配置: -### 2. 多账号管理 -- 支持添加多个闲鱼账号 -- 每个账号独立管理 -- Cookie安全存储 -- 账号状态监控 +```bash +# 基础配置 +WEB_PORT=8080 +ADMIN_USERNAME=admin +ADMIN_PASSWORD=admin123 +JWT_SECRET_KEY=your-secret-key -### 3. 智能关键词回复 -- 每个账号独立的关键词设置 -- 支持变量替换:`{send_user_name}`, `{send_user_id}`, `{send_message}` -- 实时关键词匹配 -- 默认回复机制 +# 多用户系统 +MULTIUSER_ENABLED=true +USER_REGISTRATION_ENABLED=true +EMAIL_VERIFICATION_ENABLED=true +CAPTCHA_ENABLED=true -### 4. Web管理界面 -- 响应式设计,支持移动端 -- 直观的操作界面 -- 实时数据更新 -- 操作反馈提示 +# AI回复配置 +AI_REPLY_ENABLED=false +DEFAULT_AI_MODEL=qwen-plus +DEFAULT_AI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 -## 🔌 API 接口说明 - -### 智能回复接口 -`POST http://localhost:8080/xianyu/reply` - -#### 接口说明 -你需要实现这个接口,本项目会调用这个接口获取自动回复的内容并发送给客户 -不实现这个接口也没关系,系统会默认回复,你也可以配置默认回复的内容 -用于处理闲鱼消息的自动回复,支持对接大语言模型进行智能回复。 - -**通过这个接口可以检测到用户是否已付款,然后回复虚拟资料内容即可** -#### 请求参数 -```json -{ - "msg_time": "消息时间", - "user_url": "用户主页URL", - "send_user_id": "发送者ID", - "send_user_name": "发送者昵称", - "item_id": "商品ID", - "send_message": "发送的消息内容", - "chat_id": "会话ID" -} +# 自动发货配置 +AUTO_DELIVERY_ENABLED=true +AUTO_DELIVERY_TIMEOUT=30 ``` -#### 响应格式 -```json -{ - "code": 200, - "data": { - "send_msg": "回复的消息内容" - } -} +### 全局配置文件 +`global_config.yml` 包含详细的系统配置,支持: +- WebSocket连接参数 +- API接口配置 +- 自动回复设置 +- 商品管理配置 +- 日志配置等 + +## 🔧 高级功能 + +### AI回复配置 +1. 在用户设置中配置OpenAI API密钥 +2. 选择AI模型(支持GPT-3.5、GPT-4、通义千问等) +3. 设置回复策略和提示词 +4. 启用AI回复功能 + +### 自动发货规则 +1. 进入发货管理页面 +2. 添加发货规则,设置商品关键词 +3. 上传卡密文件或输入发货内容 +4. 系统自动匹配商品并发货 + +### 商品信息管理 +1. 系统自动收集消息中的商品信息 +2. 通过API获取完整商品详情 +3. 支持手动编辑商品信息 +4. 为自动发货提供准确的商品数据 + +## 📊 监控和维护 + +### 日志管理 +- **实时日志**:Web界面查看实时系统日志 +- **日志文件**:`logs/` 目录下的按日期分割的日志文件 +- **日志级别**:支持DEBUG、INFO、WARNING、ERROR级别 + +### 数据备份 +```bash +# 手动备份 +./docker-deploy.sh backup + +# 查看备份 +ls backups/ ``` -#### 配置示例 -```yaml -AUTO_REPLY: - api: - enabled: true # 是否启用API回复 - timeout: 10 # 超时时间(秒) - url: http://localhost:8080/xianyu/reply +### 健康检查 +```bash +# 检查服务状态 +curl http://localhost:8080/health + +# 查看系统状态 +./docker-deploy.sh status ``` -#### 使用场景 -- 当收到买家消息时,系统会自动调用此接口 -- 支持接入 ChatGPT、文心一言等大语言模型 -- 支持自定义回复规则和模板 -- 支持消息变量替换(如 `{send_user_name}`) +## 🔒 安全特性 -#### 注意事项 -- 接口需要返回正确的状态码(200)和消息内容 -- 建议实现错误重试机制 -- 注意处理超时情况(默认10秒) -- 可以根据需要扩展更多的参数和功能 +- **JWT认证**:安全的用户认证机制 +- **图形验证码**:防止自动化攻击 +- **邮箱验证**:确保用户邮箱真实性 +- **数据隔离**:用户数据完全隔离 +- **会话管理**:安全的会话超时机制 +- **操作日志**:完整的用户操作记录 -## 🗝️ 注意事项 -- 请确保闲鱼账号已登录并获取有效的 Cookie -- 建议在正式环境使用前先在测试环境验证 -- 定期检查日志文件,及时处理异常情况 -- 使用大模型时注意 API 调用频率和成本控制 +## 🤝 贡献指南 -## 📝 效果 +欢迎为项目做出贡献!您可以通过以下方式参与: +### 📝 提交问题 +- 在 [GitHub Issues](https://github.com/zhinianboke/xianyu-auto-reply/issues) 中报告Bug +- 提出新功能建议和改进意见 +- 分享使用经验和最佳实践 -![image-20250611004531745](https://typeropic.oss-cn-beijing.aliyuncs.com/cp/image-20250611004531745.png) +### 🔧 代码贡献 +- Fork 项目到您的GitHub账号 +- 创建功能分支:`git checkout -b feature/your-feature` +- 提交更改:`git commit -am 'Add some feature'` +- 推送分支:`git push origin feature/your-feature` +- 提交 Pull Request -![image-20250611004549662](https://typeropic.oss-cn-beijing.aliyuncs.com/cp/image-20250611004549662.png) +### 📖 文档贡献 +- 改进现有文档 +- 添加使用示例 +- 翻译文档到其他语言 -## 🧸特别鸣谢 +## 📞 技术支持 -本项目参考了以下开源项目: https://github.com/cv-cat/XianYuApis +### 🔧 故障排除 +如遇问题,请: +1. 查看日志:`docker-compose logs -f` +2. 检查状态:`./docker-deploy.sh status` +3. 健康检查:`curl http://localhost:8080/health` -感谢[@CVcat](https://github.com/cv-cat)的技术支持 +### 💬 交流群组 -## 📞 联系方式 -如有问题或建议,欢迎提交 Issue 或 Pull Request。 +欢迎加入我们的技术交流群,获取实时帮助和最新更新: -## 技术交流 +#### 微信交流群 +微信群二维码 -![image-20250611004141387](https://typeropic.oss-cn-beijing.aliyuncs.com/cp/image-20250611004141387.png) +#### QQ交流群 +QQ群二维码 + +### 📧 联系方式 +- **技术支持**:遇到问题可在群内咨询 +- **功能建议**:欢迎提出改进建议 +- **Bug反馈**:发现问题请及时反馈 + +--- + +🎉 **开始使用闲鱼自动回复系统,让您的闲鱼店铺管理更加智能高效!** diff --git a/REGISTER_PAGE_OPTIMIZATION.md b/REGISTER_PAGE_OPTIMIZATION.md deleted file mode 100644 index cba7408..0000000 --- a/REGISTER_PAGE_OPTIMIZATION.md +++ /dev/null @@ -1,233 +0,0 @@ -# 注册页面布局优化 - -## 🎯 优化目标 - -将注册页面优化为一屏显示,消除垂直滚动条,提升用户体验。 - -## 📊 优化前后对比 - -### 优化前的问题 -- ❌ 页面过长,需要垂直滚动 -- ❌ 间距过大,浪费屏幕空间 -- ❌ 字体和元素尺寸偏大 -- ❌ 表单提示文字占用过多空间 - -### 优化后的改进 -- ✅ 整个页面在一屏内显示完整 -- ✅ 紧凑而美观的布局 -- ✅ 适当的间距和字体大小 -- ✅ 简化的提示文字 - -## 🔧 具体优化措施 - -### 1. 容器和布局优化 - -**优化前:** -```css -.register-container { - max-width: 450px; - padding: 2rem; -} -.register-header { - padding: 2rem; -} -.register-body { - padding: 2rem; -} -``` - -**优化后:** -```css -.register-container { - max-width: 420px; - max-height: 95vh; - overflow-y: auto; -} -.register-header { - padding: 1.2rem; -} -.register-body { - padding: 1.2rem; -} -``` - -### 2. 表单元素优化 - -**优化前:** -```css -.form-control { - padding: 12px 15px; - border: 2px solid #e9ecef; - border-radius: 10px; -} -.mb-3 { - margin-bottom: 1rem; -} -``` - -**优化后:** -```css -.form-control { - padding: 8px 12px; - border: 1px solid #e9ecef; - border-radius: 8px; - font-size: 0.9rem; -} -.mb-3 { - margin-bottom: 0.8rem !important; -} -``` - -### 3. 文字和标签优化 - -**优化前:** -- 详细的表单提示文字 -- 较大的字体尺寸 -- 较多的说明文本 - -**优化后:** -- 简化的占位符文字 -- 适中的字体尺寸 -- 精简的说明文本 - -```css -.form-label { - font-size: 0.85rem; - margin-bottom: 0.3rem; -} -.form-text { - font-size: 0.75rem; - margin-top: 0.2rem; -} -``` - -### 4. 按钮和交互元素优化 - -**优化前:** -```css -.btn-register { - padding: 12px; - border-radius: 10px; -} -.btn-code { - border-radius: 10px; -} -``` - -**优化后:** -```css -.btn-register { - padding: 10px; - border-radius: 8px; - font-size: 0.9rem; -} -.btn-code { - padding: 8px 12px; - border-radius: 8px; - font-size: 0.85rem; -} -``` - -### 5. 图形验证码优化 - -**优化前:** -- 验证码图片高度 38px -- 较大的间距 - -**优化后:** -- 验证码图片高度 32px -- 紧凑的布局 -- 使用 `g-2` 类减少列间距 - -```html -
-
- -
-
- -
-
-``` - -### 6. 响应式优化 - -添加了针对小屏幕的特殊优化: - -```css -@media (max-height: 700px) { - .register-header { padding: 1rem; } - .mb-3 { margin-bottom: 0.6rem !important; } - .form-control { padding: 6px 10px; } -} - -@media (max-width: 480px) { - .register-container { margin: 5px; } - .row.g-2 > * { padding: 0.25rem; } -} -``` - -## 📱 用户体验提升 - -### 视觉效果 -- **更紧凑**:整个表单在一屏内完整显示 -- **更清晰**:减少了视觉噪音,重点突出 -- **更现代**:圆角和间距更加协调 - -### 交互体验 -- **无滚动**:用户无需滚动即可看到所有内容 -- **快速填写**:表单元素紧凑,填写更高效 -- **移动友好**:在手机上也能良好显示 - -### 功能完整性 -- ✅ 保持所有原有功能 -- ✅ 图形验证码正常工作 -- ✅ 邮箱验证码流程完整 -- ✅ 表单验证逻辑不变 - -## 🎨 设计原则 - -1. **简洁性**:去除不必要的装饰和间距 -2. **功能性**:保持所有功能完整可用 -3. **可读性**:确保文字清晰易读 -4. **一致性**:保持设计风格统一 -5. **响应性**:适配不同屏幕尺寸 - -## 📏 尺寸对比 - -| 元素 | 优化前 | 优化后 | 节省空间 | -|------|--------|--------|----------| -| 容器内边距 | 2rem | 1.2rem | 40% | -| 表单间距 | 1rem | 0.8rem | 20% | -| 输入框内边距 | 12px 15px | 8px 12px | 33% | -| 按钮内边距 | 12px | 10px | 17% | -| 验证码高度 | 38px | 32px | 16% | - -## 🔍 测试建议 - -1. **不同分辨率测试** - - 1920x1080 (桌面) - - 1366x768 (笔记本) - - 375x667 (手机) - -2. **不同浏览器测试** - - Chrome - - Firefox - - Safari - - Edge - -3. **功能完整性测试** - - 图形验证码生成和验证 - - 邮箱验证码发送 - - 表单提交和验证 - - 错误提示显示 - -## 🎉 优化成果 - -- **✅ 一屏显示**:消除了垂直滚动条 -- **✅ 美观紧凑**:保持了视觉美感 -- **✅ 功能完整**:所有功能正常工作 -- **✅ 响应式**:适配各种屏幕尺寸 -- **✅ 用户友好**:提升了整体用户体验 - -现在用户可以在一个屏幕内完成整个注册流程,无需滚动,大大提升了用户体验! diff --git a/SYSTEM_IMPROVEMENTS_SUMMARY.md b/SYSTEM_IMPROVEMENTS_SUMMARY.md deleted file mode 100644 index 930f8eb..0000000 --- a/SYSTEM_IMPROVEMENTS_SUMMARY.md +++ /dev/null @@ -1,298 +0,0 @@ -# 系统改进功能总结 - -## 🎯 改进概述 - -根据用户需求,对闲鱼自动回复系统进行了三项重要改进,提升了管理员的使用体验和数据管理能力。 - -## ✅ 已完成的改进 - -### 1. 📋 日志界面优化 - -#### 改进内容 -- **最新日志置顶**:日志默认最新的显示在最上面 -- **自动滚动调整**:页面加载后自动滚动到顶部显示最新日志 - -#### 技术实现 -```javascript -// 反转日志数组,让最新的日志显示在最上面 -const reversedLogs = [...logs].reverse(); - -// 自动滚动到顶部(显示最新日志) -scrollToTop(); -``` - -#### 用户体验提升 -- ✅ 最新日志一目了然 -- ✅ 无需手动滚动查看最新信息 -- ✅ 符合用户查看习惯 - -### 2. 🗂️ 系统管理简化 - -#### 改进内容 -- **删除JSON格式备份**:移除了兼容模式的JSON备份功能 -- **保留数据库模式**:只保留更高效的数据库文件备份 -- **界面简化**:备份管理界面更加简洁明了 - -#### 删除的功能 -- ❌ JSON格式备份导出 -- ❌ JSON格式备份导入 -- ❌ 相关的JavaScript函数 - -#### 保留的功能 -- ✅ 数据库文件直接下载 -- ✅ 数据库文件直接上传恢复 -- ✅ 备份文件列表查询 - -#### 优势对比 -| 特性 | 数据库备份 | JSON备份(已删除) | -|------|------------|-------------------| -| 备份速度 | ⚡ 极快 | 🐌 较慢 | -| 文件大小 | 📦 最小 | 📦 较大 | -| 恢复速度 | ⚡ 极快 | 🐌 较慢 | -| 操作复杂度 | 🟢 简单 | 🟡 复杂 | - -### 3. 🗄️ 数据管理功能(全新) - -#### 功能概述 -新增了完整的数据管理功能,允许管理员查看和管理数据库中的所有表数据。 - -#### 主要特性 - -##### 📊 表数据查看 -- **表选择器**:下拉框显示所有数据表及中文含义 -- **数据展示**:表格形式显示所有记录 -- **列信息**:自动获取表结构和列名 -- **记录统计**:实时显示记录数量 - -##### 🗑️ 数据删除功能 -- **单条删除**:支持删除指定记录 -- **批量清空**:支持清空整个表(除用户表外) -- **确认机制**:危险操作需要二次确认 -- **权限保护**:不能删除管理员自己 - -##### 🔒 安全机制 -- **权限验证**:只有admin用户可以访问 -- **表名验证**:只允许操作预定义的安全表 -- **管理员保护**:不能删除管理员用户 -- **操作日志**:所有操作都有详细日志 - -#### 支持的数据表 - -| 表名 | 中文含义 | 支持操作 | -|------|----------|----------| -| users | 用户表 | 查看、删除(除管理员) | -| cookies | Cookie账号表 | 查看、删除、清空 | -| keywords | 关键字表 | 查看、删除、清空 | -| default_replies | 默认回复表 | 查看、删除、清空 | -| ai_reply_settings | AI回复设置表 | 查看、删除、清空 | -| message_notifications | 消息通知表 | 查看、删除、清空 | -| cards | 卡券表 | 查看、删除、清空 | -| delivery_rules | 发货规则表 | 查看、删除、清空 | -| notification_channels | 通知渠道表 | 查看、删除、清空 | -| user_settings | 用户设置表 | 查看、删除、清空 | -| email_verifications | 邮箱验证表 | 查看、删除、清空 | -| captcha_codes | 验证码表 | 查看、删除、清空 | - -#### 界面设计 - -``` -┌─────────────────────────────────────────────────────────────┐ -│ 数据管理 │ -├─────────────────────────┬───────────────────────────────────┤ -│ 选择数据表 │ 数据统计 │ -│ │ │ -│ [下拉框选择表] │ [记录数显示] [刷新按钮] │ -└─────────────────────────┴───────────────────────────────────┘ - -┌─────────────────────────────────────────────────────────────┐ -│ 数据内容 │ -│ ┌─────┬─────────┬─────────┬─────────┬─────────┬─────────┐ │ -│ │ ID │ 字段1 │ 字段2 │ 字段3 │ 字段4 │ 操作 │ │ -│ ├─────┼─────────┼─────────┼─────────┼─────────┼─────────┤ │ -│ │ 1 │ 数据1 │ 数据2 │ 数据3 │ 数据4 │ [删除] │ │ -│ │ 2 │ 数据1 │ 数据2 │ 数据3 │ 数据4 │ [删除] │ │ -│ └─────┴─────────┴─────────┴─────────┴─────────┴─────────┘ │ -└─────────────────────────────────────────────────────────────┘ -``` - -## 🔧 技术实现 - -### 后端API接口 - -#### 数据管理API -```python -# 获取表数据 -GET /admin/data/{table_name} - -# 删除单条记录 -DELETE /admin/data/{table_name}/{record_id} - -# 清空表数据 -DELETE /admin/data/{table_name} -``` - -#### 数据库方法 -```python -# 获取表数据和结构 -def get_table_data(self, table_name: str) - -# 删除指定记录 -def delete_table_record(self, table_name: str, record_id: str) - -# 清空表数据 -def clear_table_data(self, table_name: str) -``` - -### 前端实现 - -#### 页面路由 -- `/data_management.html` - 数据管理页面 - -#### 核心功能 -```javascript -// 加载表数据 -function loadTableData() - -// 显示表数据 -function displayTableData(data, columns) - -// 删除记录 -function deleteRecord(record, index) - -// 清空表数据 -function confirmDeleteAll() -``` - -## 🎨 用户界面 - -### 管理员菜单更新 -在主页侧边栏的管理员功能区域新增: -``` -管理员功能 -├── 用户管理 -├── 系统日志 -└── 数据管理 ← 新增 -``` - -### 数据管理页面特性 -- **响应式设计**:适配各种屏幕尺寸 -- **表格滚动**:支持大量数据的滚动查看 -- **固定表头**:滚动时表头保持可见 -- **操作确认**:删除操作有确认对话框 -- **实时统计**:动态显示记录数量 - -## 🛡️ 安全特性 - -### 权限控制 -- **管理员专用**:所有功能只有admin用户可以访问 -- **前端验证**:页面加载时验证用户身份 -- **后端验证**:API接口严格验证管理员权限 - -### 数据保护 -- **表名白名单**:只允许操作预定义的安全表 -- **管理员保护**:不能删除管理员用户记录 -- **操作确认**:危险操作需要用户确认 -- **详细日志**:所有操作都有完整的日志记录 - -### 错误处理 -- **异常捕获**:完善的错误处理机制 -- **用户提示**:清晰的成功/失败提示 -- **数据回滚**:失败时自动回滚操作 - -## 💡 使用方法 - -### 访问数据管理 -1. 使用admin账号登录系统 -2. 在主页侧边栏点击"数据管理" -3. 进入数据管理页面 - -### 查看表数据 -1. 在下拉框中选择要查看的数据表 -2. 系统自动加载并显示表数据 -3. 查看记录数量和表信息 - -### 删除数据 -1. 点击记录行的"删除"按钮 -2. 在确认对话框中查看记录详情 -3. 确认删除操作 - -### 清空表数据 -1. 选择要清空的表 -2. 点击"清空表"按钮 -3. 确认清空操作(不可恢复) - -## 🎯 应用场景 - -### 1. 数据维护 -- 清理测试数据 -- 删除无效记录 -- 维护数据质量 - -### 2. 问题排查 -- 查看具体数据内容 -- 分析数据异常 -- 验证数据完整性 - -### 3. 系统管理 -- 监控数据增长 -- 管理用户数据 -- 清理过期信息 - -### 4. 开发调试 -- 查看数据结构 -- 验证功能效果 -- 测试数据操作 - -## 📊 改进效果 - -### 用户体验提升 -- ✅ 日志查看更直观(最新在上) -- ✅ 备份操作更简单(只保留数据库模式) -- ✅ 数据管理更方便(可视化操作) - -### 管理效率提升 -- ✅ 快速查看任意表数据 -- ✅ 便捷删除无效记录 -- ✅ 直观的数据统计信息 - -### 系统维护能力增强 -- ✅ 完整的数据管理功能 -- ✅ 安全的操作权限控制 -- ✅ 详细的操作日志记录 - -## 🚀 部署说明 - -### 立即可用 -- 重启服务后所有功能立即生效 -- 无需额外配置 -- 兼容现有数据 - -### 访问方式 -``` -数据管理: http://your-domain/data_management.html -日志管理: http://your-domain/log_management.html -用户管理: http://your-domain/user_management.html -``` - -### 权限要求 -- 只有username为'admin'的用户可以访问 -- 其他用户访问会自动跳转到首页 - -## 🎉 总结 - -通过本次改进,闲鱼自动回复系统现在具备了: - -### ✅ 主要成就 -1. **优化的日志体验**:最新日志优先显示 -2. **简化的备份管理**:只保留最高效的数据库备份 -3. **强大的数据管理**:可视化的数据库表管理功能 -4. **完善的权限控制**:严格的管理员权限验证 -5. **安全的操作机制**:完善的确认和保护机制 - -### 🎯 实用价值 -- **提升效率**:管理员操作更加便捷高效 -- **增强安全**:严格的权限控制和操作保护 -- **便于维护**:直观的数据管理和日志查看 -- **优化体验**:符合用户习惯的界面设计 - -现在您的多用户闲鱼自动回复系统具备了更加完善的管理功能!🎊 diff --git a/TOKEN_FIX_SUMMARY.md b/TOKEN_FIX_SUMMARY.md deleted file mode 100644 index 9184741..0000000 --- a/TOKEN_FIX_SUMMARY.md +++ /dev/null @@ -1,192 +0,0 @@ -# Token认证问题修复总结 - -## 🎯 问题描述 - -用户反馈:管理员页面可以访问,但是点击功能时提示"未登录",API调用返回401未授权错误。 - -## 🔍 问题分析 - -通过日志分析发现: -``` -INFO: 127.0.0.1:63674 - "GET /admin/users HTTP/1.1" 401 Unauthorized -INFO: 【未登录】 API响应: GET /admin/users - 401 (0.003s) -``` - -问题根源:**Token存储key不一致** - -### 🔧 具体问题 - -1. **登录页面** (`login.html`) 设置token: - ```javascript - localStorage.setItem('auth_token', result.token); - ``` - -2. **主页面** (`index.html`) 读取token: - ```javascript - let authToken = localStorage.getItem('auth_token'); - ``` - -3. **管理员页面** (`user_management.html`, `log_management.html`) 读取token: - ```javascript - const token = localStorage.getItem('token'); // ❌ 错误的key - ``` - -## ✅ 修复方案 - -### 统一Token存储Key - -将所有管理员页面的token读取统一为 `auth_token`: - -#### 1. 用户管理页面修复 -```javascript -// 修复前 -const token = localStorage.getItem('token'); - -// 修复后 -const token = localStorage.getItem('auth_token'); -``` - -修复的函数: -- `checkAdminPermission()` -- `loadSystemStats()` -- `loadUsers()` -- `confirmDeleteUser()` -- `logout()` - -#### 2. 日志管理页面修复 -```javascript -// 修复前 -const token = localStorage.getItem('token'); - -// 修复后 -const token = localStorage.getItem('auth_token'); -``` - -修复的函数: -- `checkAdminPermission()` -- `loadLogs()` -- `logout()` - -### 🔄 修复的文件 - -1. **static/user_management.html** - - 5处token读取修复 - - 1处token删除修复 - -2. **static/log_management.html** - - 3处token读取修复 - - 1处token删除修复 - -## 📊 Token流程图 - -``` -登录页面 (login.html) - ↓ 设置 -localStorage.setItem('auth_token', token) - ↓ 读取 -主页面 (index.html) - ↓ 读取 -管理员页面 (user_management.html, log_management.html) - ↓ 使用 -API调用 (Authorization: Bearer token) -``` - -## 🧪 验证方法 - -### 1. 手动验证 -1. 使用admin账号登录主页 -2. 点击侧边栏"用户管理" -3. 页面应该正常加载用户列表和统计信息 -4. 点击侧边栏"系统日志" -5. 页面应该正常显示系统日志 - -### 2. 开发者工具验证 -1. 打开浏览器开发者工具 -2. 查看 Application → Local Storage -3. 确认存在 `auth_token` 项 -4. 查看 Network 标签页 -5. API请求应该返回200状态码 - -### 3. 日志验证 -服务器日志应该显示: -``` -INFO: 【admin#1】 API请求: GET /admin/users -INFO: 【admin#1】 API响应: GET /admin/users - 200 (0.005s) -``` - -## 🎯 修复效果 - -### 修复前 -- ❌ 管理员页面API调用401错误 -- ❌ 日志显示"未登录"用户访问 -- ❌ 用户管理功能无法使用 -- ❌ 日志管理功能无法使用 - -### 修复后 -- ✅ 管理员页面API调用正常 -- ✅ 日志显示正确的用户信息 -- ✅ 用户管理功能完全可用 -- ✅ 日志管理功能完全可用 - -## 🔒 安全验证 - -修复后的安全机制: - -1. **Token验证**:所有管理员API都需要有效token -2. **权限检查**:只有admin用户可以访问管理员功能 -3. **自动跳转**:无效token自动跳转到登录页 -4. **统一认证**:所有页面使用相同的认证机制 - -## 💡 最佳实践 - -### 1. Token管理规范 -- 使用统一的token存储key -- 在所有页面保持一致的token读取方式 -- 及时清理过期或无效的token - -### 2. 错误处理 -- API调用失败时提供明确的错误信息 -- 401错误自动跳转到登录页 -- 403错误提示权限不足 - -### 3. 用户体验 -- 登录状态持久化 -- 页面间无缝跳转 -- 清晰的权限提示 - -## 🚀 部署说明 - -### 立即生效 -修复后无需重启服务器,刷新页面即可生效。 - -### 用户操作 -1. 如果当前已登录,刷新管理员页面即可 -2. 如果遇到问题,重新登录即可 -3. 确保使用admin账号访问管理员功能 - -## 📋 测试清单 - -- [ ] admin用户可以正常登录 -- [ ] 主页侧边栏显示管理员菜单 -- [ ] 用户管理页面正常加载 -- [ ] 用户管理功能正常工作 -- [ ] 日志管理页面正常加载 -- [ ] 日志管理功能正常工作 -- [ ] 非admin用户无法访问管理员功能 -- [ ] 无效token被正确拒绝 - -## 🎉 总结 - -通过统一token存储key,成功修复了管理员页面的认证问题: - -### 核心改进 -- **统一认证**:所有页面使用相同的token key (`auth_token`) -- **完整功能**:用户管理和日志管理功能完全可用 -- **安全保障**:权限验证和错误处理机制完善 - -### 用户体验 -- **无缝使用**:登录后可以直接使用所有管理员功能 -- **清晰反馈**:错误信息明确,操作结果及时反馈 -- **安全可靠**:严格的权限控制和认证机制 - -现在管理员功能已经完全正常工作,可以安全地管理用户和监控系统日志!🎊 diff --git a/UI_IMPROVEMENTS.md b/UI_IMPROVEMENTS.md deleted file mode 100644 index 1ac59fc..0000000 --- a/UI_IMPROVEMENTS.md +++ /dev/null @@ -1,92 +0,0 @@ -# 🎨 界面优化总结 - -## ✨ 主要改进 - -### 1. 🎯 Cookie显示优化 -- **❌ 修改前**: Cookie值被隐藏为星号 (`****`) -- **✅ 修改后**: 显示完整的Cookie内容,便于查看和调试 - -### 2. 🎨 视觉设计升级 -- **现代化配色方案**: 使用更现代的紫色主题 (`#4f46e5`) -- **渐变背景**: 美丽的渐变背景和卡片效果 -- **毛玻璃效果**: 卡片使用 `backdrop-filter: blur()` 实现毛玻璃效果 -- **阴影和动画**: 悬停时的阴影和位移动画效果 - -### 3. 🔧 功能增强 -- **一键复制Cookie**: 点击Cookie值或复制按钮即可复制到剪贴板 -- **改进的按钮组**: 更紧凑的按钮布局,包含复制功能 -- **更好的空状态**: 当没有账号时显示更友好的提示 - -### 4. 📱 响应式设计 -- **移动端优化**: 在小屏幕上按钮垂直排列 -- **自适应布局**: 表格和卡片在不同屏幕尺寸下的自适应 - -## 🛠️ 技术改进 - -### 新增API接口 -```javascript -GET /cookies/details -``` -返回包含Cookie ID和完整值的详细信息,而不仅仅是ID列表。 - -### CSS样式优化 -- **CSS变量**: 统一的颜色管理 -- **现代字体**: 使用 Inter 字体提升可读性 -- **代码字体**: Cookie值使用等宽字体 (JetBrains Mono) -- **流畅动画**: 所有交互都有平滑的过渡效果 - -### JavaScript功能增强 -- **复制功能**: 支持现代浏览器的 Clipboard API -- **降级方案**: 对于不支持的浏览器提供传统复制方法 -- **用户反馈**: 复制成功/失败的Toast提示 - -## 🎯 用户体验提升 - -### 1. Cookie管理 -- **完整显示**: 不再隐藏Cookie内容,便于调试 -- **一键复制**: 快速复制Cookie值到剪贴板 -- **格式化显示**: 使用等宽字体和适当的行高 - -### 2. 视觉反馈 -- **悬停效果**: 所有可交互元素都有悬停反馈 -- **状态指示**: 清晰的按钮状态和颜色区分 -- **加载动画**: 优雅的加载状态显示 - -### 3. 操作便利性 -- **按钮分组**: 相关操作按钮紧凑排列 -- **图标提示**: 每个按钮都有清晰的图标和提示 -- **确认对话框**: 危险操作有确认提示 - -## 📊 界面对比 - -| 功能 | 修改前 | 修改后 | -|------|--------|--------| -| Cookie显示 | 隐藏为星号 | 完整显示 | -| 复制功能 | 无 | 一键复制 | -| 视觉效果 | 基础Bootstrap | 现代化渐变设计 | -| 响应式 | 基本支持 | 完全优化 | -| 用户反馈 | 基础提示 | 丰富的Toast反馈 | - -## 🚀 使用说明 - -### 访问界面 -1. 启动系统: `python Start.py` -2. 打开浏览器: `http://localhost:8080` -3. 登录: `admin` / `admin123` - -### 主要功能 -- **添加账号**: 在顶部表单中输入账号ID和Cookie值 -- **查看Cookie**: 完整的Cookie值显示在表格中 -- **复制Cookie**: 点击Cookie值或复制按钮 -- **管理关键词**: 点击关键词按钮设置自动回复 -- **删除账号**: 点击删除按钮(有确认提示) - -## 🎉 总结 - -这次界面优化大幅提升了用户体验: -- ✅ **Cookie不再隐藏**,便于查看和调试 -- ✅ **现代化设计**,视觉效果更佳 -- ✅ **功能增强**,操作更便利 -- ✅ **响应式优化**,支持各种设备 - -界面现在更加美观、实用和用户友好!🎨✨ diff --git a/USER_LOGGING_IMPROVEMENT.md b/USER_LOGGING_IMPROVEMENT.md deleted file mode 100644 index 26baac1..0000000 --- a/USER_LOGGING_IMPROVEMENT.md +++ /dev/null @@ -1,249 +0,0 @@ -# 用户日志显示改进总结 - -## 🎯 改进目标 - -在多用户系统中,原有的日志无法识别具体的操作用户,导致调试和监控困难。本次改进为所有系统日志添加了当前登录用户的信息。 - -## 📊 改进内容 - -### 1. API请求/响应日志增强 - -#### 改进前 -``` -2025-07-25 15:40:28.714 | INFO | reply_server:log_requests:223 - 🌐 API请求: GET /keywords/执念小店70 -2025-07-25 15:40:28.725 | INFO | reply_server:log_requests:228 - ✅ API响应: GET /keywords/执念小店70 - 200 (0.011s) -``` - -#### 改进后 -``` -2025-07-25 15:40:28.714 | INFO | reply_server:log_requests:223 - 🌐 【admin#1】 API请求: GET /keywords/执念小店70 -2025-07-25 15:40:28.725 | INFO | reply_server:log_requests:228 - ✅ 【admin#1】 API响应: GET /keywords/执念小店70 - 200 (0.011s) -``` - -### 2. 业务操作日志增强 - -#### 用户认证相关 -- ✅ 登录尝试: `【username】尝试登录` -- ✅ 登录成功: `【username#user_id】登录成功` -- ✅ 登录失败: `【username】登录失败: 用户名或密码错误` -- ✅ 注册操作: `【username】尝试注册,邮箱: email` - -#### Cookie管理相关 -- ✅ 添加Cookie: `【username#user_id】尝试添加Cookie: cookie_id` -- ✅ 操作成功: `【username#user_id】Cookie添加成功: cookie_id` -- ✅ 权限冲突: `【username#user_id】Cookie ID冲突: cookie_id 已被其他用户使用` - -#### 卡券管理相关 -- ✅ 创建卡券: `【username#user_id】创建卡券: card_name` -- ✅ 创建成功: `【username#user_id】卡券创建成功: card_name (ID: card_id)` -- ✅ 创建失败: `【username#user_id】创建卡券失败: card_name - error` - -#### 关键字管理相关 -- ✅ 更新关键字: `【username#user_id】更新Cookie关键字: cookie_id, 数量: count` -- ✅ 权限验证: `【username#user_id】尝试操作其他用户的Cookie关键字: cookie_id` - -#### 用户设置相关 -- ✅ 设置更新: `【username#user_id】更新用户设置: key = value` -- ✅ 更新成功: `【username#user_id】用户设置更新成功: key` - -## 🔧 技术实现 - -### 1. 中间件增强 -```python -@app.middleware("http") -async def log_requests(request, call_next): - # 获取用户信息 - user_info = "未登录" - try: - auth_header = request.headers.get("Authorization") - if auth_header and auth_header.startswith("Bearer "): - token = auth_header.split(" ")[1] - if token in SESSION_TOKENS: - token_data = SESSION_TOKENS[token] - if time.time() - token_data['timestamp'] <= TOKEN_EXPIRE_TIME: - user_info = f"【{token_data['username']}#{token_data['user_id']}】" - except Exception: - pass - - logger.info(f"🌐 {user_info} API请求: {request.method} {request.url.path}") - # ... -``` - -### 2. 统一日志工具函数 -```python -def get_user_log_prefix(user_info: Dict[str, Any] = None) -> str: - """获取用户日志前缀""" - if user_info: - return f"【{user_info['username']}#{user_info['user_id']}】" - return "【系统】" - -def log_with_user(level: str, message: str, user_info: Dict[str, Any] = None): - """带用户信息的日志记录""" - prefix = get_user_log_prefix(user_info) - full_message = f"{prefix} {message}" - - if level.lower() == 'info': - logger.info(full_message) - elif level.lower() == 'error': - logger.error(full_message) - # ... -``` - -### 3. 业务接口改进 -```python -@app.post("/cookies") -def add_cookie(item: CookieIn, current_user: Dict[str, Any] = Depends(get_current_user)): - try: - log_with_user('info', f"尝试添加Cookie: {item.id}", current_user) - # 业务逻辑... - log_with_user('info', f"Cookie添加成功: {item.id}", current_user) - except Exception as e: - log_with_user('error', f"添加Cookie失败: {item.id} - {str(e)}", current_user) -``` - -## 📋 修改的文件和接口 - -### reply_server.py -- **中间件**: `log_requests` - API请求/响应日志 -- **工具函数**: `get_user_log_prefix`, `log_with_user` -- **认证接口**: 登录、注册接口 -- **业务接口**: Cookie管理、卡券管理、关键字管理、用户设置 - -### 修改的接口数量 -- **API中间件**: 1个(影响所有接口) -- **认证相关**: 2个接口(登录、注册) -- **Cookie管理**: 1个接口(添加Cookie) -- **卡券管理**: 1个接口(创建卡券) -- **关键字管理**: 1个接口(更新关键字) -- **用户设置**: 1个接口(更新设置) - -## 🎯 日志格式规范 - -### 用户标识格式 -- **已登录用户**: `【username#user_id】` -- **未登录用户**: `【未登录】` -- **系统操作**: `【系统】` - -### 日志级别使用 -- **INFO**: 正常操作、成功操作 -- **WARNING**: 权限验证失败、业务规则冲突 -- **ERROR**: 系统错误、操作失败 - -### 消息格式 -- **操作尝试**: `尝试{操作}: {对象}` -- **操作成功**: `{操作}成功: {对象}` -- **操作失败**: `{操作}失败: {对象} - {原因}` - -## 💡 日志分析技巧 - -### 1. 按用户过滤 -```bash -# 查看特定用户的所有操作 -grep '【admin#1】' logs/xianyu_2025-07-25.log - -# 查看特定用户的API请求 -grep '【admin#1】.*API请求' logs/xianyu_2025-07-25.log -``` - -### 2. 监控用户活动 -```bash -# 统计用户活跃度 -grep -o '【[^】]*#[^】]*】' logs/xianyu_2025-07-25.log | sort | uniq -c - -# 查看登录活动 -grep '登录' logs/xianyu_2025-07-25.log -``` - -### 3. 权限验证监控 -```bash -# 查看权限验证失败 -grep '无权限\|权限验证失败' logs/xianyu_2025-07-25.log - -# 查看跨用户访问尝试 -grep '尝试操作其他用户' logs/xianyu_2025-07-25.log -``` - -### 4. 错误追踪 -```bash -# 查看特定用户的错误 -grep 'ERROR.*【admin#1】' logs/xianyu_2025-07-25.log - -# 查看操作失败 -grep '失败.*【.*】' logs/xianyu_2025-07-25.log -``` - -## 🔍 监控指标建议 - -### 1. 用户活跃度指标 -- 每个用户的API调用频率 -- 用户登录频率和时长 -- 用户操作成功率 - -### 2. 安全监控指标 -- 登录失败次数(按用户) -- 权限验证失败次数 -- 跨用户访问尝试次数 - -### 3. 业务监控指标 -- Cookie操作频率(按用户) -- 卡券创建和使用情况 -- 用户设置修改频率 - -## 🚀 部署和使用 - -### 1. 立即生效 -重启服务后,新的日志格式立即生效: -```bash -# 重启服务 -docker-compose restart - -# 查看新的日志格式 -docker-compose logs -f | grep '【.*】' -``` - -### 2. 日志轮转配置 -确保日志轮转能够处理增加的日志内容: -```python -# loguru配置 -logger.add( - "logs/xianyu_{time:YYYY-MM-DD}.log", - rotation="100 MB", - retention="7 days", - compression="zip", - format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {name}:{function}:{line} - {message}" -) -``` - -### 3. 监控工具集成 -如果使用ELK、Grafana等监控工具,可以基于用户标识创建仪表板: -- 按用户分组的操作统计 -- 用户行为分析 -- 安全事件监控 - -## 🎉 改进效果 - -### 1. 调试效率提升 -- **问题定位**: 快速定位特定用户的问题 -- **操作追踪**: 完整的用户操作链路追踪 -- **权限验证**: 清晰的权限验证日志 - -### 2. 监控能力增强 -- **用户行为**: 详细的用户行为分析 -- **安全监控**: 实时的安全事件监控 -- **性能分析**: 按用户维度的性能分析 - -### 3. 运维管理优化 -- **故障排查**: 快速定位用户相关问题 -- **容量规划**: 基于用户活跃度的容量规划 -- **安全审计**: 完整的用户操作审计日志 - -## 📞 使用建议 - -1. **日志查看**: 使用 `grep` 命令按用户过滤日志 -2. **实时监控**: 使用 `tail -f` 实时监控特定用户操作 -3. **定期分析**: 定期分析用户活跃度和操作模式 -4. **安全审计**: 定期检查权限验证失败和异常操作 - ---- - -**总结**: 通过本次改进,多用户系统的日志现在具备了完整的用户标识能力,大大提升了系统的可观测性和可维护性! diff --git a/XianyuAutoAsync.py b/XianyuAutoAsync.py index 6f62b45..cb03407 100644 --- a/XianyuAutoAsync.py +++ b/XianyuAutoAsync.py @@ -86,6 +86,10 @@ class XianyuLive: # 通知防重复机制 self.last_notification_time = {} # 记录每种通知类型的最后发送时间 self.notification_cooldown = 300 # 5分钟内不重复发送相同类型的通知 + + # 自动发货防重复机制 + self.last_delivery_time = {} # 记录每个商品的最后发货时间 + self.delivery_cooldown = 60 # 1分钟内不重复发货 # 人工接管功能已禁用,永远走自动模式 # self.manual_mode_conversations = set() # 存储处于人工接管模式的会话ID @@ -94,6 +98,22 @@ class XianyuLive: # self.toggle_keywords = MANUAL_MODE.get('toggle_keywords', ['。']) # 切换关键词 self.session = None # 用于API调用的aiohttp session + def can_auto_delivery(self, item_id: str) -> bool: + """检查是否可以进行自动发货(防重复发货)""" + current_time = time.time() + last_delivery = self.last_delivery_time.get(item_id, 0) + + if current_time - last_delivery < self.delivery_cooldown: + logger.info(f"【{self.cookie_id}】商品 {item_id} 在冷却期内,跳过自动发货") + return False + + return True + + def mark_delivery_sent(self, item_id: str): + """标记商品已发货""" + self.last_delivery_time[item_id] = time.time() + logger.debug(f"【{self.cookie_id}】标记商品 {item_id} 已发货") + # 人工接管功能已禁用,以下方法不再使用 # def check_toggle_keywords(self, message): # """检查消息是否包含切换关键词""" @@ -1147,10 +1167,13 @@ class XianyuLive: delivery_content = db_manager.consume_batch_data(rule['card_id']) if delivery_content: + # 处理备注信息和变量替换 + final_content = self._process_delivery_content_with_description(delivery_content, rule.get('card_description', '')) + # 增加发货次数统计 db_manager.increment_delivery_times(rule['id']) - logger.info(f"自动发货成功: 规则ID={rule['id']}, 内容长度={len(delivery_content)}") - return delivery_content + logger.info(f"自动发货成功: 规则ID={rule['id']}, 内容长度={len(final_content)}") + return final_content else: logger.warning(f"获取发货内容失败: 规则ID={rule['id']}") return None @@ -1159,6 +1182,28 @@ class XianyuLive: logger.error(f"自动发货失败: {self._safe_str(e)}") return None + def _process_delivery_content_with_description(self, delivery_content: str, card_description: str) -> str: + """处理发货内容和备注信息,实现变量替换""" + try: + # 如果没有备注信息,直接返回发货内容 + if not card_description or not card_description.strip(): + return delivery_content + + # 替换备注中的变量 + processed_description = card_description.replace('{DELIVERY_CONTENT}', delivery_content) + + # 如果备注中包含变量替换,返回处理后的备注 + if '{DELIVERY_CONTENT}' in card_description: + return processed_description + else: + # 如果备注中没有变量,将备注和发货内容组合 + return f"{processed_description}\n\n{delivery_content}" + + except Exception as e: + logger.error(f"处理备注信息失败: {e}") + # 出错时返回原始发货内容 + return delivery_content + async def _get_api_card_content(self, rule, retry_count=0): """调用API获取卡券内容,支持重试机制""" max_retries = 3 @@ -1855,9 +1900,28 @@ class XianyuLive: elif send_message == '[你关闭了订单,钱款已原路退返]': logger.info(f'[{msg_time}] 【{self.cookie_id}】系统消息不处理') return + elif send_message == '发来一条消息': + logger.info(f'[{msg_time}] 【{self.cookie_id}】系统通知消息不处理') + return + elif send_message == '发来一条新消息': + logger.info(f'[{msg_time}] 【{self.cookie_id}】系统通知消息不处理') + return + elif send_message == '[买家确认收货,交易成功]': + logger.info(f'[{msg_time}] 【{self.cookie_id}】交易完成消息不处理') + return + elif send_message == '快给ta一个评价吧~' or send_message == '快给ta一个评价吧~': + logger.info(f'[{msg_time}] 【{self.cookie_id}】评价提醒消息不处理') + return + elif send_message == '[你已发货]': + logger.info(f'[{msg_time}] 【{self.cookie_id}】发货确认消息不处理') + return elif send_message == '[我已付款,等待你发货]': logger.info(f'[{msg_time}] 【{self.cookie_id}】【系统】买家已付款,准备自动发货') + # 检查是否可以进行自动发货(防重复) + if not self.can_auto_delivery(item_id): + return + # 构造用户URL user_url = f'https://www.goofish.com/personal?userId={send_user_id}' @@ -1872,6 +1936,9 @@ class XianyuLive: delivery_content = await self._auto_delivery(item_id, item_title) if delivery_content: + # 标记已发货(防重复) + self.mark_delivery_sent(item_id) + # 发送发货内容给买家 await self.send_msg(websocket, chat_id, send_user_id, delivery_content) logger.info(f'[{msg_time}] 【自动发货】已向 {user_url} 发送发货内容') @@ -1890,6 +1957,10 @@ class XianyuLive: elif send_message == '[已付款,待发货]': logger.info(f'[{msg_time}] 【{self.cookie_id}】【系统】买家已付款,准备自动发货') + # 检查是否可以进行自动发货(防重复) + if not self.can_auto_delivery(item_id): + return + # 构造用户URL user_url = f'https://www.goofish.com/personal?userId={send_user_id}' @@ -1904,6 +1975,9 @@ class XianyuLive: delivery_content = await self._auto_delivery(item_id, item_title) if delivery_content: + # 标记已发货(防重复) + self.mark_delivery_sent(item_id) + # 发送发货内容给买家 await self.send_msg(websocket, chat_id, send_user_id, delivery_content) logger.info(f'[{msg_time}] 【自动发货】已向 {user_url} 发送发货内容') @@ -1919,6 +1993,76 @@ class XianyuLive: await self.send_delivery_failure_notification(send_user_name, send_user_id, item_id, f"自动发货处理异常: {str(e)}") return + elif send_message == '[卡片消息]': + # 检查是否为"我已小刀,待刀成"的卡片消息 + try: + # 从消息中提取卡片内容 + card_title = None + if isinstance(message, dict) and "1" in message and isinstance(message["1"], dict): + message_1 = message["1"] + if "6" in message_1 and isinstance(message_1["6"], dict): + message_6 = message_1["6"] + if "3" in message_6 and isinstance(message_6["3"], dict): + message_6_3 = message_6["3"] + if "5" in message_6_3: + # 解析JSON内容 + try: + card_content = json.loads(message_6_3["5"]) + if "dxCard" in card_content and "item" in card_content["dxCard"]: + card_item = card_content["dxCard"]["item"] + if "main" in card_item and "exContent" in card_item["main"]: + ex_content = card_item["main"]["exContent"] + card_title = ex_content.get("title", "") + except (json.JSONDecodeError, KeyError) as e: + logger.debug(f"解析卡片消息失败: {e}") + + # 检查是否为"我已小刀,待刀成" + if card_title == "我已小刀,待刀成": + logger.info(f'[{msg_time}] 【{self.cookie_id}】【系统】检测到"我已小刀,待刀成",准备自动发货') + + # 检查是否可以进行自动发货(防重复) + if not self.can_auto_delivery(item_id): + return + + # 构造用户URL + user_url = f'https://www.goofish.com/personal?userId={send_user_id}' + + # 自动发货逻辑 + try: + # 设置默认标题(将通过API获取真实商品信息) + item_title = "待获取商品信息" + + logger.info(f"【{self.cookie_id}】准备自动发货: item_id={item_id}, item_title={item_title}") + + # 调用自动发货方法 + delivery_content = await self._auto_delivery(item_id, item_title) + + if delivery_content: + # 标记已发货(防重复) + self.mark_delivery_sent(item_id) + + # 发送发货内容给买家 + await self.send_msg(websocket, chat_id, send_user_id, delivery_content) + logger.info(f'[{msg_time}] 【自动发货】已向 {user_url} 发送发货内容') + await self.send_delivery_failure_notification(send_user_name, send_user_id, item_id, "发货成功") + else: + logger.warning(f'[{msg_time}] 【自动发货】未找到匹配的发货规则或获取发货内容失败') + # 发送自动发货失败通知 + await self.send_delivery_failure_notification(send_user_name, send_user_id, item_id, "未找到匹配的发货规则或获取发货内容失败") + + except Exception as e: + logger.error(f"自动发货处理异常: {self._safe_str(e)}") + # 发送自动发货异常通知 + await self.send_delivery_failure_notification(send_user_name, send_user_id, item_id, f"自动发货处理异常: {str(e)}") + + return + else: + logger.info(f'[{msg_time}] 【{self.cookie_id}】收到卡片消息,标题: {card_title or "未知"}') + + except Exception as e: + logger.error(f"处理卡片消息异常: {self._safe_str(e)}") + + # 如果不是目标卡片消息,继续正常处理流程 # 记录回复来源 reply_source = 'API' # 默认假设是API回复 diff --git a/backup_import_update_summary.md b/backup_import_update_summary.md deleted file mode 100644 index 710ae24..0000000 --- a/backup_import_update_summary.md +++ /dev/null @@ -1,193 +0,0 @@ -# 备份和导入功能更新总结 - -## 📋 更新概述 - -由于系统新增了多个AI相关的数据表,备份和导入功能需要更新以确保所有数据都能正确备份和恢复。 - -## 🔧 更新内容 - -### 1. **新增的表** - -在原有的10个表基础上,新增了3个AI相关表: - -#### 新增表列表: -- `ai_reply_settings` - AI回复配置表 -- `ai_conversations` - AI对话历史表 -- `ai_item_cache` - AI商品信息缓存表 - -### 2. **更新的备份表列表** - -#### 更新前(10个表): -```python -tables = [ - 'cookies', 'keywords', 'cookie_status', 'cards', - 'delivery_rules', 'default_replies', 'notification_channels', - 'message_notifications', 'system_settings', 'item_info' -] -``` - -#### 更新后(13个表): -```python -tables = [ - 'cookies', 'keywords', 'cookie_status', 'cards', - 'delivery_rules', 'default_replies', 'notification_channels', - 'message_notifications', 'system_settings', 'item_info', - 'ai_reply_settings', 'ai_conversations', 'ai_item_cache' -] -``` - -### 3. **更新的删除顺序** - -考虑到外键依赖关系,更新了导入时的表删除顺序: - -#### 更新前: -```python -tables = [ - 'message_notifications', 'notification_channels', 'default_replies', - 'delivery_rules', 'cards', 'item_info', 'cookie_status', 'keywords', 'cookies' -] -``` - -#### 更新后: -```python -tables = [ - 'message_notifications', 'notification_channels', 'default_replies', - 'delivery_rules', 'cards', 'item_info', 'cookie_status', 'keywords', - 'ai_conversations', 'ai_reply_settings', 'ai_item_cache', 'cookies' -] -``` - -### 4. **更新的验证列表** - -导入功能中的表验证列表也相应更新,确保新增的AI表能够正确导入。 - -## ✅ 测试验证结果 - -### 测试环境 -- 数据库表总数:13个 -- 测试数据:包含所有表类型的数据 -- 测试场景:导出、导入、文件操作 - -### 测试结果 -``` -🎉 所有测试通过!备份和导入功能正常! - -✅ 功能验证: - • 所有13个表都包含在备份中 - • 备份导出功能正常 - • 备份导入功能正常 - • 数据完整性保持 - • 文件操作正常 -``` - -### 数据完整性验证 -所有13个表的数据在备份和导入过程中保持完整: - -| 表名 | 数据一致性 | 说明 | -|------|------------|------| -| ai_conversations | ✅ 一致 | AI对话历史 | -| ai_item_cache | ✅ 一致 | AI商品缓存 | -| ai_reply_settings | ✅ 一致 | AI回复配置 | -| cards | ✅ 一致 | 卡券信息 | -| cookie_status | ✅ 一致 | 账号状态 | -| cookies | ✅ 一致 | 账号信息 | -| default_replies | ✅ 一致 | 默认回复 | -| delivery_rules | ✅ 一致 | 发货规则 | -| item_info | ✅ 一致 | 商品信息 | -| keywords | ✅ 一致 | 关键词 | -| message_notifications | ✅ 一致 | 消息通知 | -| notification_channels | ✅ 一致 | 通知渠道 | -| system_settings | ✅ 一致 | 系统设置 | - -## 🎯 功能特性 - -### 1. **完整性保证** -- 包含所有13个数据表 -- 保持外键依赖关系 -- 数据完整性验证 - -### 2. **安全性** -- 事务性操作,确保数据一致性 -- 管理员密码保护(不会被覆盖) -- 错误回滚机制 - -### 3. **兼容性** -- 向后兼容旧版本备份文件 -- 自动跳过不存在的表 -- 版本标识和时间戳 - -### 4. **易用性** -- 一键导出所有数据 -- 一键导入恢复数据 -- 详细的操作日志 - -## 📊 使用方法 - -### 导出备份 -```python -from db_manager import db_manager - -# 导出备份数据 -backup_data = db_manager.export_backup() - -# 保存到文件 -import json -with open('backup.json', 'w', encoding='utf-8') as f: - json.dump(backup_data, f, indent=2, ensure_ascii=False) -``` - -### 导入备份 -```python -from db_manager import db_manager -import json - -# 从文件读取备份 -with open('backup.json', 'r', encoding='utf-8') as f: - backup_data = json.load(f) - -# 导入备份数据 -success = db_manager.import_backup(backup_data) -``` - -## 🔄 升级说明 - -### 对现有用户的影响 -- ✅ **无影响**:现有备份文件仍然可以正常导入 -- ✅ **自动兼容**:系统会自动跳过不存在的新表 -- ✅ **数据安全**:不会丢失任何现有数据 - -### 新功能优势 -- ✅ **AI数据备份**:AI回复配置和对话历史得到保护 -- ✅ **完整备份**:所有功能数据都包含在备份中 -- ✅ **快速恢复**:可以完整恢复所有AI功能设置 - -## 💡 建议 - -### 1. **定期备份** -建议用户定期进行数据备份,特别是在: -- 重要配置更改后 -- 系统升级前 -- 大量数据操作前 - -### 2. **备份验证** -建议在重要操作前验证备份文件的完整性: -- 检查文件大小 -- 验证JSON格式 -- 确认包含所需表 - -### 3. **多重备份** -建议保留多个备份版本: -- 每日自动备份 -- 重要节点手动备份 -- 异地备份存储 - -## 🎉 总结 - -备份和导入功能已成功更新,现在能够: - -1. ✅ **完整备份**所有13个数据表 -2. ✅ **安全导入**保持数据完整性 -3. ✅ **向后兼容**旧版本备份文件 -4. ✅ **AI数据保护**包含所有AI功能数据 - -用户可以放心使用备份和导入功能,所有数据都得到了完整的保护! diff --git a/bargain_demo.py b/bargain_demo.py deleted file mode 100644 index b2c0a36..0000000 --- a/bargain_demo.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python3 -""" -议价功能演示脚本 -展示AI回复的议价轮数限制功能 -""" - -import asyncio -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from ai_reply_engine import ai_reply_engine -from db_manager import db_manager - -def simulate_bargain_conversation(): - """模拟议价对话流程""" - print("🎭 模拟议价对话流程") - print("=" * 50) - - # 测试参数 - cookie_id = "demo_account_001" - chat_id = "demo_chat_001" - user_id = "customer_001" - item_id = "item_12345" - user_name = "小明" - - # 商品信息 - item_info = { - 'title': 'iPhone 14 Pro 256GB 深空黑色', - 'price': 8999, - 'desc': '全新未拆封,国行正品,支持全国联保' - } - - # 设置AI回复配置(模拟) - ai_settings = { - 'ai_enabled': True, - 'model_name': 'qwen-plus', - 'api_key': 'demo-key', - 'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1', - 'max_discount_percent': 10, # 最大优惠10% - 'max_discount_amount': 500, # 最大优惠500元 - 'max_bargain_rounds': 3, # 最大议价3轮 - 'custom_prompts': '' - } - - # 保存配置 - db_manager.save_ai_reply_settings(cookie_id, ai_settings) - - # 清理之前的对话 - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute('DELETE FROM ai_conversations WHERE cookie_id = ? AND chat_id = ?', - (cookie_id, chat_id)) - db_manager.conn.commit() - except: - pass - - print(f"📱 商品信息:") - print(f" 标题: {item_info['title']}") - print(f" 价格: ¥{item_info['price']}") - print(f" 描述: {item_info['desc']}") - - print(f"\n⚙️ 议价设置:") - print(f" 最大议价轮数: {ai_settings['max_bargain_rounds']}") - print(f" 最大优惠百分比: {ai_settings['max_discount_percent']}%") - print(f" 最大优惠金额: ¥{ai_settings['max_discount_amount']}") - - # 模拟议价对话 - bargain_messages = [ - "你好,这个iPhone能便宜点吗?", - "8500能卖吗?", - "8800行不行?最后一次了", - "8700,真的不能再少了" - ] - - print(f"\n💬 议价对话模拟:") - print("-" * 30) - - for i, message in enumerate(bargain_messages, 1): - print(f"\n第{i}轮议价:") - print(f"👤 {user_name}: {message}") - - # 检查当前议价次数 - current_count = ai_reply_engine.get_bargain_count(chat_id, cookie_id) - max_rounds = ai_settings['max_bargain_rounds'] - - print(f"📊 当前议价次数: {current_count}/{max_rounds}") - - # 模拟意图检测为price - intent = "price" - - # 检查是否超出限制 - if current_count >= max_rounds: - print(f"🚫 已达到最大议价轮数限制!") - refuse_reply = "抱歉,这个价格已经是最优惠的了,不能再便宜了哦!" - print(f"🤖 AI回复: {refuse_reply}") - - # 保存对话记录 - ai_reply_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "user", message, intent) - ai_reply_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "assistant", refuse_reply, intent) - - print(f"✋ 议价结束,系统拒绝继续议价") - break - else: - # 模拟AI回复(因为没有真实API密钥,这里手动模拟) - if i == 1: - ai_reply = "您好!这个价格已经很优惠了,最多可以优惠200元,8799元怎么样?" - elif i == 2: - ai_reply = "8500太低了,我们再让一点,8699元,这已经是很大的优惠了!" - elif i == 3: - ai_reply = "好的,看您很有诚意,8799元成交,这真的是最低价了!" - else: - ai_reply = "抱歉,这个价格已经是最优惠的了!" - - print(f"🤖 AI回复: {ai_reply}") - - # 保存对话记录 - ai_reply_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "user", message, intent) - ai_reply_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "assistant", ai_reply, intent) - - # 显示最终统计 - print(f"\n📈 最终统计:") - final_count = ai_reply_engine.get_bargain_count(chat_id, cookie_id) - print(f" 总议价轮数: {final_count}") - print(f" 最大允许轮数: {max_rounds}") - print(f" 是否达到限制: {'是' if final_count >= max_rounds else '否'}") - -def show_bargain_features(): - """展示议价功能特性""" - print(f"\n🎯 议价功能特性说明:") - print("=" * 50) - - features = [ - "✅ 智能议价轮数统计:自动统计用户的议价次数", - "✅ 灵活轮数限制:可配置最大议价轮数(1-10轮)", - "✅ 优惠金额控制:设置最大优惠百分比和金额", - "✅ 友好拒绝回复:超出限制时礼貌拒绝继续议价", - "✅ 上下文感知:AI了解完整的议价历史", - "✅ 个性化策略:根据议价轮数调整回复策略", - "✅ 数据持久化:议价记录永久保存", - "✅ 实时生效:配置修改后立即生效" - ] - - for feature in features: - print(f" {feature}") - - print(f"\n💡 使用建议:") - suggestions = [ - "设置合理的最大议价轮数(建议3-5轮)", - "配合最大优惠百分比和金额使用", - "在AI提示词中强调议价策略", - "定期分析议价数据,优化策略", - "根据商品类型调整议价参数" - ] - - for suggestion in suggestions: - print(f" • {suggestion}") - -def main(): - """主函数""" - print("🚀 AI回复议价功能演示") - - # 模拟议价对话 - simulate_bargain_conversation() - - # 展示功能特性 - show_bargain_features() - - print(f"\n🎉 演示完成!") - print(f"\n📋 下一步:") - print(f" 1. 在Web界面配置真实的AI API密钥") - print(f" 2. 为需要的账号启用AI回复功能") - print(f" 3. 设置合适的议价参数") - print(f" 4. 测试实际的议价效果") - -if __name__ == "__main__": - main() diff --git a/cookie_manager.py b/cookie_manager.py index e742e6c..a901281 100644 --- a/cookie_manager.py +++ b/cookie_manager.py @@ -62,12 +62,12 @@ class CookieManager: except Exception as e: logger.error(f"XianyuLive 任务异常({cookie_id}): {e}") - async def _add_cookie_async(self, cookie_id: str, cookie_value: str): + 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 - # 保存到数据库 - db_manager.save_cookie(cookie_id, cookie_value) + # 保存到数据库,如果没有指定user_id,则保持原有绑定关系 + db_manager.save_cookie(cookie_id, cookie_value, user_id) task = self.loop.create_task(self._run_xianyu(cookie_id, cookie_value)) self.tasks[cookie_id] = task logger.info(f"已启动账号任务: {cookie_id}") @@ -83,7 +83,7 @@ class CookieManager: logger.info(f"已移除账号: {cookie_id}") # ------------------------ 对外线程安全接口 ------------------------ - def add_cookie(self, cookie_id: str, cookie_value: str, kw_list: Optional[List[Tuple[str, str]]] = None): + 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 @@ -96,9 +96,9 @@ class CookieManager: if current_loop and current_loop == self.loop: # 同一事件循环中,直接调度 - return self.loop.create_task(self._add_cookie_async(cookie_id, cookie_value)) + 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), self.loop) + 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): diff --git a/db_manager.py b/db_manager.py index 60e8a5a..2865649 100644 --- a/db_manager.py +++ b/db_manager.py @@ -182,11 +182,23 @@ class DBManager: data_content TEXT, description TEXT, enabled BOOLEAN DEFAULT TRUE, + user_id INTEGER NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users (id) ) ''') + # 检查并添加 user_id 列(用于数据库迁移) + try: + cursor.execute("SELECT user_id FROM cards LIMIT 1") + except sqlite3.OperationalError: + # user_id 列不存在,需要添加 + logger.info("正在为 cards 表添加 user_id 列...") + cursor.execute("ALTER TABLE cards ADD COLUMN user_id INTEGER NOT NULL DEFAULT 1") + cursor.execute("CREATE INDEX IF NOT EXISTS idx_cards_user_id ON cards(user_id)") + logger.info("cards 表 user_id 列添加完成") + # 创建商品信息表 cursor.execute(''' CREATE TABLE IF NOT EXISTS item_info ( @@ -271,6 +283,21 @@ class DBManager: ) ''') + # 创建用户设置表 + cursor.execute(''' + CREATE TABLE IF NOT EXISTS user_settings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + key TEXT NOT NULL, + value TEXT NOT NULL, + description TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + UNIQUE(user_id, key) + ) + ''') + # 插入默认系统设置 cursor.execute(''' INSERT OR IGNORE INTO system_settings (key, value, description) VALUES @@ -301,6 +328,39 @@ class DBManager: # user_id列存在,更新NULL值 cursor.execute("UPDATE cookies SET user_id = ? WHERE user_id IS NULL", (admin_user_id,)) + # 为delivery_rules表添加user_id字段(如果不存在) + try: + cursor.execute("SELECT user_id FROM delivery_rules LIMIT 1") + except sqlite3.OperationalError: + # user_id列不存在,需要添加并更新历史数据 + cursor.execute("ALTER TABLE delivery_rules ADD COLUMN user_id INTEGER") + cursor.execute("UPDATE delivery_rules SET user_id = ? WHERE user_id IS NULL", (admin_user_id,)) + else: + # user_id列存在,更新NULL值 + cursor.execute("UPDATE delivery_rules SET user_id = ? WHERE user_id IS NULL", (admin_user_id,)) + + # 为notification_channels表添加user_id字段(如果不存在) + try: + cursor.execute("SELECT user_id FROM notification_channels LIMIT 1") + except sqlite3.OperationalError: + # user_id列不存在,需要添加并更新历史数据 + cursor.execute("ALTER TABLE notification_channels ADD COLUMN user_id INTEGER") + cursor.execute("UPDATE notification_channels SET user_id = ? WHERE user_id IS NULL", (admin_user_id,)) + else: + # user_id列存在,更新NULL值 + cursor.execute("UPDATE notification_channels SET user_id = ? WHERE user_id IS NULL", (admin_user_id,)) + + # 为email_verifications表添加type字段(如果不存在) + try: + cursor.execute("SELECT type FROM email_verifications LIMIT 1") + except sqlite3.OperationalError: + # type列不存在,需要添加并更新历史数据 + cursor.execute("ALTER TABLE email_verifications ADD COLUMN type TEXT DEFAULT 'register'") + cursor.execute("UPDATE email_verifications SET type = 'register' WHERE type IS NULL") + else: + # type列存在,更新NULL值 + cursor.execute("UPDATE email_verifications SET type = 'register' WHERE type IS NULL") + self.conn.commit() logger.info(f"数据库初始化成功: {self.db_path}") except Exception as e: @@ -345,7 +405,15 @@ class DBManager: (cookie_id, cookie_value, user_id) ) self.conn.commit() - logger.debug(f"Cookie保存成功: {cookie_id} (用户ID: {user_id})") + logger.info(f"Cookie保存成功: {cookie_id} (用户ID: {user_id})") + + # 验证保存结果 + cursor.execute("SELECT user_id FROM cookies WHERE id = ?", (cookie_id,)) + saved_user_id = cursor.fetchone() + if saved_user_id: + logger.info(f"Cookie保存验证: {cookie_id} 实际绑定到用户ID: {saved_user_id[0]}") + else: + logger.error(f"Cookie保存验证失败: {cookie_id} 未找到记录") return True except Exception as e: logger.error(f"Cookie保存失败: {e}") @@ -713,15 +781,15 @@ class DBManager: return False # -------------------- 通知渠道操作 -------------------- - def create_notification_channel(self, name: str, channel_type: str, config: str) -> int: + def create_notification_channel(self, name: str, channel_type: str, config: str, user_id: int = None) -> int: """创建通知渠道""" with self.lock: try: cursor = self.conn.cursor() cursor.execute(''' - INSERT INTO notification_channels (name, type, config) - VALUES (?, ?, ?) - ''', (name, channel_type, config)) + INSERT INTO notification_channels (name, type, config, user_id) + VALUES (?, ?, ?, ?) + ''', (name, channel_type, config, user_id)) self.conn.commit() channel_id = cursor.lastrowid logger.debug(f"创建通知渠道: {name} (ID: {channel_id})") @@ -731,16 +799,24 @@ class DBManager: self.conn.rollback() raise - def get_notification_channels(self) -> List[Dict[str, any]]: + def get_notification_channels(self, user_id: int = None) -> List[Dict[str, any]]: """获取所有通知渠道""" with self.lock: try: cursor = self.conn.cursor() - cursor.execute(''' - SELECT id, name, type, config, enabled, created_at, updated_at - FROM notification_channels - ORDER BY created_at DESC - ''') + if user_id is not None: + cursor.execute(''' + SELECT id, name, type, config, enabled, created_at, updated_at + FROM notification_channels + WHERE user_id = ? + ORDER BY created_at DESC + ''', (user_id,)) + else: + cursor.execute(''' + SELECT id, name, type, config, enabled, created_at, updated_at + FROM notification_channels + ORDER BY created_at DESC + ''') channels = [] for row in cursor.fetchall(): @@ -1360,7 +1436,7 @@ class DBManager: logger.error(f"验证图形验证码失败: {e}") return False - def save_verification_code(self, email: str, code: str, expires_minutes: int = 10) -> bool: + def save_verification_code(self, email: str, code: str, code_type: str = 'register', expires_minutes: int = 10) -> bool: """保存邮箱验证码""" with self.lock: try: @@ -1368,19 +1444,19 @@ class DBManager: expires_at = time.time() + (expires_minutes * 60) cursor.execute(''' - INSERT INTO email_verifications (email, code, expires_at) - VALUES (?, ?, ?) - ''', (email, code, expires_at)) + INSERT INTO email_verifications (email, code, type, expires_at) + VALUES (?, ?, ?, ?) + ''', (email, code, code_type, expires_at)) self.conn.commit() - logger.info(f"保存验证码成功: {email}") + logger.info(f"保存验证码成功: {email} ({code_type})") return True except Exception as e: logger.error(f"保存验证码失败: {e}") self.conn.rollback() return False - def verify_email_code(self, email: str, code: str) -> bool: + def verify_email_code(self, email: str, code: str, code_type: str = 'register') -> bool: """验证邮箱验证码""" with self.lock: try: @@ -1390,9 +1466,9 @@ class DBManager: # 查找有效的验证码 cursor.execute(''' SELECT id FROM email_verifications - WHERE email = ? AND code = ? AND expires_at > ? AND used = FALSE + WHERE email = ? AND code = ? AND type = ? AND expires_at > ? AND used = FALSE ORDER BY created_at DESC LIMIT 1 - ''', (email, code, current_time)) + ''', (email, code, code_type, current_time)) row = cursor.fetchone() if row: @@ -1401,10 +1477,10 @@ class DBManager: UPDATE email_verifications SET used = TRUE WHERE id = ? ''', (row[0],)) self.conn.commit() - logger.info(f"验证码验证成功: {email}") + logger.info(f"验证码验证成功: {email} ({code_type})") return True else: - logger.warning(f"验证码验证失败: {email} - {code}") + logger.warning(f"验证码验证失败: {email} - {code} ({code_type})") return False except Exception as e: logger.error(f"验证邮箱验证码失败: {e}") @@ -1414,78 +1490,52 @@ class DBManager: """发送验证码邮件""" try: subject = "闲鱼自动回复系统 - 邮箱验证码" - html_content = f""" - - - - - 邮箱验证码 - - - -
-
- -
邮箱验证码
-
+ # 使用简单的纯文本邮件内容 + text_content = f"""【闲鱼自动回复系统】邮箱验证码 -
- 您好!

- 您正在注册闲鱼自动回复系统账号,请使用以下验证码完成邮箱验证: -
+您好! -
-
{code}
-
+感谢您使用闲鱼自动回复系统。为了确保账户安全,请使用以下验证码完成邮箱验证: -
- ⚠️ 重要提醒:
- • 验证码有效期为 10 分钟
- • 请勿将验证码告诉他人
- • 如果您没有进行此操作,请忽略此邮件 -
+验证码:{code} -
- 如有任何问题,请联系系统管理员。
- 感谢您使用闲鱼自动回复系统! -
+重要提醒: +• 验证码有效期为 10 分钟,请及时使用 +• 请勿将验证码分享给任何人 +• 如非本人操作,请忽略此邮件 +• 系统不会主动索要您的验证码 - -
- - - """ +如果您在使用过程中遇到任何问题,请联系我们的技术支持团队。 +感谢您选择闲鱼自动回复系统! - # 调用邮件发送API +--- +此邮件由系统自动发送,请勿直接回复 +© 2025 闲鱼自动回复系统""" + + # 使用GET请求发送邮件 api_url = "https://dy.zhinianboke.com/api/emailSend" params = { 'subject': subject, 'receiveUser': email, - 'sendHtml': html_content + 'sendHtml': text_content } async with aiohttp.ClientSession() as session: - async with session.get(api_url, params=params) as response: - if response.status == 200: - logger.info(f"验证码邮件发送成功: {email}") - return True - else: - logger.error(f"验证码邮件发送失败: {email}, 状态码: {response.status}") - return False + try: + logger.info(f"发送验证码邮件: {email}") + async with session.get(api_url, params=params, timeout=15) as response: + response_text = await response.text() + logger.info(f"邮件API响应: {response.status}") + + if response.status == 200: + logger.info(f"验证码邮件发送成功: {email}") + return True + else: + logger.error(f"验证码邮件发送失败: {email}, 状态码: {response.status}, 响应: {response_text[:200]}") + return False + except Exception as e: + logger.error(f"邮件发送异常: {email}, 错误: {e}") + return False except Exception as e: logger.error(f"发送验证码邮件异常: {e}") @@ -1688,15 +1738,15 @@ class DBManager: # ==================== 自动发货规则方法 ==================== def create_delivery_rule(self, keyword: str, card_id: int, delivery_count: int = 1, - enabled: bool = True, description: str = None): + enabled: bool = True, description: str = None, user_id: int = None): """创建发货规则""" with self.lock: try: cursor = self.conn.cursor() cursor.execute(''' - INSERT INTO delivery_rules (keyword, card_id, delivery_count, enabled, description) - VALUES (?, ?, ?, ?, ?) - ''', (keyword, card_id, delivery_count, enabled, description)) + INSERT INTO delivery_rules (keyword, card_id, delivery_count, enabled, description, user_id) + VALUES (?, ?, ?, ?, ?, ?) + ''', (keyword, card_id, delivery_count, enabled, description, user_id)) self.conn.commit() rule_id = cursor.lastrowid logger.info(f"创建发货规则成功: {keyword} -> 卡券ID {card_id} (规则ID: {rule_id})") @@ -1705,19 +1755,30 @@ class DBManager: logger.error(f"创建发货规则失败: {e}") raise - def get_all_delivery_rules(self): + def get_all_delivery_rules(self, user_id: int = None): """获取所有发货规则""" with self.lock: try: cursor = self.conn.cursor() - cursor.execute(''' - SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, - dr.description, dr.delivery_times, dr.created_at, dr.updated_at, - c.name as card_name, c.type as card_type - FROM delivery_rules dr - LEFT JOIN cards c ON dr.card_id = c.id - ORDER BY dr.created_at DESC - ''') + if user_id is not None: + cursor.execute(''' + SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, + dr.description, dr.delivery_times, dr.created_at, dr.updated_at, + c.name as card_name, c.type as card_type + FROM delivery_rules dr + LEFT JOIN cards c ON dr.card_id = c.id + WHERE dr.user_id = ? + ORDER BY dr.created_at DESC + ''', (user_id,)) + else: + cursor.execute(''' + SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, + dr.description, dr.delivery_times, dr.created_at, dr.updated_at, + c.name as card_name, c.type as card_type + FROM delivery_rules dr + LEFT JOIN cards c ON dr.card_id = c.id + ORDER BY dr.created_at DESC + ''') rules = [] for row in cursor.fetchall(): @@ -1750,7 +1811,7 @@ class DBManager: SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, dr.description, dr.delivery_times, c.name as card_name, c.type as card_type, c.api_config, - c.text_content, c.data_content, c.enabled as card_enabled + c.text_content, c.data_content, c.enabled as card_enabled, c.description as card_description FROM delivery_rules dr LEFT JOIN cards c ON dr.card_id = c.id WHERE dr.enabled = 1 AND c.enabled = 1 @@ -1788,7 +1849,8 @@ class DBManager: 'card_api_config': api_config, 'card_text_content': row[10], 'card_data_content': row[11], - 'card_enabled': bool(row[12]) + 'card_enabled': bool(row[12]), + 'card_description': row[13] # 卡券备注信息 }) return rules diff --git a/demo_captcha_registration.py b/demo_captcha_registration.py deleted file mode 100644 index dcf2c43..0000000 --- a/demo_captcha_registration.py +++ /dev/null @@ -1,329 +0,0 @@ -#!/usr/bin/env python3 -""" -图形验证码注册流程演示 -""" - -import requests -import json -import sqlite3 -import time - -def demo_complete_registration(): - """演示完整的注册流程""" - print("🎭 图形验证码注册流程演示") - print("=" * 60) - - session_id = f"demo_session_{int(time.time())}" - test_email = "demo@example.com" - test_username = "demouser" - test_password = "demo123456" - - # 清理可能存在的测试数据 - try: - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('DELETE FROM users WHERE username = ? OR email = ?', (test_username, test_email)) - cursor.execute('DELETE FROM email_verifications WHERE email = ?', (test_email,)) - cursor.execute('DELETE FROM captcha_codes WHERE session_id = ?', (session_id,)) - conn.commit() - conn.close() - print("🧹 清理旧的测试数据") - except: - pass - - print("\n📋 注册流程步骤:") - print("1. 生成图形验证码") - print("2. 用户输入图形验证码") - print("3. 验证图形验证码") - print("4. 发送邮箱验证码") - print("5. 用户输入邮箱验证码") - print("6. 完成注册") - - # 步骤1: 生成图形验证码 - print("\n🔸 步骤1: 生成图形验证码") - response = requests.post('http://localhost:8080/generate-captcha', - json={'session_id': session_id}) - - if response.status_code != 200: - print(f"❌ 生成图形验证码失败: {response.status_code}") - return False - - result = response.json() - if not result['success']: - print(f"❌ 生成图形验证码失败: {result['message']}") - return False - - print("✅ 图形验证码生成成功") - - # 从数据库获取验证码文本(模拟用户看到图片并输入) - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id,)) - captcha_result = cursor.fetchone() - conn.close() - - if not captcha_result: - print("❌ 无法获取图形验证码") - return False - - captcha_text = captcha_result[0] - print(f"📷 图形验证码: {captcha_text}") - - # 步骤2-3: 验证图形验证码 - print("\n🔸 步骤2-3: 验证图形验证码") - response = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': session_id, - 'captcha_code': captcha_text - }) - - if response.status_code != 200: - print(f"❌ 验证图形验证码失败: {response.status_code}") - return False - - result = response.json() - if not result['success']: - print(f"❌ 图形验证码验证失败: {result['message']}") - return False - - print("✅ 图形验证码验证成功") - - # 步骤4: 发送邮箱验证码 - print("\n🔸 步骤4: 发送邮箱验证码") - response = requests.post('http://localhost:8080/send-verification-code', - json={'email': test_email}) - - if response.status_code != 200: - print(f"❌ 发送邮箱验证码失败: {response.status_code}") - return False - - result = response.json() - if not result['success']: - print(f"❌ 发送邮箱验证码失败: {result['message']}") - return False - - print("✅ 邮箱验证码发送成功") - - # 从数据库获取邮箱验证码(模拟用户收到邮件) - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM email_verifications WHERE email = ? ORDER BY created_at DESC LIMIT 1', - (test_email,)) - email_result = cursor.fetchone() - conn.close() - - if not email_result: - print("❌ 无法获取邮箱验证码") - return False - - email_code = email_result[0] - print(f"📧 邮箱验证码: {email_code}") - - # 步骤5-6: 完成注册 - print("\n🔸 步骤5-6: 完成用户注册") - response = requests.post('http://localhost:8080/register', - json={ - 'username': test_username, - 'email': test_email, - 'verification_code': email_code, - 'password': test_password - }) - - if response.status_code != 200: - print(f"❌ 用户注册失败: {response.status_code}") - return False - - result = response.json() - if not result['success']: - print(f"❌ 用户注册失败: {result['message']}") - return False - - print("✅ 用户注册成功") - - # 验证登录 - print("\n🔸 验证登录功能") - response = requests.post('http://localhost:8080/login', - json={ - 'username': test_username, - 'password': test_password - }) - - if response.status_code != 200: - print(f"❌ 用户登录失败: {response.status_code}") - return False - - result = response.json() - if not result['success']: - print(f"❌ 用户登录失败: {result['message']}") - return False - - print("✅ 用户登录成功") - print(f"🎫 Token: {result['token'][:20]}...") - print(f"👤 用户ID: {result['user_id']}") - - return True - -def demo_security_features(): - """演示安全特性""" - print("\n🔒 安全特性演示") - print("-" * 40) - - session_id = f"security_test_{int(time.time())}" - - # 1. 测试错误的图形验证码 - print("1️⃣ 测试错误的图形验证码...") - - # 先生成一个验证码 - requests.post('http://localhost:8080/generate-captcha', - json={'session_id': session_id}) - - # 尝试用错误的验证码 - response = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': session_id, - 'captcha_code': 'WRONG' - }) - - result = response.json() - if not result['success']: - print(" ✅ 错误的图形验证码被正确拒绝") - else: - print(" ❌ 错误的图形验证码验证成功(安全漏洞)") - - # 2. 测试未验证图形验证码就发送邮件 - print("\n2️⃣ 测试未验证图形验证码发送邮件...") - - # 注意:当前实现中发送邮件接口没有检查图形验证码状态 - # 这是前端控制的,后端应该也要检查 - response = requests.post('http://localhost:8080/send-verification-code', - json={'email': 'test@example.com'}) - - result = response.json() - if result['success']: - print(" ⚠️ 未验证图形验证码也能发送邮件(建议后端也要检查)") - else: - print(" ✅ 未验证图形验证码无法发送邮件") - - # 3. 测试验证码重复使用 - print("\n3️⃣ 测试验证码重复使用...") - - # 生成新的验证码 - session_id2 = f"reuse_test_{int(time.time())}" - requests.post('http://localhost:8080/generate-captcha', - json={'session_id': session_id2}) - - # 获取验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id2,)) - result = cursor.fetchone() - conn.close() - - if result: - captcha_code = result[0] - - # 第一次验证 - response1 = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': session_id2, - 'captcha_code': captcha_code - }) - - # 第二次验证(重复使用) - response2 = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': session_id2, - 'captcha_code': captcha_code - }) - - result1 = response1.json() - result2 = response2.json() - - if result1['success'] and not result2['success']: - print(" ✅ 验证码重复使用被正确阻止") - else: - print(" ❌ 验证码可以重复使用(安全漏洞)") - -def cleanup_demo_data(): - """清理演示数据""" - print("\n🧹 清理演示数据") - print("-" * 40) - - try: - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 清理测试用户 - cursor.execute('DELETE FROM users WHERE username LIKE "demo%" OR email LIKE "demo%"') - user_count = cursor.rowcount - - # 清理测试验证码 - cursor.execute('DELETE FROM email_verifications WHERE email LIKE "demo%"') - email_count = cursor.rowcount - - # 清理测试图形验证码 - cursor.execute('DELETE FROM captcha_codes WHERE session_id LIKE "demo%" OR session_id LIKE "security%" OR session_id LIKE "reuse%"') - captcha_count = cursor.rowcount - - conn.commit() - conn.close() - - print(f"✅ 清理完成:") - print(f" • 用户: {user_count} 条") - print(f" • 邮箱验证码: {email_count} 条") - print(f" • 图形验证码: {captcha_count} 条") - - except Exception as e: - print(f"❌ 清理失败: {e}") - -def main(): - """主演示函数""" - print("🎪 图形验证码系统完整演示") - print("=" * 60) - - try: - # 演示完整注册流程 - success = demo_complete_registration() - - if success: - print("\n🎉 完整注册流程演示成功!") - else: - print("\n💥 注册流程演示失败!") - return False - - # 演示安全特性 - demo_security_features() - - # 清理演示数据 - cleanup_demo_data() - - print("\n" + "=" * 60) - print("🎊 图形验证码系统演示完成!") - - print("\n📋 功能总结:") - print("✅ 图形验证码生成和验证") - print("✅ 邮箱验证码发送") - print("✅ 用户注册流程") - print("✅ 用户登录验证") - print("✅ 安全特性保护") - - print("\n🌐 使用方法:") - print("1. 访问: http://localhost:8080/register.html") - print("2. 查看图形验证码并输入") - print("3. 输入邮箱地址") - print("4. 点击发送验证码(需要先验证图形验证码)") - print("5. 输入邮箱验证码") - print("6. 设置密码并完成注册") - - return True - - except Exception as e: - print(f"\n❌ 演示失败: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/deploy.bat b/deploy.bat deleted file mode 100644 index c10fd9d..0000000 --- a/deploy.bat +++ /dev/null @@ -1,298 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -:: 闲鱼自动回复系统 Docker 部署脚本 (Windows版本) -:: 作者: Xianyu Auto Reply System -:: 版本: 1.0.0 - -title 闲鱼自动回复系统 Docker 部署 - -:: 颜色定义 -set "RED=[91m" -set "GREEN=[92m" -set "YELLOW=[93m" -set "BLUE=[94m" -set "NC=[0m" - -:: 打印带颜色的消息 -:print_info -echo %BLUE%[INFO]%NC% %~1 -goto :eof - -:print_success -echo %GREEN%[SUCCESS]%NC% %~1 -goto :eof - -:print_warning -echo %YELLOW%[WARNING]%NC% %~1 -goto :eof - -:print_error -echo %RED%[ERROR]%NC% %~1 -goto :eof - -:: 检查Docker是否安装 -:check_docker -call :print_info "检查 Docker 环境..." - -docker --version >nul 2>&1 -if errorlevel 1 ( - call :print_error "Docker 未安装,请先安装 Docker Desktop" - echo. - echo 下载地址: https://www.docker.com/products/docker-desktop - pause - exit /b 1 -) - -docker-compose --version >nul 2>&1 -if errorlevel 1 ( - call :print_error "Docker Compose 未安装,请先安装 Docker Compose" - pause - exit /b 1 -) - -call :print_success "Docker 环境检查通过" -goto :eof - -:: 创建必要的目录 -:create_directories -call :print_info "创建必要的目录..." - -if not exist "data" mkdir data -if not exist "logs" mkdir logs -if not exist "backups" mkdir backups -if not exist "nginx" mkdir nginx -if not exist "nginx\ssl" mkdir nginx\ssl - -REM 检查目录是否创建成功 -if not exist "data" ( - call :print_error "data目录创建失败" - pause - exit /b 1 -) - -if not exist "logs" ( - call :print_error "logs目录创建失败" - pause - exit /b 1 -) - -call :print_success "目录创建完成" -goto :eof - -:: 生成默认配置文件 -:generate_config -REM 生成.env文件 -if not exist ".env" ( - if exist ".env.example" ( - call :print_info "从模板生成 .env 文件..." - copy ".env.example" ".env" >nul - call :print_success ".env 文件已生成" - ) else ( - call :print_warning ".env.example 文件不存在,跳过 .env 文件生成" - ) -) else ( - call :print_info ".env 文件已存在,跳过生成" -) - -REM 生成global_config.yml文件 -if exist "global_config.yml" ( - call :print_info "配置文件已存在,跳过生成" - goto :eof -) - -call :print_info "生成默认配置文件..." - -( -echo # 闲鱼自动回复系统配置文件 -echo API_ENDPOINTS: -echo login_check: https://passport.goofish.com/newlogin/hasLogin.do -echo message_headinfo: https://h5api.m.goofish.com/h5/mtop.idle.trade.pc.message.headinfo/1.0/ -echo token: https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/ -echo. -echo APP_CONFIG: -echo api_version: '1.0' -echo app_key: 444e9908a51d1cb236a27862abc769c9 -echo app_version: '1.0' -echo platform: web -echo. -echo AUTO_REPLY: -echo enabled: true -echo default_message: '亲爱的"{send_user_name}" 老板你好!所有宝贝都可以拍,秒发货的哈~不满意的话可以直接申请退款哈~' -echo max_retry: 3 -echo retry_interval: 5 -echo api: -echo enabled: false -echo host: 0.0.0.0 # 绑定所有网络接口,支持IP访问 -echo port: 8080 # Web服务端口 -echo url: http://0.0.0.0:8080/xianyu/reply -echo timeout: 10 -echo. -echo COOKIES: -echo last_update_time: '' -echo value: '' -echo. -echo DEFAULT_HEADERS: -echo accept: application/json -echo accept-language: zh-CN,zh;q=0.9 -echo cache-control: no-cache -echo origin: https://www.goofish.com -echo pragma: no-cache -echo referer: https://www.goofish.com/ -echo user-agent: Mozilla/5.0 ^(Windows NT 10.0; Win64; x64^) AppleWebKit/537.36 ^(KHTML, like Gecko^) Chrome/119.0.0.0 Safari/537.36 -echo. -echo WEBSOCKET_URL: wss://wss-goofish.dingtalk.com/ -echo HEARTBEAT_INTERVAL: 15 -echo HEARTBEAT_TIMEOUT: 5 -echo TOKEN_REFRESH_INTERVAL: 3600 -echo TOKEN_RETRY_INTERVAL: 300 -echo MESSAGE_EXPIRE_TIME: 300000 -echo. -echo LOG_CONFIG: -echo level: INFO -echo format: '{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {name}:{function}:{line} - {message}' -echo rotation: '1 day' -echo retention: '7 days' -) > global_config.yml - -call :print_success "默认配置文件已生成" -goto :eof - -:: 构建Docker镜像 -:build_image -call :print_info "构建 Docker 镜像..." - -docker build -t xianyu-auto-reply:latest . -if errorlevel 1 ( - call :print_error "Docker 镜像构建失败" - pause - exit /b 1 -) - -call :print_success "Docker 镜像构建完成" -goto :eof - -:: 启动服务 -:start_services -call :print_info "启动服务..." - -if "%~1"=="--with-nginx" ( - call :print_info "启动服务(包含 Nginx)..." - docker-compose --profile with-nginx up -d -) else ( - call :print_info "启动服务(不包含 Nginx)..." - docker-compose up -d -) - -if errorlevel 1 ( - call :print_error "服务启动失败" - pause - exit /b 1 -) - -call :print_success "服务启动完成" -goto :eof - -:: 显示服务状态 -:show_status -call :print_info "服务状态:" -docker-compose ps - -echo. -call :print_info "服务日志(最近10行):" -docker-compose logs --tail=10 -goto :eof - -:: 显示访问信息 -:show_access_info -call :print_success "部署完成!" -echo. -call :print_info "访问信息:" -echo Web界面: http://localhost:8080 -echo 默认账号: admin -echo 默认密码: admin123 -echo. -call :print_info "常用命令:" -echo 查看日志: docker-compose logs -f -echo 重启服务: docker-compose restart -echo 停止服务: docker-compose down -echo 更新服务: deploy.bat update -echo. -call :print_info "数据目录:" -echo 数据库: .\data\xianyu_data.db -echo 日志: .\logs\ -echo 配置: .\global_config.yml -echo. -goto :eof - -:: 更新服务 -:update_services -call :print_info "更新服务..." - -docker-compose down -call :build_image -call :start_services %~1 - -call :print_success "服务更新完成" -goto :eof - -:: 清理资源 -:cleanup -call :print_warning "清理 Docker 资源..." - -docker-compose down --volumes --remove-orphans -docker rmi xianyu-auto-reply:latest 2>nul - -call :print_success "清理完成" -goto :eof - -:: 显示帮助 -:show_help -echo 使用方法: -echo %~nx0 # 首次部署 -echo %~nx0 with-nginx # 部署并启动 Nginx -echo %~nx0 update # 更新服务 -echo %~nx0 update with-nginx # 更新服务并启动 Nginx -echo %~nx0 status # 查看服务状态 -echo %~nx0 cleanup # 清理所有资源 -echo %~nx0 help # 显示帮助 -goto :eof - -:: 主函数 -:main -echo ======================================== -echo 闲鱼自动回复系统 Docker 部署脚本 -echo ======================================== -echo. - -if "%~1"=="update" ( - call :print_info "更新模式" - call :check_docker - call :update_services %~2 - call :show_status - call :show_access_info -) else if "%~1"=="cleanup" ( - call :print_warning "清理模式" - call :cleanup -) else if "%~1"=="status" ( - call :show_status -) else if "%~1"=="help" ( - call :show_help -) else ( - call :print_info "首次部署模式" - call :check_docker - call :create_directories - call :generate_config - call :build_image - call :start_services %~1 - call :show_status - call :show_access_info -) - -echo. -pause -goto :eof - -:: 执行主函数 -call :main %* diff --git a/deploy.sh b/deploy.sh deleted file mode 100644 index 75f3d0b..0000000 --- a/deploy.sh +++ /dev/null @@ -1,288 +0,0 @@ -#!/bin/bash - -# 闲鱼自动回复系统 Docker 部署脚本 -# 作者: Xianyu Auto Reply System -# 版本: 1.0.0 - -set -e - -# 颜色定义 -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# 打印带颜色的消息 -print_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -print_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -print_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -# 检查Docker是否安装 -check_docker() { - 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 "Docker 环境检查通过" -} - -# 创建必要的目录 -create_directories() { - print_info "创建必要的目录..." - - # 创建目录 - mkdir -p data - mkdir -p logs - mkdir -p backups - mkdir -p nginx/ssl - - # 设置权限 (确保Docker容器可以写入) - chmod 755 data logs backups - - # 检查权限 - if [ ! -w "data" ]; then - print_error "data目录没有写权限" - exit 1 - fi - - if [ ! -w "logs" ]; then - print_error "logs目录没有写权限" - exit 1 - fi - - print_success "目录创建完成" -} - -# 生成默认配置文件 -generate_config() { - # 生成.env文件 - if [ ! -f ".env" ]; then - if [ -f ".env.example" ]; then - print_info "从模板生成 .env 文件..." - cp .env.example .env - print_success ".env 文件已生成" - else - print_warning ".env.example 文件不存在,跳过 .env 文件生成" - fi - else - print_info ".env 文件已存在,跳过生成" - fi - - # 生成global_config.yml文件 - if [ ! -f "global_config.yml" ]; then - print_info "生成默认配置文件..." - - cat > global_config.yml << EOF -# 闲鱼自动回复系统配置文件 -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: - enabled: true - default_message: '亲爱的"{send_user_name}" 老板你好!所有宝贝都可以拍,秒发货的哈~不满意的话可以直接申请退款哈~' - max_retry: 3 - retry_interval: 5 - api: - enabled: false - host: 0.0.0.0 # 绑定所有网络接口,支持IP访问 - port: 8080 # Web服务端口 - url: http://0.0.0.0:8080/xianyu/reply - timeout: 10 - -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 - referer: https://www.goofish.com/ - sec-ch-ua: '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"' - 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/119.0.0.0 Safari/537.36 - -WEBSOCKET_URL: wss://wss-goofish.dingtalk.com/ -HEARTBEAT_INTERVAL: 15 -HEARTBEAT_TIMEOUT: 5 -TOKEN_REFRESH_INTERVAL: 3600 -TOKEN_RETRY_INTERVAL: 300 -MESSAGE_EXPIRE_TIME: 300000 - -LOG_CONFIG: - level: INFO - format: '{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {name}:{function}:{line} - {message}' - rotation: '1 day' - retention: '7 days' -EOF - - print_success "默认配置文件已生成" - else - print_info "配置文件已存在,跳过生成" - fi -} - -# 构建Docker镜像 -build_image() { - print_info "构建 Docker 镜像..." - - docker build -t xianyu-auto-reply:latest . - - print_success "Docker 镜像构建完成" -} - -# 启动服务 -start_services() { - print_info "启动服务..." - - # 检查是否需要启动 Nginx - if [ "$1" = "--with-nginx" ]; then - print_info "启动服务(包含 Nginx)..." - docker-compose --profile with-nginx up -d - else - print_info "启动服务(不包含 Nginx)..." - docker-compose up -d - fi - - print_success "服务启动完成" -} - -# 显示服务状态 -show_status() { - print_info "服务状态:" - docker-compose ps - - print_info "服务日志(最近10行):" - docker-compose logs --tail=10 -} - -# 显示访问信息 -show_access_info() { - print_success "部署完成!" - echo "" - print_info "访问信息:" - echo " Web界面: http://localhost:8080" - echo " 默认账号: admin" - echo " 默认密码: admin123" - echo "" - print_info "常用命令:" - echo " 查看日志: docker-compose logs -f" - echo " 重启服务: docker-compose restart" - echo " 停止服务: docker-compose down" - echo " 更新服务: ./deploy.sh --update" - echo "" - print_info "数据目录:" - echo " 数据库: ./data/xianyu_data.db" - echo " 日志: ./logs/" - echo " 配置: ./global_config.yml" -} - -# 更新服务 -update_services() { - print_info "更新服务..." - - # 停止服务 - docker-compose down - - # 重新构建镜像 - build_image - - # 启动服务 - start_services $1 - - print_success "服务更新完成" -} - -# 清理资源 -cleanup() { - print_warning "清理 Docker 资源..." - - # 停止并删除容器 - docker-compose down --volumes --remove-orphans - - # 删除镜像 - docker rmi xianyu-auto-reply:latest 2>/dev/null || true - - print_success "清理完成" -} - -# 主函数 -main() { - echo "========================================" - echo " 闲鱼自动回复系统 Docker 部署脚本" - echo "========================================" - echo "" - - case "$1" in - --update) - print_info "更新模式" - check_docker - update_services $2 - show_status - show_access_info - ;; - --cleanup) - print_warning "清理模式" - cleanup - ;; - --status) - show_status - ;; - --help) - echo "使用方法:" - echo " $0 # 首次部署" - echo " $0 --with-nginx # 部署并启动 Nginx" - echo " $0 --update # 更新服务" - echo " $0 --update --with-nginx # 更新服务并启动 Nginx" - echo " $0 --status # 查看服务状态" - echo " $0 --cleanup # 清理所有资源" - echo " $0 --help # 显示帮助" - ;; - *) - print_info "首次部署模式" - check_docker - create_directories - generate_config - build_image - start_services $1 - show_status - show_access_info - ;; - esac -} - -# 执行主函数 -main "$@" diff --git a/docker-deploy.bat b/docker-deploy.bat deleted file mode 100644 index 671acb9..0000000 --- a/docker-deploy.bat +++ /dev/null @@ -1,301 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -:: 闲鱼自动回复系统 Docker 部署脚本 (Windows版本) -:: 支持快速部署和管理 - -set PROJECT_NAME=xianyu-auto-reply -set COMPOSE_FILE=docker-compose.yml -set ENV_FILE=.env - -:: 颜色定义 (Windows 10+ 支持ANSI颜色) -set "RED=[31m" -set "GREEN=[32m" -set "YELLOW=[33m" -set "BLUE=[34m" -set "NC=[0m" - -:: 打印带颜色的消息 -:print_info -echo %BLUE%ℹ️ %~1%NC% -goto :eof - -:print_success -echo %GREEN%✅ %~1%NC% -goto :eof - -:print_warning -echo %YELLOW%⚠️ %~1%NC% -goto :eof - -:print_error -echo %RED%❌ %~1%NC% -goto :eof - -:: 检查依赖 -:check_dependencies -call :print_info "检查系统依赖..." - -docker --version >nul 2>&1 -if errorlevel 1 ( - call :print_error "Docker 未安装,请先安装 Docker Desktop" - exit /b 1 -) - -docker-compose --version >nul 2>&1 -if errorlevel 1 ( - call :print_error "Docker Compose 未安装,请先安装 Docker Compose" - exit /b 1 -) - -call :print_success "系统依赖检查通过" -goto :eof - -:: 初始化配置 -:init_config -call :print_info "初始化配置文件..." - -if not exist "%ENV_FILE%" ( - if exist ".env.example" ( - copy ".env.example" "%ENV_FILE%" >nul - call :print_success "已创建 %ENV_FILE% 配置文件" - ) else ( - call :print_error ".env.example 文件不存在" - exit /b 1 - ) -) else ( - call :print_warning "%ENV_FILE% 已存在,跳过创建" -) - -:: 创建必要的目录 -if not exist "data" mkdir data -if not exist "logs" mkdir logs -if not exist "backups" mkdir backups -call :print_success "已创建必要的目录" -goto :eof - -:: 构建镜像 -:build_image -call :print_info "构建 Docker 镜像..." -docker-compose build --no-cache -if errorlevel 1 ( - call :print_error "镜像构建失败" - exit /b 1 -) -call :print_success "镜像构建完成" -goto :eof - -:: 启动服务 -:start_services -set "profile=" -if "%~1"=="with-nginx" ( - set "profile=--profile with-nginx" - call :print_info "启动服务(包含 Nginx)..." -) else ( - call :print_info "启动基础服务..." -) - -docker-compose %profile% up -d -if errorlevel 1 ( - call :print_error "服务启动失败" - exit /b 1 -) -call :print_success "服务启动完成" - -:: 等待服务就绪 -call :print_info "等待服务就绪..." -timeout /t 10 /nobreak >nul - -:: 检查服务状态 -docker-compose ps | findstr "Up" >nul -if errorlevel 1 ( - call :print_error "服务启动失败" - docker-compose logs - exit /b 1 -) else ( - call :print_success "服务运行正常" - call :show_access_info "%~1" -) -goto :eof - -:: 停止服务 -:stop_services -call :print_info "停止服务..." -docker-compose down -call :print_success "服务已停止" -goto :eof - -:: 重启服务 -:restart_services -call :print_info "重启服务..." -docker-compose restart -call :print_success "服务已重启" -goto :eof - -:: 查看日志 -:show_logs -if "%~1"=="" ( - docker-compose logs -f -) else ( - docker-compose logs -f "%~1" -) -goto :eof - -:: 查看状态 -:show_status -call :print_info "服务状态:" -docker-compose ps - -call :print_info "资源使用:" -for /f "tokens=*" %%i in ('docker-compose ps -q') do ( - docker stats --no-stream %%i -) -goto :eof - -:: 显示访问信息 -:show_access_info -echo. -call :print_success "🎉 部署完成!" -echo. - -if "%~1"=="with-nginx" ( - echo 📱 访问地址: - echo HTTP: http://localhost - echo HTTPS: https://localhost ^(如果配置了SSL^) -) else ( - 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 - -:: 健康检查 -:health_check -call :print_info "执行健康检查..." - -set "url=http://localhost:8080/health" -set "max_attempts=30" -set "attempt=1" - -:health_loop -curl -f -s "%url%" >nul 2>&1 -if not errorlevel 1 ( - call :print_success "健康检查通过" - goto :eof -) - -call :print_info "等待服务就绪... (!attempt!/%max_attempts%)" -timeout /t 2 /nobreak >nul -set /a attempt+=1 - -if !attempt! leq %max_attempts% goto health_loop - -call :print_error "健康检查失败" -exit /b 1 - -:: 备份数据 -:backup_data -call :print_info "备份数据..." - -for /f "tokens=2 delims==" %%i in ('wmic OS Get localdatetime /value') do set datetime=%%i -set backup_dir=backups\%datetime:~0,8%_%datetime:~8,6% -mkdir "%backup_dir%" 2>nul - -:: 备份数据库 -if exist "data\xianyu_data.db" ( - copy "data\xianyu_data.db" "%backup_dir%\" >nul - call :print_success "数据库备份完成" -) - -:: 备份配置 -copy "%ENV_FILE%" "%backup_dir%\" >nul -copy "global_config.yml" "%backup_dir%\" >nul 2>&1 - -call :print_success "数据备份完成: %backup_dir%" -goto :eof - -:: 显示帮助信息 -:show_help -echo 闲鱼自动回复系统 Docker 部署脚本 ^(Windows版本^) -echo. -echo 用法: %~nx0 [命令] [选项] -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 help 显示帮助信息 -echo. -echo 示例: -echo %~nx0 init # 初始化配置 -echo %~nx0 start # 启动基础服务 -echo %~nx0 start with-nginx # 启动包含 Nginx 的服务 -echo %~nx0 logs xianyu-app # 查看应用日志 -echo. -goto :eof - -:: 主函数 -:main -if "%~1"=="init" ( - call :check_dependencies - call :init_config -) else if "%~1"=="build" ( - call :check_dependencies - call :build_image -) else if "%~1"=="start" ( - call :check_dependencies - call :init_config - call :build_image - call :start_services "%~2" -) else if "%~1"=="stop" ( - call :stop_services -) else if "%~1"=="restart" ( - call :restart_services -) else if "%~1"=="status" ( - call :show_status -) else if "%~1"=="logs" ( - call :show_logs "%~2" -) else if "%~1"=="health" ( - call :health_check -) else if "%~1"=="backup" ( - call :backup_data -) else if "%~1"=="help" ( - call :show_help -) else if "%~1"=="-h" ( - call :show_help -) else if "%~1"=="--help" ( - call :show_help -) else if "%~1"=="" ( - call :print_info "快速部署模式" - call :check_dependencies - call :init_config - call :build_image - call :start_services -) else ( - call :print_error "未知命令: %~1" - call :show_help - exit /b 1 -) - -goto :eof - -:: 执行主函数 -call :main %* diff --git a/docker_deployment_update.md b/docker_deployment_update.md deleted file mode 100644 index b68877b..0000000 --- a/docker_deployment_update.md +++ /dev/null @@ -1,207 +0,0 @@ -# Docker部署更新检查报告 - -## 📋 检查概述 - -对Docker部署配置进行了全面检查,评估是否需要更新以支持新增的AI回复功能和其他改进。 - -## ✅ 当前状态评估 - -### 🎯 **结论:Docker部署配置已经完善,无需重大更新** - -所有新增功能都已经在现有的Docker配置中得到支持。 - -## 📊 详细检查结果 - -### 1. **依赖包检查** ✅ -#### requirements.txt 状态:**完整** -``` -✅ openai>=1.65.5 # AI回复功能 -✅ python-dotenv>=1.0.1 # 环境变量支持 -✅ python-multipart>=0.0.6 # 文件上传支持 -✅ fastapi>=0.111 # Web框架 -✅ uvicorn[standard]>=0.29 # ASGI服务器 -✅ 其他所有必要依赖 -``` - -### 2. **环境变量配置** ✅ -#### .env.example 状态:**完整** -``` -✅ AI_REPLY_ENABLED=false -✅ DEFAULT_AI_MODEL=qwen-plus -✅ DEFAULT_AI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 -✅ AI_REQUEST_TIMEOUT=30 -✅ AI_MAX_TOKENS=100 -✅ 所有基础配置变量 -``` - -### 3. **Docker Compose配置** ✅ -#### docker-compose.yml 状态:**完整** -``` -✅ AI回复相关环境变量映射 -✅ 数据持久化配置 (/app/data, /app/logs, /app/backups) -✅ 健康检查配置 -✅ 资源限制配置 -✅ 网络配置 -✅ Nginx反向代理支持 -``` - -### 4. **Dockerfile配置** ✅ -#### Dockerfile 状态:**完整** -``` -✅ Python 3.11基础镜像 -✅ 所有系统依赖安装 -✅ 应用依赖安装 -✅ 工作目录配置 -✅ 端口暴露配置 -✅ 启动命令配置 -``` - -### 5. **数据持久化** ✅ -#### 挂载点配置:**完整** -``` -✅ ./data:/app/data:rw # 数据库文件 -✅ ./logs:/app/logs:rw # 日志文件 -✅ ./backups:/app/backups:rw # 备份文件 -✅ ./global_config.yml:/app/global_config.yml:ro # 配置文件 -``` - -### 6. **健康检查** ✅ -#### 健康检查配置:**完整** -``` -✅ HTTP健康检查端点 (/health) -✅ 检查间隔:30秒 -✅ 超时时间:10秒 -✅ 重试次数:3次 -✅ 启动等待:40秒 -``` - -## 🔍 新功能支持验证 - -### AI回复功能 ✅ -- **依赖支持**:openai库已包含 -- **配置支持**:所有AI相关环境变量已配置 -- **数据支持**:AI数据表会自动创建 -- **API支持**:FastAPI框架支持所有新接口 - -### 备份功能增强 ✅ -- **存储支持**:备份目录已挂载 -- **数据支持**:所有新表都包含在备份中 -- **权限支持**:容器有读写权限 - -### 商品管理功能 ✅ -- **文件上传**:python-multipart依赖已包含 -- **数据存储**:数据库挂载支持新表 -- **API支持**:FastAPI支持文件上传接口 - -## 💡 可选优化建议 - -虽然当前配置已经完善,但可以考虑以下优化: - -### 1. **添加AI服务健康检查** -```yaml -# 可选:添加AI服务连通性检查 -healthcheck: - test: ["CMD", "python", "-c", "import requests; requests.get('http://localhost:8080/api/ai/health', timeout=5)"] -``` - -### 2. **添加更多监控指标** -```yaml -# 可选:添加Prometheus监控 -environment: - - ENABLE_METRICS=true - - METRICS_PORT=9090 -``` - -### 3. **添加AI配置验证** -```yaml -# 可选:启动时验证AI配置 -environment: - - VALIDATE_AI_CONFIG=true -``` - -## 🚀 部署建议 - -### 生产环境部署 -1. **使用强密码** - ```bash - ADMIN_PASSWORD=$(openssl rand -base64 32) - JWT_SECRET_KEY=$(openssl rand -base64 32) - ``` - -2. **配置AI服务** - ```bash - AI_REPLY_ENABLED=true - # 配置真实的API密钥 - ``` - -3. **启用HTTPS** - ```bash - docker-compose --profile with-nginx up -d - ``` - -4. **配置资源限制** - ```bash - MEMORY_LIMIT=1024 # 如果使用AI功能,建议增加内存 - CPU_LIMIT=1.0 - ``` - -### 开发环境部署 -```bash -# 克隆项目 -git clone -cd xianyuapis - -# 复制环境变量 -cp .env.example .env - -# 启动服务 -docker-compose up -d - -# 查看日志 -docker-compose logs -f -``` - -## 📋 部署检查清单 - -### 部署前检查 ✅ -- [x] Docker和Docker Compose已安装 -- [x] 端口8080未被占用 -- [x] 有足够的磁盘空间(建议>2GB) -- [x] 网络连接正常 - -### 配置检查 ✅ -- [x] .env文件已配置 -- [x] global_config.yml文件存在 -- [x] data、logs、backups目录权限正确 -- [x] AI API密钥已配置(如果使用AI功能) - -### 功能验证 ✅ -- [x] Web界面可访问 -- [x] 账号管理功能正常 -- [x] 自动回复功能正常 -- [x] AI回复功能正常(如果启用) -- [x] 备份功能正常 - -## 🎉 总结 - -### ✅ **Docker部署配置完全就绪** - -1. **无需更新**:当前配置已支持所有新功能 -2. **开箱即用**:可直接部署使用 -3. **功能完整**:支持AI回复、备份、商品管理等所有功能 -4. **生产就绪**:包含安全、监控、资源限制等配置 - -### 🚀 **立即可用的部署命令** - -```bash -# 快速部署 -git clone -cd xianyuapis -cp .env.example .env -docker-compose up -d - -# 访问系统 -open http://localhost:8080 -``` - -**Docker部署配置已经完善,支持所有新功能,可以直接使用!** 🎉 diff --git a/fix-db-permissions.bat b/fix-db-permissions.bat deleted file mode 100644 index fdcb358..0000000 --- a/fix-db-permissions.bat +++ /dev/null @@ -1,156 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -:: 修复数据库权限问题的脚本 (Windows版本) -:: 解决Docker容器中数据库无法创建的问题 - -title 数据库权限修复脚本 - -:: 颜色定义 -set "RED=[91m" -set "GREEN=[92m" -set "YELLOW=[93m" -set "BLUE=[94m" -set "NC=[0m" - -:: 打印带颜色的消息 -:print_info -echo %BLUE%[INFO]%NC% %~1 -goto :eof - -:print_success -echo %GREEN%[SUCCESS]%NC% %~1 -goto :eof - -:print_warning -echo %YELLOW%[WARNING]%NC% %~1 -goto :eof - -:print_error -echo %RED%[ERROR]%NC% %~1 -goto :eof - -echo ======================================== -echo 数据库权限修复脚本 -echo ======================================== -echo. - -:: 1. 停止现有容器 -call :print_info "停止现有容器..." -docker-compose down >nul 2>&1 - -:: 2. 检查并创建目录 -call :print_info "检查并创建必要目录..." - -for %%d in (data logs backups) do ( - if not exist "%%d" ( - call :print_info "创建目录: %%d" - mkdir "%%d" - ) - - if not exist "%%d" ( - call :print_error "目录 %%d 创建失败" - pause - exit /b 1 - ) - - call :print_success "目录 %%d 权限正常" -) - -:: 3. 检查现有数据库文件 -if exist "data\xianyu_data.db" ( - call :print_info "检查现有数据库文件..." - call :print_success "数据库文件存在" -) else ( - call :print_info "数据库文件不存在,将在启动时创建" -) - -:: 4. 测试数据库创建 -call :print_info "测试数据库创建..." -python -c " -import sqlite3 -import os - -db_path = 'data/test_db.sqlite' -try: - conn = sqlite3.connect(db_path) - conn.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY)') - conn.commit() - conn.close() - print('✅ 数据库创建测试成功') - if os.path.exists(db_path): - os.remove(db_path) -except Exception as e: - print(f'❌ 数据库创建测试失败: {e}') - exit(1) -" - -if !errorlevel! neq 0 ( - call :print_error "数据库创建测试失败" - pause - exit /b 1 -) - -:: 5. 重新构建并启动 -call :print_info "重新构建并启动服务..." -docker-compose build --no-cache -if !errorlevel! neq 0 ( - call :print_error "Docker镜像构建失败" - pause - exit /b 1 -) - -docker-compose up -d -if !errorlevel! neq 0 ( - call :print_error "服务启动失败" - pause - exit /b 1 -) - -:: 6. 等待服务启动 -call :print_info "等待服务启动..." -timeout /t 15 /nobreak >nul - -:: 7. 检查服务状态 -call :print_info "检查服务状态..." -docker-compose ps | findstr "Up" >nul -if !errorlevel! equ 0 ( - call :print_success "服务启动成功" - - :: 检查日志 - call :print_info "检查启动日志..." - docker-compose logs --tail=20 xianyu-app - - :: 测试健康检查 - call :print_info "测试健康检查..." - timeout /t 5 /nobreak >nul - curl -f http://localhost:8080/health >nul 2>&1 - if !errorlevel! equ 0 ( - call :print_success "健康检查通过" - ) else ( - call :print_warning "健康检查失败,但服务可能仍在启动中" - ) -) else ( - call :print_error "服务启动失败" - call :print_info "查看错误日志:" - docker-compose logs xianyu-app - pause - exit /b 1 -) - -echo. -call :print_success "数据库权限修复完成!" -echo. -call :print_info "服务信息:" -echo Web界面: http://localhost:8080 -echo 健康检查: http://localhost:8080/health -echo 默认账号: admin / admin123 -echo. -call :print_info "常用命令:" -echo 查看日志: docker-compose logs -f -echo 重启服务: docker-compose restart -echo 停止服务: docker-compose down -echo. - -pause diff --git a/fix-db-permissions.sh b/fix-db-permissions.sh deleted file mode 100644 index e6ea4ff..0000000 --- a/fix-db-permissions.sh +++ /dev/null @@ -1,167 +0,0 @@ -#!/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 - -print_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -print_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -print_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -echo "========================================" -echo " 数据库权限修复脚本" -echo "========================================" -echo "" - -# 1. 停止现有容器 -print_info "停止现有容器..." -docker-compose down 2>/dev/null || true - -# 2. 检查并创建目录 -print_info "检查并创建必要目录..." -for dir in data logs backups; do - if [ ! -d "$dir" ]; then - print_info "创建目录: $dir" - mkdir -p "$dir" - fi - - # 设置权限 - chmod 755 "$dir" - - # 检查权限 - if [ ! -w "$dir" ]; then - print_error "目录 $dir 没有写权限" - - # 尝试修复权限 - print_info "尝试修复权限..." - sudo chmod 755 "$dir" 2>/dev/null || { - print_error "无法修复权限,请手动执行: sudo chmod 755 $dir" - exit 1 - } - fi - - print_success "目录 $dir 权限正常" -done - -# 3. 检查现有数据库文件 -if [ -f "data/xianyu_data.db" ]; then - print_info "检查现有数据库文件权限..." - if [ ! -w "data/xianyu_data.db" ]; then - print_warning "数据库文件没有写权限,尝试修复..." - chmod 644 "data/xianyu_data.db" - print_success "数据库文件权限已修复" - else - print_success "数据库文件权限正常" - fi -fi - -# 4. 检查Docker用户映射 -print_info "检查Docker用户映射..." -CURRENT_UID=$(id -u) -CURRENT_GID=$(id -g) - -print_info "当前用户 UID:GID = $CURRENT_UID:$CURRENT_GID" - -# 5. 创建测试数据库 -print_info "测试数据库创建..." -python3 -c " -import sqlite3 -import os - -db_path = 'data/test_db.sqlite' -try: - conn = sqlite3.connect(db_path) - conn.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY)') - conn.commit() - conn.close() - print('✅ 数据库创建测试成功') - os.remove(db_path) -except Exception as e: - print(f'❌ 数据库创建测试失败: {e}') - exit(1) -" || { - print_error "数据库创建测试失败" - exit 1 -} - -# 6. 更新docker-compose.yml用户映射 -print_info "检查docker-compose.yml用户映射..." -if ! grep -q "user:" docker-compose.yml; then - print_info "添加用户映射到docker-compose.yml..." - - # 备份原文件 - cp docker-compose.yml docker-compose.yml.backup - - # 在xianyu-app服务中添加user配置 - sed -i '/container_name: xianyu-auto-reply/a\ user: "'$CURRENT_UID':'$CURRENT_GID'"' docker-compose.yml - - print_success "用户映射已添加" -else - print_info "用户映射已存在" -fi - -# 7. 重新构建并启动 -print_info "重新构建并启动服务..." -docker-compose build --no-cache -docker-compose up -d - -# 8. 等待服务启动 -print_info "等待服务启动..." -sleep 10 - -# 9. 检查服务状态 -print_info "检查服务状态..." -if docker-compose ps | grep -q "Up"; then - print_success "服务启动成功" - - # 检查日志 - print_info "检查启动日志..." - docker-compose logs --tail=20 xianyu-app - - # 测试健康检查 - print_info "测试健康检查..." - sleep 5 - if curl -f http://localhost:8080/health >/dev/null 2>&1; then - print_success "健康检查通过" - else - print_warning "健康检查失败,但服务可能仍在启动中" - fi -else - print_error "服务启动失败" - print_info "查看错误日志:" - docker-compose logs xianyu-app - exit 1 -fi - -echo "" -print_success "数据库权限修复完成!" -echo "" -print_info "服务信息:" -echo " Web界面: http://localhost:8080" -echo " 健康检查: http://localhost:8080/health" -echo " 默认账号: admin / admin123" -echo "" -print_info "常用命令:" -echo " 查看日志: docker-compose logs -f" -echo " 重启服务: docker-compose restart" -echo " 停止服务: docker-compose down" diff --git a/fix-docker-warnings.bat b/fix-docker-warnings.bat deleted file mode 100644 index 6810784..0000000 --- a/fix-docker-warnings.bat +++ /dev/null @@ -1,144 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -:: 修复Docker部署警告的快速脚本 (Windows版本) -:: 解决version过时和.env文件缺失问题 - -title Docker部署警告修复脚本 - -:: 颜色定义 -set "RED=[91m" -set "GREEN=[92m" -set "YELLOW=[93m" -set "BLUE=[94m" -set "NC=[0m" - -:: 打印带颜色的消息 -:print_info -echo %BLUE%[INFO]%NC% %~1 -goto :eof - -:print_success -echo %GREEN%[SUCCESS]%NC% %~1 -goto :eof - -:print_warning -echo %YELLOW%[WARNING]%NC% %~1 -goto :eof - -:print_error -echo %RED%[ERROR]%NC% %~1 -goto :eof - -echo ======================================== -echo Docker部署警告修复脚本 -echo ======================================== -echo. - -:: 1. 检查并创建.env文件 -call :print_info "检查 .env 文件..." -if not exist ".env" ( - if exist ".env.example" ( - call :print_info "从 .env.example 创建 .env 文件..." - copy ".env.example" ".env" >nul - call :print_success ".env 文件已创建" - ) else ( - call :print_warning ".env.example 文件不存在" - call :print_info "创建基本的 .env 文件..." - - ( - echo # 闲鱼自动回复系统 Docker 环境变量配置文件 - echo. - echo # 基础配置 - echo TZ=Asia/Shanghai - echo PYTHONUNBUFFERED=1 - echo LOG_LEVEL=INFO - echo. - echo # 数据库配置 - echo DB_PATH=/app/data/xianyu_data.db - echo. - echo # 服务配置 - echo WEB_PORT=8080 - echo. - echo # 安全配置 - echo ADMIN_USERNAME=admin - echo ADMIN_PASSWORD=admin123 - echo JWT_SECRET_KEY=xianyu-auto-reply-secret-key-2024 - echo. - echo # 资源限制 - echo MEMORY_LIMIT=512 - echo CPU_LIMIT=0.5 - echo MEMORY_RESERVATION=256 - echo CPU_RESERVATION=0.25 - echo. - echo # 自动回复配置 - echo AUTO_REPLY_ENABLED=true - echo WEBSOCKET_URL=wss://wss-goofish.dingtalk.com/ - echo HEARTBEAT_INTERVAL=15 - echo TOKEN_REFRESH_INTERVAL=3600 - ) > .env - - call :print_success "基本 .env 文件已创建" - ) -) else ( - call :print_success ".env 文件已存在" -) - -:: 2. 检查docker-compose.yml版本问题 -call :print_info "检查 docker-compose.yml 配置..." -findstr /B "version:" docker-compose.yml >nul 2>&1 -if !errorlevel! equ 0 ( - call :print_warning "发现过时的 version 字段" - call :print_info "移除 version 字段..." - - REM 备份原文件 - copy docker-compose.yml docker-compose.yml.backup >nul - - REM 创建临时文件,移除version行 - ( - for /f "tokens=*" %%a in (docker-compose.yml) do ( - echo %%a | findstr /B "version:" >nul - if !errorlevel! neq 0 ( - echo %%a - ) - ) - ) > docker-compose.yml.tmp - - REM 替换原文件 - move docker-compose.yml.tmp docker-compose.yml >nul - - call :print_success "已移除过时的 version 字段" - call :print_info "原文件已备份为 docker-compose.yml.backup" -) else ( - call :print_success "docker-compose.yml 配置正确" -) - -:: 3. 验证修复结果 -call :print_info "验证修复结果..." - -echo. -call :print_info "测试 Docker Compose 配置..." -docker-compose config >nul 2>&1 -if !errorlevel! equ 0 ( - call :print_success "Docker Compose 配置验证通过" -) else ( - call :print_error "Docker Compose 配置验证失败" - echo 请检查 docker-compose.yml 文件 - pause - exit /b 1 -) - -echo. -call :print_success "所有警告已修复!" -echo. -call :print_info "现在可以正常使用以下命令:" -echo docker-compose up -d # 启动服务 -echo docker-compose ps # 查看状态 -echo docker-compose logs -f # 查看日志 -echo. -call :print_info "如果需要恢复原配置:" -echo move docker-compose.yml.backup docker-compose.yml -echo. - -pause diff --git a/fix-docker-warnings.sh b/fix-docker-warnings.sh deleted file mode 100644 index 63d63e5..0000000 --- a/fix-docker-warnings.sh +++ /dev/null @@ -1,145 +0,0 @@ -#!/bin/bash - -# 修复Docker部署警告的快速脚本 -# 解决version过时和.env文件缺失问题 - -set -e - -# 颜色定义 -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -print_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -print_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -print_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -echo "========================================" -echo " Docker部署警告修复脚本" -echo "========================================" -echo "" - -# 1. 检查并创建.env文件 -print_info "检查 .env 文件..." -if [ ! -f ".env" ]; then - if [ -f ".env.example" ]; then - print_info "从 .env.example 创建 .env 文件..." - cp .env.example .env - print_success ".env 文件已创建" - else - print_warning ".env.example 文件不存在" - print_info "创建基本的 .env 文件..." - cat > .env << 'EOF' -# 闲鱼自动回复系统 Docker 环境变量配置文件 - -# 基础配置 -TZ=Asia/Shanghai -PYTHONUNBUFFERED=1 -LOG_LEVEL=INFO - -# 数据库配置 -DB_PATH=/app/data/xianyu_data.db - -# 服务配置 -WEB_PORT=8080 - -# 安全配置 -ADMIN_USERNAME=admin -ADMIN_PASSWORD=admin123 -JWT_SECRET_KEY=xianyu-auto-reply-secret-key-2024 - -# 资源限制 -MEMORY_LIMIT=512 -CPU_LIMIT=0.5 -MEMORY_RESERVATION=256 -CPU_RESERVATION=0.25 - -# 自动回复配置 -AUTO_REPLY_ENABLED=true -WEBSOCKET_URL=wss://wss-goofish.dingtalk.com/ -HEARTBEAT_INTERVAL=15 -TOKEN_REFRESH_INTERVAL=3600 -EOF - print_success "基本 .env 文件已创建" - fi -else - print_success ".env 文件已存在" -fi - -# 2. 检查docker-compose.yml版本问题 -print_info "检查 docker-compose.yml 配置..." -if grep -q "^version:" docker-compose.yml 2>/dev/null; then - print_warning "发现过时的 version 字段" - print_info "移除 version 字段..." - - # 备份原文件 - cp docker-compose.yml docker-compose.yml.backup - - # 移除version行 - sed -i '/^version:/d' docker-compose.yml - sed -i '/^$/N;/^\n$/d' docker-compose.yml # 移除空行 - - print_success "已移除过时的 version 字段" - print_info "原文件已备份为 docker-compose.yml.backup" -else - print_success "docker-compose.yml 配置正确" -fi - -# 3. 检查env_file配置 -print_info "检查 env_file 配置..." -if grep -A1 "env_file:" docker-compose.yml | grep -q "required: false"; then - print_success "env_file 配置正确" -else - print_info "更新 env_file 配置为可选..." - - # 备份文件(如果还没备份) - if [ ! -f "docker-compose.yml.backup" ]; then - cp docker-compose.yml docker-compose.yml.backup - fi - - # 更新env_file配置 - sed -i '/env_file:/,+1c\ - env_file:\ - - path: .env\ - required: false' docker-compose.yml - - print_success "env_file 配置已更新" -fi - -# 4. 验证修复结果 -print_info "验证修复结果..." - -echo "" -print_info "测试 Docker Compose 配置..." -if docker-compose config >/dev/null 2>&1; then - print_success "Docker Compose 配置验证通过" -else - print_error "Docker Compose 配置验证失败" - echo "请检查 docker-compose.yml 文件" - exit 1 -fi - -echo "" -print_success "所有警告已修复!" -echo "" -print_info "现在可以正常使用以下命令:" -echo " docker-compose up -d # 启动服务" -echo " docker-compose ps # 查看状态" -echo " docker-compose logs -f # 查看日志" -echo "" -print_info "如果需要恢复原配置:" -echo " mv docker-compose.yml.backup docker-compose.yml" diff --git a/fix-websocket-issue.sh b/fix-websocket-issue.sh deleted file mode 100644 index d874a86..0000000 --- a/fix-websocket-issue.sh +++ /dev/null @@ -1,121 +0,0 @@ -#!/bin/bash - -# 快速修复WebSocket兼容性问题 -# 解决 "extra_headers" 参数不支持的问题 - -set -e - -# 颜色定义 -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' - -print_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -print_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -print_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -echo "🔧 WebSocket兼容性问题修复" -echo "================================" - -# 1. 检查当前websockets版本 -print_info "检查当前websockets版本..." -if command -v python3 &> /dev/null; then - PYTHON_CMD="python3" -elif command -v python &> /dev/null; then - PYTHON_CMD="python" -else - print_error "未找到Python解释器" - exit 1 -fi - -CURRENT_VERSION=$($PYTHON_CMD -c "import websockets; print(websockets.__version__)" 2>/dev/null || echo "未安装") -print_info "当前websockets版本: $CURRENT_VERSION" - -# 2. 测试WebSocket兼容性 -print_info "测试WebSocket兼容性..." -$PYTHON_CMD test-websocket-compatibility.py - -# 3. 停止现有服务 -print_info "停止现有Docker服务..." -docker-compose down 2>/dev/null || true - -# 4. 更新websockets版本 -print_info "更新websockets版本到兼容版本..." -if [ -f "requirements.txt" ]; then - # 备份原文件 - cp requirements.txt requirements.txt.backup - - # 更新websockets版本 - sed -i 's/websockets>=.*/websockets>=10.0,<13.0 # 兼容性版本范围/' requirements.txt - - print_success "requirements.txt已更新" -else - print_warning "requirements.txt文件不存在" -fi - -# 5. 重新构建Docker镜像 -print_info "重新构建Docker镜像..." -docker-compose build --no-cache - -# 6. 启动服务 -print_info "启动服务..." -docker-compose up -d - -# 7. 等待服务启动 -print_info "等待服务启动..." -sleep 15 - -# 8. 检查服务状态 -print_info "检查服务状态..." -if docker-compose ps | grep -q "Up"; then - print_success "✅ 服务启动成功!" - - # 检查WebSocket错误 - print_info "检查WebSocket连接状态..." - sleep 5 - - # 查看最近的日志 - echo "" - print_info "最近的服务日志:" - docker-compose logs --tail=20 xianyu-app | grep -E "(WebSocket|extra_headers|ERROR)" || echo "未发现WebSocket相关错误" - - # 测试健康检查 - if curl -f http://localhost:8080/health >/dev/null 2>&1; then - print_success "健康检查通过" - else - print_warning "健康检查失败,服务可能仍在启动中" - fi - -else - print_error "❌ 服务启动失败" - print_info "查看错误日志:" - docker-compose logs --tail=30 xianyu-app - exit 1 -fi - -echo "" -print_success "🎉 WebSocket兼容性问题修复完成!" -echo "" -print_info "服务信息:" -echo " Web界面: http://localhost:8080" -echo " 健康检查: http://localhost:8080/health" -echo " 默认账号: admin / admin123" -echo "" -print_info "如果仍有WebSocket问题,请:" -echo " 1. 查看日志: docker-compose logs -f xianyu-app" -echo " 2. 运行测试: python test-websocket-compatibility.py" -echo " 3. 检查网络连接和防火墙设置" diff --git a/fix_api_isolation.py b/fix_api_isolation.py deleted file mode 100644 index ed6bf2f..0000000 --- a/fix_api_isolation.py +++ /dev/null @@ -1,334 +0,0 @@ -#!/usr/bin/env python3 -""" -修复API接口的用户隔离问题 -""" - -import re -import os -from loguru import logger - -def fix_cards_api(): - """修复卡券管理API的用户隔离""" - logger.info("修复卡券管理API...") - - # 读取reply_server.py文件 - with open('reply_server.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 修复获取卡券列表接口 - content = re.sub( - r'@app\.get\("/cards"\)\ndef get_cards\(_: None = Depends\(require_auth\)\):', - '@app.get("/cards")\ndef get_cards(current_user: Dict[str, Any] = Depends(get_current_user)):', - content - ) - - # 修复获取卡券列表的实现 - content = re.sub( - r'cards = db_manager\.get_all_cards\(\)\s+return cards', - '''# 只返回当前用户的卡券 - user_id = current_user['user_id'] - cards = db_manager.get_all_cards(user_id) - return cards''', - content, - flags=re.MULTILINE - ) - - # 修复创建卡券接口 - content = re.sub( - r'@app\.post\("/cards"\)\ndef create_card\(card_data: dict, _: None = Depends\(require_auth\)\):', - '@app.post("/cards")\ndef create_card(card_data: dict, current_user: Dict[str, Any] = Depends(get_current_user)):', - content - ) - - # 修复其他卡券接口... - # 这里需要更多的修复代码 - - # 写回文件 - with open('reply_server.py', 'w', encoding='utf-8') as f: - f.write(content) - - logger.info("✅ 卡券管理API修复完成") - -def fix_delivery_rules_api(): - """修复自动发货规则API的用户隔离""" - logger.info("修复自动发货规则API...") - - # 读取reply_server.py文件 - with open('reply_server.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 修复获取发货规则列表接口 - content = re.sub( - r'@app\.get\("/delivery-rules"\)\ndef get_delivery_rules\(_: None = Depends\(require_auth\)\):', - '@app.get("/delivery-rules")\ndef get_delivery_rules(current_user: Dict[str, Any] = Depends(get_current_user)):', - content - ) - - # 修复其他发货规则接口... - - # 写回文件 - with open('reply_server.py', 'w', encoding='utf-8') as f: - f.write(content) - - logger.info("✅ 自动发货规则API修复完成") - -def fix_notification_channels_api(): - """修复通知渠道API的用户隔离""" - logger.info("修复通知渠道API...") - - # 读取reply_server.py文件 - with open('reply_server.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 修复通知渠道接口... - - # 写回文件 - with open('reply_server.py', 'w', encoding='utf-8') as f: - f.write(content) - - logger.info("✅ 通知渠道API修复完成") - -def update_db_manager(): - """更新db_manager.py中的方法以支持用户隔离""" - logger.info("更新数据库管理器...") - - # 读取db_manager.py文件 - with open('db_manager.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 修复get_all_cards方法 - if 'def get_all_cards(self, user_id: int = None):' not in content: - content = re.sub( - r'def get_all_cards\(self\):', - 'def get_all_cards(self, user_id: int = None):', - content - ) - - # 修复方法实现 - content = re.sub( - r'SELECT id, name, type, api_config, text_content, data_content,\s+description, enabled, created_at, updated_at\s+FROM cards\s+ORDER BY created_at DESC', - '''SELECT id, name, type, api_config, text_content, data_content, - description, enabled, created_at, updated_at - FROM cards - WHERE (user_id = ? OR ? IS NULL) - ORDER BY created_at DESC''', - content, - flags=re.MULTILINE - ) - - # 写回文件 - with open('db_manager.py', 'w', encoding='utf-8') as f: - f.write(content) - - logger.info("✅ 数据库管理器更新完成") - -def create_user_settings_api(): - """创建用户设置API""" - logger.info("创建用户设置API...") - - user_settings_api = ''' - -# ------------------------- 用户设置接口 ------------------------- - -@app.get('/user-settings') -def get_user_settings(current_user: Dict[str, Any] = Depends(get_current_user)): - """获取当前用户的设置""" - from db_manager import db_manager - try: - user_id = current_user['user_id'] - settings = db_manager.get_user_settings(user_id) - return settings - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) - -@app.put('/user-settings/{key}') -def update_user_setting(key: str, setting_data: dict, current_user: Dict[str, Any] = Depends(get_current_user)): - """更新用户设置""" - from db_manager import db_manager - try: - user_id = current_user['user_id'] - value = setting_data.get('value') - description = setting_data.get('description', '') - - success = db_manager.set_user_setting(user_id, key, value, description) - if success: - return {'msg': 'setting updated', 'key': key, 'value': value} - else: - raise HTTPException(status_code=400, detail='更新失败') - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) - -@app.get('/user-settings/{key}') -def get_user_setting(key: str, current_user: Dict[str, Any] = Depends(get_current_user)): - """获取用户特定设置""" - from db_manager import db_manager - try: - user_id = current_user['user_id'] - setting = db_manager.get_user_setting(user_id, key) - if setting: - return setting - else: - raise HTTPException(status_code=404, detail='设置不存在') - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) -''' - - # 读取reply_server.py文件 - with open('reply_server.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 在文件末尾添加用户设置API - if 'user-settings' not in content: - content += user_settings_api - - # 写回文件 - with open('reply_server.py', 'w', encoding='utf-8') as f: - f.write(content) - - logger.info("✅ 用户设置API创建完成") - else: - logger.info("用户设置API已存在") - -def add_user_settings_methods_to_db(): - """为db_manager添加用户设置相关方法""" - logger.info("为数据库管理器添加用户设置方法...") - - user_settings_methods = ''' - - # ==================== 用户设置管理方法 ==================== - - def get_user_settings(self, user_id: int): - """获取用户的所有设置""" - with self.lock: - try: - cursor = self.conn.cursor() - cursor.execute(''' - SELECT key, value, description, updated_at - FROM user_settings - WHERE user_id = ? - ORDER BY key - ''', (user_id,)) - - settings = {} - for row in cursor.fetchall(): - settings[row[0]] = { - 'value': row[1], - 'description': row[2], - 'updated_at': row[3] - } - - return settings - except Exception as e: - logger.error(f"获取用户设置失败: {e}") - return {} - - def get_user_setting(self, user_id: int, key: str): - """获取用户的特定设置""" - with self.lock: - try: - cursor = self.conn.cursor() - cursor.execute(''' - SELECT value, description, updated_at - FROM user_settings - WHERE user_id = ? AND key = ? - ''', (user_id, key)) - - row = cursor.fetchone() - if row: - return { - 'key': key, - 'value': row[0], - 'description': row[1], - 'updated_at': row[2] - } - return None - except Exception as e: - logger.error(f"获取用户设置失败: {e}") - return None - - def set_user_setting(self, user_id: int, key: str, value: str, description: str = None): - """设置用户配置""" - with self.lock: - try: - cursor = self.conn.cursor() - cursor.execute(''' - INSERT OR REPLACE INTO user_settings (user_id, key, value, description, updated_at) - VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) - ''', (user_id, key, value, description)) - - self.conn.commit() - logger.info(f"用户设置更新成功: user_id={user_id}, key={key}") - return True - except Exception as e: - logger.error(f"设置用户配置失败: {e}") - self.conn.rollback() - return False -''' - - # 读取db_manager.py文件 - with open('db_manager.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 检查是否已经添加了用户设置方法 - if 'def get_user_settings(self, user_id: int):' not in content: - # 在类的末尾添加方法 - content = content.rstrip() + user_settings_methods - - # 写回文件 - with open('db_manager.py', 'w', encoding='utf-8') as f: - f.write(content) - - logger.info("✅ 用户设置方法添加完成") - else: - logger.info("用户设置方法已存在") - -def main(): - """主函数""" - print("🔧 修复API接口的用户隔离问题") - print("=" * 50) - - try: - # 1. 更新数据库管理器 - print("\n📦 1. 更新数据库管理器") - update_db_manager() - add_user_settings_methods_to_db() - - # 2. 修复卡券管理API - print("\n🎫 2. 修复卡券管理API") - fix_cards_api() - - # 3. 修复自动发货规则API - print("\n🚚 3. 修复自动发货规则API") - fix_delivery_rules_api() - - # 4. 修复通知渠道API - print("\n📢 4. 修复通知渠道API") - fix_notification_channels_api() - - # 5. 创建用户设置API - print("\n⚙️ 5. 创建用户设置API") - create_user_settings_api() - - print("\n" + "=" * 50) - print("🎉 API接口修复完成!") - - print("\n📋 修复内容:") - print("✅ 1. 更新数据库管理器方法") - print("✅ 2. 修复卡券管理API用户隔离") - print("✅ 3. 修复自动发货规则API用户隔离") - print("✅ 4. 修复通知渠道API用户隔离") - print("✅ 5. 创建用户设置API") - - print("\n⚠️ 注意:") - print("1. 部分接口可能需要手动调整") - print("2. 建议重启服务后进行测试") - print("3. 检查前端代码是否需要更新") - - return True - - except Exception as e: - logger.error(f"修复过程中出现错误: {e}") - return False - -if __name__ == "__main__": - main() diff --git a/fix_complete_isolation.py b/fix_complete_isolation.py deleted file mode 100644 index bf1987e..0000000 --- a/fix_complete_isolation.py +++ /dev/null @@ -1,317 +0,0 @@ -#!/usr/bin/env python3 -""" -完整的多用户数据隔离修复脚本 -""" - -import sqlite3 -import json -import time -from loguru import logger - -def backup_database(): - """备份数据库""" - try: - import shutil - timestamp = time.strftime("%Y%m%d_%H%M%S") - backup_file = f"xianyu_data_backup_{timestamp}.db" - shutil.copy2("xianyu_data.db", backup_file) - logger.info(f"数据库备份完成: {backup_file}") - return backup_file - except Exception as e: - logger.error(f"数据库备份失败: {e}") - return None - -def add_user_id_columns(): - """为相关表添加user_id字段""" - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - try: - # 检查并添加user_id字段到cards表 - cursor.execute("PRAGMA table_info(cards)") - columns = [column[1] for column in cursor.fetchall()] - - if 'user_id' not in columns: - logger.info("为cards表添加user_id字段...") - cursor.execute('ALTER TABLE cards ADD COLUMN user_id INTEGER REFERENCES users(id)') - logger.info("✅ cards表user_id字段添加成功") - else: - logger.info("cards表已有user_id字段") - - # 检查并添加user_id字段到delivery_rules表 - cursor.execute("PRAGMA table_info(delivery_rules)") - columns = [column[1] for column in cursor.fetchall()] - - if 'user_id' not in columns: - logger.info("为delivery_rules表添加user_id字段...") - cursor.execute('ALTER TABLE delivery_rules ADD COLUMN user_id INTEGER REFERENCES users(id)') - logger.info("✅ delivery_rules表user_id字段添加成功") - else: - logger.info("delivery_rules表已有user_id字段") - - # 检查并添加user_id字段到notification_channels表 - cursor.execute("PRAGMA table_info(notification_channels)") - columns = [column[1] for column in cursor.fetchall()] - - if 'user_id' not in columns: - logger.info("为notification_channels表添加user_id字段...") - cursor.execute('ALTER TABLE notification_channels ADD COLUMN user_id INTEGER REFERENCES users(id)') - logger.info("✅ notification_channels表user_id字段添加成功") - else: - logger.info("notification_channels表已有user_id字段") - - conn.commit() - return True - - except Exception as e: - logger.error(f"添加user_id字段失败: {e}") - conn.rollback() - return False - finally: - conn.close() - -def create_user_settings_table(): - """创建用户设置表""" - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - try: - # 检查表是否已存在 - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='user_settings'") - if cursor.fetchone(): - logger.info("user_settings表已存在") - return True - - logger.info("创建user_settings表...") - cursor.execute(''' - CREATE TABLE user_settings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL, - key TEXT NOT NULL, - value TEXT, - description TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, - UNIQUE(user_id, key) - ) - ''') - - conn.commit() - logger.info("✅ user_settings表创建成功") - return True - - except Exception as e: - logger.error(f"创建user_settings表失败: {e}") - conn.rollback() - return False - finally: - conn.close() - -def migrate_existing_data(): - """迁移现有数据到admin用户""" - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - try: - # 获取admin用户ID - cursor.execute("SELECT id FROM users WHERE username = 'admin'") - admin_result = cursor.fetchone() - - if not admin_result: - logger.error("未找到admin用户,请先创建admin用户") - return False - - admin_id = admin_result[0] - logger.info(f"找到admin用户,ID: {admin_id}") - - # 迁移cards表数据 - cursor.execute("SELECT COUNT(*) FROM cards WHERE user_id IS NULL") - unbound_cards = cursor.fetchone()[0] - - if unbound_cards > 0: - logger.info(f"迁移 {unbound_cards} 个未绑定的卡券到admin用户...") - cursor.execute("UPDATE cards SET user_id = ? WHERE user_id IS NULL", (admin_id,)) - logger.info("✅ 卡券数据迁移完成") - - # 迁移delivery_rules表数据 - cursor.execute("SELECT COUNT(*) FROM delivery_rules WHERE user_id IS NULL") - unbound_rules = cursor.fetchone()[0] - - if unbound_rules > 0: - logger.info(f"迁移 {unbound_rules} 个未绑定的发货规则到admin用户...") - cursor.execute("UPDATE delivery_rules SET user_id = ? WHERE user_id IS NULL", (admin_id,)) - logger.info("✅ 发货规则数据迁移完成") - - # 迁移notification_channels表数据 - cursor.execute("SELECT COUNT(*) FROM notification_channels WHERE user_id IS NULL") - unbound_channels = cursor.fetchone()[0] - - if unbound_channels > 0: - logger.info(f"迁移 {unbound_channels} 个未绑定的通知渠道到admin用户...") - cursor.execute("UPDATE notification_channels SET user_id = ? WHERE user_id IS NULL", (admin_id,)) - logger.info("✅ 通知渠道数据迁移完成") - - conn.commit() - return True - - except Exception as e: - logger.error(f"数据迁移失败: {e}") - conn.rollback() - return False - finally: - conn.close() - -def verify_isolation(): - """验证数据隔离效果""" - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - try: - logger.info("验证数据隔离效果...") - - # 检查各表的用户分布 - tables = ['cards', 'delivery_rules', 'notification_channels'] - - for table in tables: - cursor.execute(f''' - SELECT u.username, COUNT(*) as count - FROM {table} t - JOIN users u ON t.user_id = u.id - GROUP BY u.id, u.username - ORDER BY count DESC - ''') - - results = cursor.fetchall() - logger.info(f"📊 {table} 表用户分布:") - for username, count in results: - logger.info(f" • {username}: {count} 条记录") - - # 检查是否有未绑定的数据 - cursor.execute(f"SELECT COUNT(*) FROM {table} WHERE user_id IS NULL") - unbound_count = cursor.fetchone()[0] - if unbound_count > 0: - logger.warning(f"⚠️ {table} 表还有 {unbound_count} 条未绑定用户的记录") - else: - logger.info(f"✅ {table} 表所有记录都已正确绑定用户") - - return True - - except Exception as e: - logger.error(f"验证失败: {e}") - return False - finally: - conn.close() - -def create_default_user_settings(): - """为现有用户创建默认设置""" - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - try: - logger.info("为现有用户创建默认设置...") - - # 获取所有用户 - cursor.execute("SELECT id, username FROM users") - users = cursor.fetchall() - - default_settings = [ - ('theme_color', '#1890ff', '主题颜色'), - ('language', 'zh-CN', '界面语言'), - ('notification_enabled', 'true', '通知开关'), - ('auto_refresh', 'true', '自动刷新'), - ] - - for user_id, username in users: - logger.info(f"为用户 {username} 创建默认设置...") - - for key, value, description in default_settings: - # 检查设置是否已存在 - cursor.execute( - "SELECT id FROM user_settings WHERE user_id = ? AND key = ?", - (user_id, key) - ) - - if not cursor.fetchone(): - cursor.execute(''' - INSERT INTO user_settings (user_id, key, value, description) - VALUES (?, ?, ?, ?) - ''', (user_id, key, value, description)) - - conn.commit() - logger.info("✅ 默认用户设置创建完成") - return True - - except Exception as e: - logger.error(f"创建默认用户设置失败: {e}") - conn.rollback() - return False - finally: - conn.close() - -def main(): - """主函数""" - print("🚀 完整的多用户数据隔离修复") - print("=" * 60) - - # 1. 备份数据库 - print("\n📦 1. 备份数据库") - backup_file = backup_database() - if not backup_file: - print("❌ 数据库备份失败,停止修复") - return False - - # 2. 添加user_id字段 - print("\n🔧 2. 添加用户隔离字段") - if not add_user_id_columns(): - print("❌ 添加user_id字段失败") - return False - - # 3. 创建用户设置表 - print("\n📋 3. 创建用户设置表") - if not create_user_settings_table(): - print("❌ 创建用户设置表失败") - return False - - # 4. 迁移现有数据 - print("\n📦 4. 迁移现有数据") - if not migrate_existing_data(): - print("❌ 数据迁移失败") - return False - - # 5. 创建默认用户设置 - print("\n⚙️ 5. 创建默认用户设置") - if not create_default_user_settings(): - print("❌ 创建默认用户设置失败") - return False - - # 6. 验证隔离效果 - print("\n🔍 6. 验证数据隔离") - if not verify_isolation(): - print("❌ 验证失败") - return False - - print("\n" + "=" * 60) - print("🎉 多用户数据隔离修复完成!") - - print("\n📋 修复内容:") - print("✅ 1. 为cards表添加用户隔离") - print("✅ 2. 为delivery_rules表添加用户隔离") - print("✅ 3. 为notification_channels表添加用户隔离") - print("✅ 4. 创建用户设置表") - print("✅ 5. 迁移现有数据到admin用户") - print("✅ 6. 创建默认用户设置") - - print("\n⚠️ 下一步:") - print("1. 重启服务以应用数据库更改") - print("2. 运行API接口修复脚本") - print("3. 测试多用户数据隔离") - print("4. 更新前端代码") - - print(f"\n💾 数据库备份文件: {backup_file}") - print("如有问题,可以使用备份文件恢复数据") - - return True - -if __name__ == "__main__": - main() diff --git a/fix_user_isolation.py b/fix_user_isolation.py deleted file mode 100644 index f6fef0d..0000000 --- a/fix_user_isolation.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python3 -""" -修复多用户数据隔离的脚本 -""" - -import re - -def fix_user_isolation(): - """修复用户隔离问题""" - print("🔧 修复多用户数据隔离问题") - print("=" * 60) - - # 需要修复的接口列表 - interfaces_to_fix = [ - # 商品管理 - { - 'pattern': r'@app\.put\("/items/\{cookie_id\}/\{item_id\}"\)\ndef update_item_detail\(', - 'description': '更新商品详情接口', - 'add_user_check': True - }, - { - 'pattern': r'@app\.delete\("/items/\{cookie_id\}/\{item_id\}"\)\ndef delete_item_info\(', - 'description': '删除商品信息接口', - 'add_user_check': True - }, - { - 'pattern': r'@app\.delete\("/items/batch"\)\ndef batch_delete_items\(', - 'description': '批量删除商品接口', - 'add_user_check': True - }, - { - 'pattern': r'@app\.post\("/items/get-all-from-account"\)\nasync def get_all_items_from_account\(', - 'description': '从账号获取所有商品接口', - 'add_user_check': True - }, - { - 'pattern': r'@app\.post\("/items/get-by-page"\)\nasync def get_items_by_page\(', - 'description': '分页获取商品接口', - 'add_user_check': True - }, - # 卡券管理 - { - 'pattern': r'@app\.get\("/cards"\)\ndef get_cards\(', - 'description': '获取卡券列表接口', - 'add_user_check': False # 卡券是全局的,不需要用户隔离 - }, - # AI回复设置 - { - 'pattern': r'@app\.get\("/ai-reply-settings/\{cookie_id\}"\)\ndef get_ai_reply_settings\(', - 'description': 'AI回复设置接口', - 'add_user_check': True - }, - # 消息通知 - { - 'pattern': r'@app\.get\("/message-notifications/\{cid\}"\)\ndef get_account_notifications\(', - 'description': '获取账号消息通知接口', - 'add_user_check': True - }, - ] - - print("📋 需要修复的接口:") - for i, interface in enumerate(interfaces_to_fix, 1): - status = "✅ 需要用户检查" if interface['add_user_check'] else "ℹ️ 全局接口" - print(f" {i}. {interface['description']} - {status}") - - print("\n💡 修复建议:") - print("1. 将 '_: None = Depends(require_auth)' 替换为 'current_user: Dict[str, Any] = Depends(get_current_user)'") - print("2. 在需要用户检查的接口中添加用户权限验证") - print("3. 确保只返回当前用户的数据") - - print("\n🔍 检查当前状态...") - - # 读取reply_server.py文件 - try: - with open('reply_server.py', 'r', encoding='utf-8') as f: - content = f.read() - - # 统计还有多少接口使用旧的认证方式 - old_auth_count = len(re.findall(r'_: None = Depends\(require_auth\)', content)) - new_auth_count = len(re.findall(r'current_user: Dict\[str, Any\] = Depends\(get_current_user\)', content)) - - print(f"📊 认证方式统计:") - print(f" • 旧认证方式 (require_auth): {old_auth_count} 个接口") - print(f" • 新认证方式 (get_current_user): {new_auth_count} 个接口") - - if old_auth_count > 0: - print(f"\n⚠️ 还有 {old_auth_count} 个接口需要修复") - - # 找出具体哪些接口还没修复 - old_auth_interfaces = re.findall(r'@app\.\w+\([^)]+\)\s*\ndef\s+(\w+)\([^)]*_: None = Depends\(require_auth\)', content, re.MULTILINE) - - print("📝 未修复的接口:") - for interface in old_auth_interfaces: - print(f" • {interface}") - else: - print("\n🎉 所有接口都已使用新的认证方式!") - - # 检查是否有用户权限验证 - user_check_pattern = r'user_cookies = db_manager\.get_all_cookies\(user_id\)' - user_check_count = len(re.findall(user_check_pattern, content)) - - print(f"\n🔒 用户权限检查统计:") - print(f" • 包含用户权限检查的接口: {user_check_count} 个") - - return old_auth_count == 0 - - except Exception as e: - print(f"❌ 检查失败: {e}") - return False - -def generate_fix_template(): - """生成修复模板""" - print("\n📝 修复模板:") - print("-" * 40) - - template = ''' -# 修复前: -@app.get("/some-endpoint/{cid}") -def some_function(cid: str, _: None = Depends(require_auth)): - """接口描述""" - # 原有逻辑 - pass - -# 修复后: -@app.get("/some-endpoint/{cid}") -def some_function(cid: str, current_user: Dict[str, Any] = Depends(get_current_user)): - """接口描述""" - try: - # 检查cookie是否属于当前用户 - user_id = current_user['user_id'] - from db_manager import db_manager - user_cookies = db_manager.get_all_cookies(user_id) - - if cid not in user_cookies: - raise HTTPException(status_code=403, detail="无权限访问该Cookie") - - # 原有逻辑 - pass - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) -''' - - print(template) - -def check_database_isolation(): - """检查数据库隔离情况""" - print("\n🗄️ 检查数据库隔离情况") - print("-" * 40) - - try: - import sqlite3 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 检查cookies表是否有user_id字段 - cursor.execute("PRAGMA table_info(cookies)") - columns = [column[1] for column in cursor.fetchall()] - - if 'user_id' in columns: - print("✅ cookies表已支持用户隔离") - - # 统计用户数据分布 - cursor.execute(''' - SELECT u.username, COUNT(c.id) as cookie_count - FROM users u - LEFT JOIN cookies c ON u.id = c.user_id - GROUP BY u.id, u.username - ORDER BY cookie_count DESC - ''') - - user_stats = cursor.fetchall() - print("\n📊 用户数据分布:") - for username, cookie_count in user_stats: - print(f" • {username}: {cookie_count} 个cookies") - - # 检查未绑定的数据 - cursor.execute("SELECT COUNT(*) FROM cookies WHERE user_id IS NULL") - unbound_count = cursor.fetchone()[0] - if unbound_count > 0: - print(f"\n⚠️ 发现 {unbound_count} 个未绑定用户的cookies") - else: - print("\n✅ 所有cookies已正确绑定用户") - else: - print("❌ cookies表不支持用户隔离") - - conn.close() - - except Exception as e: - print(f"❌ 检查数据库失败: {e}") - -def main(): - """主函数""" - print("🚀 多用户数据隔离修复工具") - print("=" * 60) - - # 检查修复状态 - all_fixed = fix_user_isolation() - - # 生成修复模板 - generate_fix_template() - - # 检查数据库隔离 - check_database_isolation() - - print("\n" + "=" * 60) - if all_fixed: - print("🎉 多用户数据隔离检查完成!所有接口都已正确实现用户隔离。") - else: - print("⚠️ 还有接口需要修复,请按照模板进行修复。") - - print("\n📋 功能模块隔离状态:") - print("✅ 1. 账号管理 - Cookie相关接口已隔离") - print("✅ 2. 自动回复 - 关键字和默认回复已隔离") - print("❓ 3. 商品管理 - 部分接口需要检查") - print("❓ 4. 卡券管理 - 需要确认是否需要隔离") - print("❓ 5. 自动发货 - 需要检查") - print("❓ 6. 通知渠道 - 需要确认隔离策略") - print("❓ 7. 消息通知 - 需要检查") - print("❓ 8. 系统设置 - 需要确认哪些需要隔离") - - print("\n💡 下一步:") - print("1. 手动修复剩余的接口") - print("2. 测试所有功能的用户隔离") - print("3. 更新前端代码以支持多用户") - print("4. 编写完整的测试用例") - -if __name__ == "__main__": - main() diff --git a/gitignore_rules_explanation.md b/gitignore_rules_explanation.md deleted file mode 100644 index dacf1e4..0000000 --- a/gitignore_rules_explanation.md +++ /dev/null @@ -1,172 +0,0 @@ -# .gitignore 规则说明 - -## 📋 概述 - -本项目的 `.gitignore` 文件已经过优化,包含了完整的忽略规则,确保敏感文件和不必要的文件不会被提交到版本控制中。 - -## 🔧 主要修复 - -### 1. **数据库文件忽略** ✅ -**问题**: 原来缺少 `*.db` 文件的忽略规则 -**解决**: 添加了完整的数据库文件忽略规则 - -```gitignore -# Database files -*.db -*.sqlite -*.sqlite3 -db.sqlite3 -``` - -### 2. **静态资源例外** ✅ -**问题**: `lib/` 规则会忽略 `static/lib/` 中的本地 CDN 资源 -**解决**: 添加例外规则,允许 `static/lib/` 被版本控制 - -```gitignore -# Python lib directories (but not static/lib) -lib/ -!static/lib/ -``` - -## 📂 完整规则分类 - -### Python 相关 -```gitignore -__pycache__ -*.so -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -MANIFEST -*.manifest -*.spec -__pypackages__/ -.venv -venv/ -ENV/ -env.bak/ -venv.bak/ -``` - -### 数据库文件 -```gitignore -*.db -*.sqlite -*.sqlite3 -db.sqlite3 -``` - -### 日志和缓存 -```gitignore -*.log -.cache -``` - -### 临时文件 -```gitignore -*.tmp -*.temp -temp/ -tmp/ -``` - -### 操作系统生成的文件 -```gitignore -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -ehthumbs.db -Thumbs.db -``` - -### IDE 和编辑器文件 -```gitignore -.vscode/ -.idea/ -*.swp -*.swo -*~ -``` - -### 环境配置文件 -```gitignore -.env -.env.local -.env.*.local -local_settings.py -``` - -### Node.js 相关 -```gitignore -*node_modules/* -``` - -### 静态资源例外 -```gitignore -!static/lib/ -``` - -## 🎯 特殊说明 - -### 数据库文件保护 -- **目的**: 防止敏感的用户数据和配置信息被意外提交 -- **影响**: `xianyu_data.db` 等数据库文件不会被 Git 跟踪 -- **好处**: 保护用户隐私,避免数据泄露 - -### 静态资源管理 -- **目的**: 允许本地 CDN 资源被版本控制,提升中国大陆访问速度 -- **规则**: `lib/` 被忽略,但 `static/lib/` 不被忽略 -- **包含**: Bootstrap CSS/JS、Bootstrap Icons 等本地资源 - -### 环境配置保护 -- **目的**: 防止敏感的环境变量和配置被提交 -- **影响**: `.env` 文件和本地设置不会被跟踪 -- **好处**: 保护 API 密钥、数据库连接等敏感信息 - -## 🧪 验证方法 - -可以运行以下测试脚本验证规则是否正确: - -```bash -# 测试数据库文件忽略 -python test_gitignore_db.py - -# 测试静态资源例外 -python test_gitignore.py -``` - -## 📊 当前项目状态 - -### 被忽略的文件 -- `xianyu_data.db` (139,264 bytes) - 主数据库 -- `data/xianyu_data.db` (106,496 bytes) - 数据目录中的数据库 -- 各种临时文件、日志文件、IDE 配置等 - -### 不被忽略的重要文件 -- `static/lib/` 目录下的所有本地 CDN 资源 (702 KB) -- 源代码文件 (`.py`, `.html`, `.js` 等) -- 配置模板文件 (`.yml.example`, `.env.example` 等) -- 文档文件 (`.md` 等) - -## 🎉 优势总结 - -1. **数据安全**: 数据库文件不会被意外提交,保护用户数据 -2. **配置安全**: 环境变量和敏感配置得到保护 -3. **仓库整洁**: 临时文件、缓存文件等不会污染仓库 -4. **本地资源**: CDN 资源可以正常版本控制,提升访问速度 -5. **跨平台**: 支持 Windows、macOS、Linux 的常见忽略文件 -6. **IDE 友好**: 支持 VSCode、IntelliJ IDEA 等常见 IDE - -现在的 `.gitignore` 配置既保证了项目的安全性,又确保了必要文件的正常版本控制! diff --git a/migrate_to_multiuser.py b/migrate_to_multiuser.py deleted file mode 100644 index b760084..0000000 --- a/migrate_to_multiuser.py +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env python3 -""" -多用户系统迁移脚本 -将历史数据绑定到admin用户,并创建admin用户记录 -""" - -import sqlite3 -import hashlib -import time -from loguru import logger - -def migrate_to_multiuser(): - """迁移到多用户系统""" - print("🔄 开始迁移到多用户系统...") - print("=" * 60) - - try: - # 连接数据库 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - print("1️⃣ 检查数据库结构...") - - # 检查users表是否存在 - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'") - users_table_exists = cursor.fetchone() is not None - - if not users_table_exists: - print(" ❌ users表不存在,请先运行主程序初始化数据库") - return False - - print(" ✅ users表已存在") - - # 检查是否已有admin用户 - cursor.execute("SELECT id FROM users WHERE username = 'admin'") - admin_user = cursor.fetchone() - - if admin_user: - admin_user_id = admin_user[0] - print(f" ✅ admin用户已存在,ID: {admin_user_id}") - else: - print("2️⃣ 创建admin用户...") - - # 获取当前的admin密码哈希 - cursor.execute("SELECT value FROM system_settings WHERE key = 'admin_password_hash'") - password_hash_row = cursor.fetchone() - - if password_hash_row: - admin_password_hash = password_hash_row[0] - else: - # 如果没有设置密码,使用默认密码 admin123 - admin_password_hash = hashlib.sha256('admin123'.encode()).hexdigest() - print(" ⚠️ 未找到admin密码,使用默认密码: admin123") - - # 创建admin用户 - cursor.execute(''' - INSERT INTO users (username, email, password_hash, is_active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?) - ''', ('admin', 'admin@localhost', admin_password_hash, True, time.time(), time.time())) - - admin_user_id = cursor.lastrowid - print(f" ✅ admin用户创建成功,ID: {admin_user_id}") - - print("3️⃣ 检查cookies表结构...") - - # 检查cookies表是否有user_id字段 - cursor.execute("PRAGMA table_info(cookies)") - columns = [column[1] for column in cursor.fetchall()] - - if 'user_id' not in columns: - print(" 🔧 添加user_id字段到cookies表...") - cursor.execute("ALTER TABLE cookies ADD COLUMN user_id INTEGER") - print(" ✅ user_id字段添加成功") - else: - print(" ✅ user_id字段已存在") - - print("4️⃣ 迁移历史数据...") - - # 统计需要迁移的数据 - cursor.execute("SELECT COUNT(*) FROM cookies WHERE user_id IS NULL") - cookies_to_migrate = cursor.fetchone()[0] - - if cookies_to_migrate > 0: - print(f" 📊 发现 {cookies_to_migrate} 个cookies需要绑定到admin用户") - - # 将所有没有user_id的cookies绑定到admin用户 - cursor.execute("UPDATE cookies SET user_id = ? WHERE user_id IS NULL", (admin_user_id,)) - - print(f" ✅ 已将 {cookies_to_migrate} 个cookies绑定到admin用户") - else: - print(" ✅ 所有cookies已正确绑定用户") - - print("5️⃣ 验证迁移结果...") - - # 统计各用户的数据 - cursor.execute(''' - SELECT u.username, COUNT(c.id) as cookie_count - FROM users u - LEFT JOIN cookies c ON u.id = c.user_id - GROUP BY u.id, u.username - ''') - - user_stats = cursor.fetchall() - print(" 📊 用户数据统计:") - for username, cookie_count in user_stats: - print(f" • {username}: {cookie_count} 个cookies") - - # 检查是否还有未绑定的数据 - cursor.execute("SELECT COUNT(*) FROM cookies WHERE user_id IS NULL") - unbound_cookies = cursor.fetchone()[0] - - if unbound_cookies > 0: - print(f" ⚠️ 仍有 {unbound_cookies} 个cookies未绑定用户") - else: - print(" ✅ 所有cookies已正确绑定用户") - - # 提交事务 - conn.commit() - print("\n6️⃣ 迁移完成!") - - print("\n" + "=" * 60) - print("🎉 多用户系统迁移成功!") - print("\n📋 迁移总结:") - print(f" • admin用户ID: {admin_user_id}") - print(f" • 迁移的cookies数量: {cookies_to_migrate}") - print(f" • 当前用户数量: {len(user_stats)}") - - print("\n💡 下一步操作:") - print(" 1. 重启应用程序") - print(" 2. 使用admin账号登录管理现有数据") - print(" 3. 其他用户可以通过注册页面创建新账号") - print(" 4. 每个用户只能看到自己的数据") - - return True - - except Exception as e: - print(f"❌ 迁移失败: {e}") - if 'conn' in locals(): - conn.rollback() - return False - finally: - if 'conn' in locals(): - conn.close() - -def check_migration_status(): - """检查迁移状态""" - print("\n🔍 检查多用户系统状态...") - print("=" * 60) - - try: - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 检查users表 - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'") - if not cursor.fetchone(): - print("❌ users表不存在,需要先运行主程序初始化数据库") - return - - # 检查用户数量 - cursor.execute("SELECT COUNT(*) FROM users") - user_count = cursor.fetchone()[0] - print(f"👥 用户数量: {user_count}") - - # 检查admin用户 - cursor.execute("SELECT id, username, email, is_active FROM users WHERE username = 'admin'") - admin_user = cursor.fetchone() - if admin_user: - print(f"👑 admin用户: ID={admin_user[0]}, 邮箱={admin_user[2]}, 状态={'激活' if admin_user[3] else '禁用'}") - else: - print("❌ admin用户不存在") - - # 检查cookies表结构 - cursor.execute("PRAGMA table_info(cookies)") - columns = [column[1] for column in cursor.fetchall()] - if 'user_id' in columns: - print("✅ cookies表已支持用户隔离") - - # 统计各用户的cookies - cursor.execute(''' - SELECT u.username, COUNT(c.id) as cookie_count - FROM users u - LEFT JOIN cookies c ON u.id = c.user_id - GROUP BY u.id, u.username - ORDER BY cookie_count DESC - ''') - - user_stats = cursor.fetchall() - print("\n📊 用户数据分布:") - for username, cookie_count in user_stats: - print(f" • {username}: {cookie_count} 个cookies") - - # 检查未绑定的数据 - cursor.execute("SELECT COUNT(*) FROM cookies WHERE user_id IS NULL") - unbound_count = cursor.fetchone()[0] - if unbound_count > 0: - print(f"\n⚠️ 发现 {unbound_count} 个未绑定用户的cookies,建议运行迁移") - else: - print("\n✅ 所有数据已正确绑定用户") - else: - print("❌ cookies表不支持用户隔离,需要运行迁移") - - except Exception as e: - print(f"❌ 检查失败: {e}") - finally: - if 'conn' in locals(): - conn.close() - -if __name__ == "__main__": - import sys - - if len(sys.argv) > 1 and sys.argv[1] == 'check': - check_migration_status() - else: - print("🚀 闲鱼自动回复系统 - 多用户迁移工具") - print("=" * 60) - print("此工具将帮助您将单用户系统迁移到多用户系统") - print("主要功能:") - print("• 创建admin用户账号") - print("• 将历史数据绑定到admin用户") - print("• 支持新用户注册和数据隔离") - print("\n⚠️ 重要提醒:") - print("• 迁移前请备份数据库文件") - print("• 迁移过程中请勿操作系统") - print("• 迁移完成后需要重启应用") - - confirm = input("\n是否继续迁移?(y/N): ").strip().lower() - if confirm in ['y', 'yes']: - success = migrate_to_multiuser() - if success: - print("\n🎊 迁移完成!请重启应用程序。") - else: - print("\n💥 迁移失败!请检查错误信息。") - else: - print("取消迁移。") - - print(f"\n💡 提示: 运行 'python {sys.argv[0]} check' 可以检查迁移状态") diff --git a/qq-group.png b/qq-group.png new file mode 100644 index 0000000..f351cf1 Binary files /dev/null and b/qq-group.png differ diff --git a/quick-fix-permissions.bat b/quick-fix-permissions.bat deleted file mode 100644 index 762e0e5..0000000 --- a/quick-fix-permissions.bat +++ /dev/null @@ -1,116 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -:: 快速修复Docker权限问题 (Windows版本) - -title 快速修复Docker权限问题 - -:: 颜色定义 -set "RED=[91m" -set "GREEN=[92m" -set "YELLOW=[93m" -set "BLUE=[94m" -set "NC=[0m" - -:print_info -echo %BLUE%[INFO]%NC% %~1 -goto :eof - -:print_success -echo %GREEN%[SUCCESS]%NC% %~1 -goto :eof - -:print_error -echo %RED%[ERROR]%NC% %~1 -goto :eof - -echo 🚀 快速修复Docker权限问题 -echo ================================ -echo. - -:: 1. 停止容器 -call :print_info "停止现有容器..." -docker-compose down >nul 2>&1 - -:: 2. 确保目录存在 -call :print_info "创建必要目录..." -if not exist "data" mkdir data -if not exist "logs" mkdir logs -if not exist "backups" mkdir backups - -:: 3. 检查并修复docker-compose.yml -call :print_info "检查docker-compose.yml配置..." -findstr /C:"user.*0:0" docker-compose.yml >nul 2>&1 -if !errorlevel! neq 0 ( - call :print_info "添加root用户配置..." - - REM 备份原文件 - copy docker-compose.yml docker-compose.yml.backup >nul - - REM 创建临时文件添加user配置 - ( - for /f "tokens=*" %%a in (docker-compose.yml) do ( - echo %%a - echo %%a | findstr /C:"container_name: xianyu-auto-reply" >nul - if !errorlevel! equ 0 ( - echo user: "0:0" - ) - ) - ) > docker-compose.yml.tmp - - REM 替换原文件 - move docker-compose.yml.tmp docker-compose.yml >nul - - call :print_success "已配置使用root用户运行" -) - -:: 4. 重新构建镜像 -call :print_info "重新构建Docker镜像..." -docker-compose build --no-cache -if !errorlevel! neq 0 ( - call :print_error "Docker镜像构建失败" - pause - exit /b 1 -) - -:: 5. 启动服务 -call :print_info "启动服务..." -docker-compose up -d -if !errorlevel! neq 0 ( - call :print_error "服务启动失败" - pause - exit /b 1 -) - -:: 6. 等待启动 -call :print_info "等待服务启动..." -timeout /t 15 /nobreak >nul - -:: 7. 检查状态 -call :print_info "检查服务状态..." -docker-compose ps | findstr "Up" >nul -if !errorlevel! equ 0 ( - call :print_success "✅ 服务启动成功!" - - echo. - call :print_info "最近的日志:" - docker-compose logs --tail=10 xianyu-app - - echo. - call :print_success "🎉 权限问题已修复!" - echo. - echo 访问信息: - echo Web界面: http://localhost:8080 - echo 健康检查: http://localhost:8080/health - echo 默认账号: admin / admin123 - -) else ( - call :print_error "❌ 服务启动失败" - echo. - call :print_info "错误日志:" - docker-compose logs xianyu-app -) - -echo. -pause diff --git a/quick-fix-permissions.sh b/quick-fix-permissions.sh deleted file mode 100644 index fbe55de..0000000 --- a/quick-fix-permissions.sh +++ /dev/null @@ -1,88 +0,0 @@ -#!/bin/bash - -# 快速修复Docker权限问题 -# 这个脚本会立即解决权限问题并重启服务 - -set -e - -# 颜色定义 -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' - -print_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -print_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -echo "🚀 快速修复Docker权限问题" -echo "================================" - -# 1. 停止容器 -print_info "停止现有容器..." -docker-compose down - -# 2. 确保目录存在并设置权限 -print_info "设置目录权限..." -mkdir -p data logs backups -chmod 777 data logs backups - -# 3. 检查并修复docker-compose.yml -print_info "检查docker-compose.yml配置..." -if ! grep -q "user.*0:0" docker-compose.yml; then - print_info "添加root用户配置..." - - # 备份原文件 - cp docker-compose.yml docker-compose.yml.backup - - # 在container_name后添加user配置 - sed -i '/container_name: xianyu-auto-reply/a\ user: "0:0"' docker-compose.yml - - print_success "已配置使用root用户运行" -fi - -# 4. 重新构建镜像 -print_info "重新构建Docker镜像..." -docker-compose build --no-cache - -# 5. 启动服务 -print_info "启动服务..." -docker-compose up -d - -# 6. 等待启动 -print_info "等待服务启动..." -sleep 15 - -# 7. 检查状态 -print_info "检查服务状态..." -if docker-compose ps | grep -q "Up"; then - print_success "✅ 服务启动成功!" - - # 显示日志 - echo "" - print_info "最近的日志:" - docker-compose logs --tail=10 xianyu-app - - echo "" - print_success "🎉 权限问题已修复!" - echo "" - echo "访问信息:" - echo " Web界面: http://localhost:8080" - echo " 健康检查: http://localhost:8080/health" - echo " 默认账号: admin / admin123" - -else - print_error "❌ 服务启动失败" - echo "" - print_info "错误日志:" - docker-compose logs xianyu-app -fi diff --git a/reply_server.py b/reply_server.py index d37984a..f647df6 100644 --- a/reply_server.py +++ b/reply_server.py @@ -66,8 +66,10 @@ KEYWORDS_MAPPING = load_keywords() # 认证相关模型 class LoginRequest(BaseModel): - username: str - password: str + username: Optional[str] = None + password: Optional[str] = None + email: Optional[str] = None + verification_code: Optional[str] = None class LoginResponse(BaseModel): @@ -91,7 +93,8 @@ class RegisterResponse(BaseModel): class SendCodeRequest(BaseModel): email: str - session_id: str + session_id: Optional[str] = None + type: Optional[str] = 'register' # 'register' 或 'login' class SendCodeResponse(BaseModel): @@ -414,38 +417,70 @@ async def data_management_page(): async def login(request: LoginRequest): from db_manager import db_manager - logger.info(f"【{request.username}】尝试登录") + # 判断登录方式 + if request.username and request.password: + # 用户名/密码登录 + logger.info(f"【{request.username}】尝试用户名登录") - # 首先检查是否是admin用户(向后兼容) - if request.username == ADMIN_USERNAME and db_manager.verify_admin_password(request.password): - # 获取admin用户信息 - admin_user = db_manager.get_user_by_username('admin') - if admin_user: - user_id = admin_user['id'] - else: - user_id = 1 # 默认admin用户ID + # 首先检查是否是admin用户(向后兼容) + if request.username == ADMIN_USERNAME and db_manager.verify_admin_password(request.password): + # 获取admin用户信息 + admin_user = db_manager.get_user_by_username('admin') + if admin_user: + user_id = admin_user['id'] + else: + user_id = 1 # 默认admin用户ID - # 生成token - token = generate_token() - SESSION_TOKENS[token] = { - 'user_id': user_id, - 'username': 'admin', - 'timestamp': time.time() - } + # 生成token + token = generate_token() + SESSION_TOKENS[token] = { + 'user_id': user_id, + 'username': 'admin', + 'timestamp': time.time() + } - logger.info(f"【admin#{user_id}】登录成功(管理员)") + logger.info(f"【admin#{user_id}】登录成功(管理员)") + return LoginResponse( + success=True, + token=token, + message="登录成功", + user_id=user_id + ) + + # 检查普通用户 + if db_manager.verify_user_password(request.username, request.password): + user = db_manager.get_user_by_username(request.username) + if user: + # 生成token + token = generate_token() + SESSION_TOKENS[token] = { + 'user_id': user['id'], + 'username': user['username'], + 'timestamp': time.time() + } + + logger.info(f"【{user['username']}#{user['id']}】登录成功") + + return LoginResponse( + success=True, + token=token, + message="登录成功", + user_id=user['id'] + ) + + logger.warning(f"【{request.username}】登录失败:用户名或密码错误") return LoginResponse( - success=True, - token=token, - message="登录成功", - user_id=user_id + success=False, + message="用户名或密码错误" ) - # 检查普通用户 - if db_manager.verify_user_password(request.username, request.password): - user = db_manager.get_user_by_username(request.username) - if user: + elif request.email and request.password: + # 邮箱/密码登录 + logger.info(f"【{request.email}】尝试邮箱密码登录") + + user = db_manager.get_user_by_email(request.email) + if user and db_manager.verify_user_password(user['username'], request.password): # 生成token token = generate_token() SESSION_TOKENS[token] = { @@ -454,7 +489,7 @@ async def login(request: LoginRequest): 'timestamp': time.time() } - logger.info(f"【{user['username']}#{user['id']}】登录成功") + logger.info(f"【{user['username']}#{user['id']}】邮箱登录成功") return LoginResponse( success=True, @@ -463,11 +498,55 @@ async def login(request: LoginRequest): user_id=user['id'] ) - logger.warning(f"【{request.username}】登录失败: 用户名或密码错误") - return LoginResponse( - success=False, - message="用户名或密码错误" - ) + logger.warning(f"【{request.email}】邮箱登录失败:邮箱或密码错误") + return LoginResponse( + success=False, + message="邮箱或密码错误" + ) + + elif request.email and request.verification_code: + # 邮箱/验证码登录 + logger.info(f"【{request.email}】尝试邮箱验证码登录") + + # 验证邮箱验证码 + if not db_manager.verify_email_code(request.email, request.verification_code, 'login'): + logger.warning(f"【{request.email}】验证码登录失败:验证码错误或已过期") + return LoginResponse( + success=False, + message="验证码错误或已过期" + ) + + # 获取用户信息 + user = db_manager.get_user_by_email(request.email) + if not user: + logger.warning(f"【{request.email}】验证码登录失败:用户不存在") + return LoginResponse( + success=False, + message="用户不存在" + ) + + # 生成token + token = generate_token() + SESSION_TOKENS[token] = { + 'user_id': user['id'], + 'username': user['username'], + 'timestamp': time.time() + } + + logger.info(f"【{user['username']}#{user['id']}】验证码登录成功") + + return LoginResponse( + success=True, + token=token, + message="登录成功", + user_id=user['id'] + ) + + else: + return LoginResponse( + success=False, + message="请提供有效的登录信息" + ) # 验证token接口 @@ -578,19 +657,29 @@ async def send_verification_code(request: SendCodeRequest): # 或者我们可以在验证成功后设置一个临时标记 pass - # 检查邮箱是否已注册 - existing_user = db_manager.get_user_by_email(request.email) - if existing_user: - return SendCodeResponse( - success=False, - message="该邮箱已被注册" - ) + # 根据验证码类型进行不同的检查 + if request.type == 'register': + # 注册验证码:检查邮箱是否已注册 + existing_user = db_manager.get_user_by_email(request.email) + if existing_user: + return SendCodeResponse( + success=False, + message="该邮箱已被注册" + ) + elif request.type == 'login': + # 登录验证码:检查邮箱是否存在 + existing_user = db_manager.get_user_by_email(request.email) + if not existing_user: + return SendCodeResponse( + success=False, + message="该邮箱未注册" + ) # 生成验证码 code = db_manager.generate_verification_code() # 保存验证码到数据库 - if not db_manager.save_verification_code(request.email, code): + if not db_manager.save_verification_code(request.email, code, request.type): return SendCodeResponse( success=False, message="验证码保存失败,请稍后重试" @@ -788,7 +877,7 @@ def add_cookie(item: CookieIn, current_user: Dict[str, Any] = Depends(get_curren user_id = current_user['user_id'] from db_manager import db_manager - log_with_user('info', f"尝试添加Cookie: {item.id}", current_user) + log_with_user('info', f"尝试添加Cookie: {item.id}, 当前用户ID: {user_id}, 用户名: {current_user.get('username', 'unknown')}", current_user) # 检查cookie是否已存在且属于其他用户 existing_cookies = db_manager.get_all_cookies() @@ -802,8 +891,8 @@ def add_cookie(item: CookieIn, current_user: Dict[str, Any] = Depends(get_curren # 保存到数据库时指定用户ID db_manager.save_cookie(item.id, item.value, user_id) - # 添加到CookieManager - cookie_manager.manager.add_cookie(item.id, item.value) + # 添加到CookieManager,同时指定用户ID + cookie_manager.manager.add_cookie(item.id, item.value, user_id=user_id) log_with_user('info', f"Cookie添加成功: {item.id}", current_user) return {"msg": "success"} except HTTPException: @@ -946,24 +1035,27 @@ def delete_default_reply(cid: str, current_user: Dict[str, Any] = Depends(get_cu # ------------------------- 通知渠道管理接口 ------------------------- @app.get('/notification-channels') -def get_notification_channels(_: None = Depends(require_auth)): +def get_notification_channels(current_user: Dict[str, Any] = Depends(get_current_user)): """获取所有通知渠道""" from db_manager import db_manager try: - return db_manager.get_notification_channels() + user_id = current_user['user_id'] + return db_manager.get_notification_channels(user_id) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post('/notification-channels') -def create_notification_channel(channel_data: NotificationChannelIn, _: None = Depends(require_auth)): +def create_notification_channel(channel_data: NotificationChannelIn, current_user: Dict[str, Any] = Depends(get_current_user)): """创建通知渠道""" from db_manager import db_manager try: + user_id = current_user['user_id'] channel_id = db_manager.create_notification_channel( channel_data.name, channel_data.type, - channel_data.config + channel_data.config, + user_id ) return {'msg': 'notification channel created', 'id': channel_id} except Exception as e: @@ -1327,27 +1419,30 @@ def update_card(card_id: int, card_data: dict, _: None = Depends(require_auth)): # 自动发货规则API @app.get("/delivery-rules") -def get_delivery_rules(_: None = Depends(require_auth)): +def get_delivery_rules(current_user: Dict[str, Any] = Depends(get_current_user)): """获取发货规则列表""" try: from db_manager import db_manager - rules = db_manager.get_all_delivery_rules() + user_id = current_user['user_id'] + rules = db_manager.get_all_delivery_rules(user_id) return rules except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/delivery-rules") -def create_delivery_rule(rule_data: dict, _: None = Depends(require_auth)): +def create_delivery_rule(rule_data: dict, current_user: Dict[str, Any] = Depends(get_current_user)): """创建新发货规则""" try: from db_manager import db_manager + user_id = current_user['user_id'] rule_id = db_manager.create_delivery_rule( keyword=rule_data.get('keyword'), card_id=rule_data.get('card_id'), delivery_count=rule_data.get('delivery_count', 1), enabled=rule_data.get('enabled', True), - description=rule_data.get('description') + description=rule_data.get('description'), + user_id=user_id ) return {"id": rule_id, "message": "发货规则创建成功"} except Exception as e: @@ -1355,11 +1450,12 @@ def create_delivery_rule(rule_data: dict, _: None = Depends(require_auth)): @app.get("/delivery-rules/{rule_id}") -def get_delivery_rule(rule_id: int, _: None = Depends(require_auth)): +def get_delivery_rule(rule_id: int, current_user: Dict[str, Any] = Depends(get_current_user)): """获取单个发货规则详情""" try: from db_manager import db_manager - rule = db_manager.get_delivery_rule_by_id(rule_id) + user_id = current_user['user_id'] + rule = db_manager.get_delivery_rule_by_id(rule_id, user_id) if rule: return rule else: @@ -1369,17 +1465,19 @@ def get_delivery_rule(rule_id: int, _: None = Depends(require_auth)): @app.put("/delivery-rules/{rule_id}") -def update_delivery_rule(rule_id: int, rule_data: dict, _: None = Depends(require_auth)): +def update_delivery_rule(rule_id: int, rule_data: dict, current_user: Dict[str, Any] = Depends(get_current_user)): """更新发货规则""" try: from db_manager import db_manager + user_id = current_user['user_id'] success = db_manager.update_delivery_rule( rule_id=rule_id, keyword=rule_data.get('keyword'), card_id=rule_data.get('card_id'), delivery_count=rule_data.get('delivery_count', 1), enabled=rule_data.get('enabled', True), - description=rule_data.get('description') + description=rule_data.get('description'), + user_id=user_id ) if success: return {"message": "发货规则更新成功"} @@ -1404,11 +1502,12 @@ def delete_card(card_id: int, _: None = Depends(require_auth)): @app.delete("/delivery-rules/{rule_id}") -def delete_delivery_rule(rule_id: int, _: None = Depends(require_auth)): +def delete_delivery_rule(rule_id: int, current_user: Dict[str, Any] = Depends(get_current_user)): """删除发货规则""" try: from db_manager import db_manager - success = db_manager.delete_delivery_rule(rule_id) + user_id = current_user['user_id'] + success = db_manager.delete_delivery_rule(rule_id, user_id) if success: return {"message": "发货规则删除成功"} else: diff --git a/simple_log_test.py b/simple_log_test.py deleted file mode 100644 index c0392e7..0000000 --- a/simple_log_test.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python3 -""" -简单的日志测试 -""" - -import requests -import time - -BASE_URL = "http://localhost:8080" - -def test_admin_login(): - """测试管理员登录的日志显示""" - print("🔧 测试管理员登录...") - - # 管理员登录 - response = requests.post(f"{BASE_URL}/login", - json={'username': 'admin', 'password': 'admin123'}) - - if response.json()['success']: - token = response.json()['token'] - headers = {'Authorization': f'Bearer {token}'} - - print("✅ 管理员登录成功") - - # 测试一些API调用 - print("📋 测试API调用...") - - # 1. 获取Cookie列表 - response = requests.get(f"{BASE_URL}/cookies", headers=headers) - print(f" Cookie列表: {response.status_code}") - - # 2. 获取Cookie详情 - response = requests.get(f"{BASE_URL}/cookies/details", headers=headers) - print(f" Cookie详情: {response.status_code}") - - # 3. 获取卡券列表 - response = requests.get(f"{BASE_URL}/cards", headers=headers) - print(f" 卡券列表: {response.status_code}") - - # 4. 获取用户设置 - response = requests.get(f"{BASE_URL}/user-settings", headers=headers) - print(f" 用户设置: {response.status_code}") - - print("✅ API调用测试完成") - return True - else: - print("❌ 管理员登录失败") - return False - -def main(): - """主函数""" - print("🚀 简单日志测试") - print("=" * 40) - - print("📋 测试内容:") - print("• 管理员登录日志") - print("• API请求/响应日志") - print("• 用户信息显示") - - print("\n🔍 请观察服务器日志输出...") - print("应该看到类似以下格式的日志:") - print("🌐 【admin#1】 API请求: GET /cookies") - print("✅ 【admin#1】 API响应: GET /cookies - 200 (0.005s)") - - print("\n" + "-" * 40) - - # 执行测试 - success = test_admin_login() - - print("-" * 40) - - if success: - print("🎉 测试完成!请检查服务器日志中的用户信息显示。") - print("\n💡 检查要点:") - print("1. 登录日志应显示: 【admin】尝试登录") - print("2. API请求日志应显示: 【admin#1】") - print("3. API响应日志应显示: 【admin#1】") - else: - print("❌ 测试失败") - - return success - -if __name__ == "__main__": - main() diff --git a/static/data_management.html b/static/data_management.html index 4efc64c..9281723 100644 --- a/static/data_management.html +++ b/static/data_management.html @@ -56,6 +56,9 @@ 用户管理 + + 数据管理 + 日志管理 @@ -156,7 +159,7 @@
-
+ - - - -
+ + -
- - - - diff --git a/static/user_management.html b/static/user_management.html index cae0628..5fade08 100644 --- a/static/user_management.html +++ b/static/user_management.html @@ -46,6 +46,12 @@ 首页 + + 用户管理 + + + 数据管理 + 日志管理 diff --git a/test_admin_features.py b/test_admin_features.py deleted file mode 100644 index 17712f0..0000000 --- a/test_admin_features.py +++ /dev/null @@ -1,345 +0,0 @@ -#!/usr/bin/env python3 -""" -测试管理员功能 -""" - -import requests -import json -import time -import sqlite3 -from loguru import logger - -BASE_URL = "http://localhost:8080" - -def test_admin_login(): - """测试管理员登录""" - logger.info("测试管理员登录...") - - response = requests.post(f"{BASE_URL}/login", - json={'username': 'admin', 'password': 'admin123'}) - - if response.json()['success']: - token = response.json()['token'] - user_id = response.json()['user_id'] - - logger.info(f"管理员登录成功,token: {token[:20]}...") - return { - 'token': token, - 'user_id': user_id, - 'headers': {'Authorization': f'Bearer {token}'} - } - else: - logger.error("管理员登录失败") - return None - -def test_user_management(admin): - """测试用户管理功能""" - logger.info("测试用户管理功能...") - - # 1. 获取所有用户 - response = requests.get(f"{BASE_URL}/admin/users", headers=admin['headers']) - if response.status_code == 200: - users = response.json()['users'] - logger.info(f"✅ 获取用户列表成功,共 {len(users)} 个用户") - - for user in users: - logger.info(f" 用户: {user['username']} (ID: {user['id']}) - Cookie: {user.get('cookie_count', 0)}, 卡券: {user.get('card_count', 0)}") - else: - logger.error(f"❌ 获取用户列表失败: {response.status_code}") - return False - - # 2. 测试非管理员权限验证 - logger.info("测试非管理员权限验证...") - - # 创建一个普通用户token(模拟) - fake_headers = {'Authorization': 'Bearer fake_token'} - response = requests.get(f"{BASE_URL}/admin/users", headers=fake_headers) - - if response.status_code == 401 or response.status_code == 403: - logger.info("✅ 非管理员权限验证正常") - else: - logger.warning(f"⚠️ 权限验证可能有问题: {response.status_code}") - - return True - -def test_system_stats(admin): - """测试系统统计功能""" - logger.info("测试系统统计功能...") - - response = requests.get(f"{BASE_URL}/admin/stats", headers=admin['headers']) - if response.status_code == 200: - stats = response.json() - logger.info("✅ 获取系统统计成功:") - logger.info(f" 总用户数: {stats['users']['total']}") - logger.info(f" 总Cookie数: {stats['cookies']['total']}") - logger.info(f" 总卡券数: {stats['cards']['total']}") - logger.info(f" 系统版本: {stats['system']['version']}") - return True - else: - logger.error(f"❌ 获取系统统计失败: {response.status_code}") - return False - -def test_log_management(admin): - """测试日志管理功能""" - logger.info("测试日志管理功能...") - - # 1. 获取系统日志 - response = requests.get(f"{BASE_URL}/admin/logs?lines=50", headers=admin['headers']) - if response.status_code == 200: - log_data = response.json() - logs = log_data.get('logs', []) - logger.info(f"✅ 获取系统日志成功,共 {len(logs)} 条") - - if logs: - logger.info(" 最新几条日志:") - for i, log in enumerate(logs[-3:]): # 显示最后3条 - logger.info(f" {i+1}. {log[:100]}...") - else: - logger.error(f"❌ 获取系统日志失败: {response.status_code}") - return False - - # 2. 测试日志级别过滤 - response = requests.get(f"{BASE_URL}/admin/logs?lines=20&level=info", headers=admin['headers']) - if response.status_code == 200: - log_data = response.json() - info_logs = log_data.get('logs', []) - logger.info(f"✅ INFO级别日志过滤成功,共 {len(info_logs)} 条") - else: - logger.error(f"❌ 日志级别过滤失败: {response.status_code}") - return False - - return True - -def create_test_user_for_deletion(): - """创建一个测试用户用于删除测试""" - logger.info("创建测试用户用于删除测试...") - - user_data = { - "username": "test_delete_user", - "email": "delete@test.com", - "password": "test123456" - } - - try: - # 清理可能存在的用户 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('DELETE FROM users WHERE username = ? OR email = ?', (user_data['username'], user_data['email'])) - cursor.execute('DELETE FROM email_verifications WHERE email = ?', (user_data['email'],)) - conn.commit() - conn.close() - - # 生成验证码 - session_id = f"delete_test_{int(time.time())}" - - # 生成图形验证码 - captcha_response = requests.post(f"{BASE_URL}/generate-captcha", - json={'session_id': session_id}) - if not captcha_response.json()['success']: - logger.error("图形验证码生成失败") - return None - - # 获取图形验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id,)) - captcha_result = cursor.fetchone() - conn.close() - - if not captcha_result: - logger.error("无法获取图形验证码") - return None - - captcha_code = captcha_result[0] - - # 验证图形验证码 - verify_response = requests.post(f"{BASE_URL}/verify-captcha", - json={'session_id': session_id, 'captcha_code': captcha_code}) - if not verify_response.json()['success']: - logger.error("图形验证码验证失败") - return None - - # 发送邮箱验证码 - email_response = requests.post(f"{BASE_URL}/send-verification-code", - json={'email': user_data['email'], 'session_id': session_id}) - if not email_response.json()['success']: - logger.error("邮箱验证码发送失败") - return None - - # 获取邮箱验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM email_verifications WHERE email = ? ORDER BY created_at DESC LIMIT 1', - (user_data['email'],)) - email_result = cursor.fetchone() - conn.close() - - if not email_result: - logger.error("无法获取邮箱验证码") - return None - - email_code = email_result[0] - - # 注册用户 - register_response = requests.post(f"{BASE_URL}/register", - json={ - 'username': user_data['username'], - 'email': user_data['email'], - 'verification_code': email_code, - 'password': user_data['password'] - }) - - if register_response.json()['success']: - logger.info(f"测试用户创建成功: {user_data['username']}") - - # 获取用户ID - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT id FROM users WHERE username = ?', (user_data['username'],)) - result = cursor.fetchone() - conn.close() - - if result: - return { - 'user_id': result[0], - 'username': user_data['username'] - } - - logger.error("测试用户创建失败") - return None - - except Exception as e: - logger.error(f"创建测试用户失败: {e}") - return None - -def test_user_deletion(admin): - """测试用户删除功能""" - logger.info("测试用户删除功能...") - - # 创建测试用户 - test_user = create_test_user_for_deletion() - if not test_user: - logger.error("无法创建测试用户,跳过删除测试") - return False - - user_id = test_user['user_id'] - username = test_user['username'] - - # 删除用户 - response = requests.delete(f"{BASE_URL}/admin/users/{user_id}", headers=admin['headers']) - if response.status_code == 200: - logger.info(f"✅ 用户删除成功: {username}") - - # 验证用户确实被删除 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT id FROM users WHERE id = ?', (user_id,)) - result = cursor.fetchone() - conn.close() - - if not result: - logger.info("✅ 用户删除验证通过") - return True - else: - logger.error("❌ 用户删除验证失败,用户仍然存在") - return False - else: - logger.error(f"❌ 用户删除失败: {response.status_code}") - return False - -def test_admin_self_deletion_protection(admin): - """测试管理员自删除保护""" - logger.info("测试管理员自删除保护...") - - admin_user_id = admin['user_id'] - - response = requests.delete(f"{BASE_URL}/admin/users/{admin_user_id}", headers=admin['headers']) - if response.status_code == 400: - logger.info("✅ 管理员自删除保护正常") - return True - else: - logger.error(f"❌ 管理员自删除保护失败: {response.status_code}") - return False - -def main(): - """主测试函数""" - print("🚀 管理员功能测试") - print("=" * 60) - - print("📋 测试内容:") - print("• 管理员登录") - print("• 用户管理功能") - print("• 系统统计功能") - print("• 日志管理功能") - print("• 用户删除功能") - print("• 管理员保护机制") - - try: - # 管理员登录 - admin = test_admin_login() - if not admin: - print("❌ 测试失败:管理员登录失败") - return False - - print("✅ 管理员登录成功") - - # 测试各项功能 - tests = [ - ("用户管理", lambda: test_user_management(admin)), - ("系统统计", lambda: test_system_stats(admin)), - ("日志管理", lambda: test_log_management(admin)), - ("用户删除", lambda: test_user_deletion(admin)), - ("管理员保护", lambda: test_admin_self_deletion_protection(admin)) - ] - - results = [] - for test_name, test_func in tests: - print(f"\n🧪 测试 {test_name}...") - try: - result = test_func() - results.append((test_name, result)) - if result: - print(f"✅ {test_name} 测试通过") - else: - print(f"❌ {test_name} 测试失败") - except Exception as e: - print(f"💥 {test_name} 测试异常: {e}") - results.append((test_name, False)) - - print("\n" + "=" * 60) - print("🎉 管理员功能测试完成!") - - print("\n📊 测试结果:") - passed = 0 - for test_name, result in results: - status = "✅ 通过" if result else "❌ 失败" - print(f" {test_name}: {status}") - if result: - passed += 1 - - print(f"\n📈 总体结果: {passed}/{len(results)} 项测试通过") - - if passed == len(results): - print("🎊 所有测试都通过了!管理员功能正常工作。") - - print("\n💡 使用说明:") - print("1. 使用admin账号登录系统") - print("2. 在侧边栏可以看到'管理员功能'菜单") - print("3. 点击'用户管理'可以查看和删除用户") - print("4. 点击'系统日志'可以查看系统运行日志") - print("5. 这些功能只有admin用户可以访问") - - return True - else: - print("⚠️ 部分测试失败,请检查相关功能。") - return False - - except Exception as e: - print(f"💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/test_ai_reply.py b/test_ai_reply.py deleted file mode 100644 index 430c355..0000000 --- a/test_ai_reply.py +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/bin/env python3 -""" -AI回复功能测试脚本 -用于验证AI回复集成是否正常工作 -""" - -import asyncio -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from ai_reply_engine import ai_reply_engine -from db_manager import db_manager -from loguru import logger - -async def test_ai_reply_basic(): - """测试AI回复基本功能""" - print("🧪 开始测试AI回复基本功能...") - - # 测试数据 - test_cookie_id = "test_cookie_001" - test_item_id = "123456789" - test_message = "你好,这个商品能便宜点吗?" - test_chat_id = "test_chat_001" - test_user_id = "test_user_001" - - # 测试商品信息 - test_item_info = { - 'title': '测试商品', - 'price': 100, - 'desc': '这是一个用于测试的商品' - } - - print(f"📝 测试参数:") - print(f" 账号ID: {test_cookie_id}") - print(f" 商品ID: {test_item_id}") - print(f" 用户消息: {test_message}") - print(f" 商品信息: {test_item_info}") - - # 1. 测试AI回复是否启用检查 - print("\n1️⃣ 测试AI回复启用状态检查...") - is_enabled = ai_reply_engine.is_ai_enabled(test_cookie_id) - print(f" AI回复启用状态: {is_enabled}") - - if not is_enabled: - print(" ⚠️ AI回复未启用,跳过后续测试") - print(" 💡 请在Web界面中为测试账号启用AI回复功能") - return False - - # 2. 测试意图检测 - print("\n2️⃣ 测试意图检测...") - try: - intent = ai_reply_engine.detect_intent(test_message, test_cookie_id) - print(f" 检测到的意图: {intent}") - except Exception as e: - print(f" ❌ 意图检测失败: {e}") - return False - - # 3. 测试AI回复生成 - print("\n3️⃣ 测试AI回复生成...") - try: - reply = ai_reply_engine.generate_reply( - message=test_message, - item_info=test_item_info, - chat_id=test_chat_id, - cookie_id=test_cookie_id, - user_id=test_user_id, - item_id=test_item_id - ) - - if reply: - print(f" ✅ AI回复生成成功: {reply}") - else: - print(f" ❌ AI回复生成失败: 返回空值") - return False - - except Exception as e: - print(f" ❌ AI回复生成异常: {e}") - return False - - print("\n✅ AI回复基本功能测试完成!") - return True - -def test_database_operations(): - """测试数据库操作""" - print("\n🗄️ 开始测试数据库操作...") - - test_cookie_id = "test_cookie_001" - - # 1. 测试获取AI回复设置 - print("\n1️⃣ 测试获取AI回复设置...") - try: - settings = db_manager.get_ai_reply_settings(test_cookie_id) - print(f" AI回复设置: {settings}") - except Exception as e: - print(f" ❌ 获取AI回复设置失败: {e}") - return False - - # 2. 测试保存AI回复设置 - print("\n2️⃣ 测试保存AI回复设置...") - try: - test_settings = { - 'ai_enabled': True, - 'model_name': 'qwen-plus', - 'api_key': 'test-api-key', - 'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1', - 'max_discount_percent': 10, - 'max_discount_amount': 100, - 'max_bargain_rounds': 3, - 'custom_prompts': '' - } - - success = db_manager.save_ai_reply_settings(test_cookie_id, test_settings) - if success: - print(f" ✅ AI回复设置保存成功") - else: - print(f" ❌ AI回复设置保存失败") - return False - - except Exception as e: - print(f" ❌ 保存AI回复设置异常: {e}") - return False - - # 3. 验证设置是否正确保存 - print("\n3️⃣ 验证设置保存...") - try: - saved_settings = db_manager.get_ai_reply_settings(test_cookie_id) - if saved_settings['ai_enabled'] == True: - print(f" ✅ 设置验证成功: AI回复已启用") - else: - print(f" ❌ 设置验证失败: AI回复未启用") - return False - except Exception as e: - print(f" ❌ 设置验证异常: {e}") - return False - - print("\n✅ 数据库操作测试完成!") - return True - -def test_configuration(): - """测试配置检查""" - print("\n⚙️ 开始测试配置检查...") - - # 1. 检查必要的模块导入 - print("\n1️⃣ 检查模块导入...") - try: - from openai import OpenAI - print(" ✅ OpenAI模块导入成功") - except ImportError as e: - print(f" ❌ OpenAI模块导入失败: {e}") - print(" 💡 请运行: pip install openai>=1.65.5") - return False - - # 2. 检查数据库表结构 - print("\n2️⃣ 检查数据库表结构...") - try: - # 检查ai_reply_settings表是否存在 - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='ai_reply_settings'") - if cursor.fetchone(): - print(" ✅ ai_reply_settings表存在") - else: - print(" ❌ ai_reply_settings表不存在") - return False - - # 检查ai_conversations表是否存在 - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='ai_conversations'") - if cursor.fetchone(): - print(" ✅ ai_conversations表存在") - else: - print(" ❌ ai_conversations表不存在") - return False - - except Exception as e: - print(f" ❌ 数据库表检查异常: {e}") - return False - - print("\n✅ 配置检查完成!") - return True - -async def main(): - """主测试函数""" - print("🚀 AI回复功能集成测试开始") - print("=" * 50) - - # 测试配置 - config_ok = test_configuration() - if not config_ok: - print("\n❌ 配置检查失败,请修复后重试") - return - - # 测试数据库操作 - db_ok = test_database_operations() - if not db_ok: - print("\n❌ 数据库操作测试失败") - return - - # 测试AI回复功能 - ai_ok = await test_ai_reply_basic() - if not ai_ok: - print("\n❌ AI回复功能测试失败") - return - - print("\n" + "=" * 50) - print("🎉 所有测试通过!AI回复功能集成成功!") - print("\n📋 下一步操作:") - print("1. 在Web界面中配置AI回复API密钥") - print("2. 为需要的账号启用AI回复功能") - print("3. 测试实际的消息回复效果") - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/test_ai_reply_fix.py b/test_ai_reply_fix.py deleted file mode 100644 index 771f7c2..0000000 --- a/test_ai_reply_fix.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python3 -""" -AI回复修复验证脚本 -验证settings变量作用域问题是否已修复 -""" - -import asyncio -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from ai_reply_engine import ai_reply_engine -from db_manager import db_manager - -def setup_test_account(): - """设置测试账号""" - test_cookie_id = "test_fix_001" - - # 配置AI回复设置 - ai_settings = { - 'ai_enabled': True, - 'model_name': 'qwen-plus', - 'api_key': 'test-api-key', # 测试用假密钥 - 'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1', - 'max_discount_percent': 10, - 'max_discount_amount': 100, - 'max_bargain_rounds': 3, - 'custom_prompts': '' - } - - success = db_manager.save_ai_reply_settings(test_cookie_id, ai_settings) - return test_cookie_id if success else None - -def test_settings_variable_scope(): - """测试settings变量作用域问题""" - print("🔧 测试settings变量作用域修复...") - - test_cookie_id = setup_test_account() - if not test_cookie_id: - print(" ❌ 测试账号设置失败") - return False - - # 测试数据 - test_item_info = { - 'title': '测试商品', - 'price': 100, - 'desc': '测试商品描述' - } - - test_chat_id = "test_chat_fix_001" - - # 清理测试数据 - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute('DELETE FROM ai_conversations WHERE cookie_id = ? AND chat_id = ?', - (test_cookie_id, test_chat_id)) - db_manager.conn.commit() - except: - pass - - print(f" 测试账号: {test_cookie_id}") - print(f" 测试对话: {test_chat_id}") - - # 测试1: 普通消息(非议价) - print(f"\n1️⃣ 测试普通消息处理...") - try: - reply = ai_reply_engine.generate_reply( - message="你好", - item_info=test_item_info, - chat_id=test_chat_id, - cookie_id=test_cookie_id, - user_id="test_user", - item_id="test_item" - ) - - # 由于使用测试API密钥,预期会失败,但不应该出现settings变量错误 - print(f" 普通消息测试完成(预期API调用失败)") - - except Exception as e: - error_msg = str(e) - if "cannot access local variable 'settings'" in error_msg: - print(f" ❌ settings变量作用域问题仍然存在: {error_msg}") - return False - else: - print(f" ✅ settings变量作用域问题已修复(其他错误: {error_msg[:50]}...)") - - # 测试2: 议价消息 - print(f"\n2️⃣ 测试议价消息处理...") - try: - # 先添加一些议价记录,测试轮数限制逻辑 - for i in range(3): # 添加3轮议价记录 - ai_reply_engine.save_conversation( - chat_id=test_chat_id, - cookie_id=test_cookie_id, - user_id="test_user", - item_id="test_item", - role="user", - content=f"第{i+1}次议价", - intent="price" - ) - - # 现在测试第4轮议价(应该被拒绝) - reply = ai_reply_engine.generate_reply( - message="能再便宜点吗?", - item_info=test_item_info, - chat_id=test_chat_id, - cookie_id=test_cookie_id, - user_id="test_user", - item_id="test_item" - ) - - if reply and "不能再便宜" in reply: - print(f" ✅ 议价轮数限制正常工作: {reply}") - else: - print(f" ⚠️ 议价消息处理完成,但结果可能不符合预期") - - except Exception as e: - error_msg = str(e) - if "cannot access local variable 'settings'" in error_msg: - print(f" ❌ settings变量作用域问题仍然存在: {error_msg}") - return False - else: - print(f" ✅ settings变量作用域问题已修复(其他错误: {error_msg[:50]}...)") - - # 测试3: 验证settings获取 - print(f"\n3️⃣ 测试settings获取...") - try: - settings = db_manager.get_ai_reply_settings(test_cookie_id) - print(f" ✅ settings获取成功:") - print(f" AI启用: {settings.get('ai_enabled')}") - print(f" 最大议价轮数: {settings.get('max_bargain_rounds')}") - print(f" 最大优惠百分比: {settings.get('max_discount_percent')}%") - - except Exception as e: - print(f" ❌ settings获取失败: {e}") - return False - - return True - -def main(): - """主测试函数""" - print("🚀 AI回复settings变量修复验证") - print("=" * 50) - - # 测试修复 - fix_ok = test_settings_variable_scope() - - if fix_ok: - print("\n" + "=" * 50) - print("🎉 修复验证成功!") - print("\n✅ 修复内容:") - print(" • settings变量作用域问题已解决") - print(" • 议价轮数限制功能正常") - print(" • AI回复流程完整") - print("\n💡 说明:") - print(" • 由于使用测试API密钥,AI调用会失败") - print(" • 但不会再出现settings变量错误") - print(" • 配置真实API密钥后即可正常使用") - else: - print("\n❌ 修复验证失败,请检查代码") - -if __name__ == "__main__": - main() diff --git a/test_backup_import.py b/test_backup_import.py deleted file mode 100644 index 7ced03a..0000000 --- a/test_backup_import.py +++ /dev/null @@ -1,282 +0,0 @@ -#!/usr/bin/env python3 -""" -备份和导入功能测试脚本 -验证所有表是否正确包含在备份中 -""" - -import asyncio -import sys -import os -import json -import tempfile - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from db_manager import db_manager -from loguru import logger - -def get_all_tables(): - """获取数据库中的所有表""" - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") - tables = [row[0] for row in cursor.fetchall()] - return sorted(tables) - except Exception as e: - logger.error(f"获取表列表失败: {e}") - return [] - -def get_table_row_count(table_name): - """获取表的行数""" - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute(f"SELECT COUNT(*) FROM {table_name}") - return cursor.fetchone()[0] - except Exception as e: - logger.error(f"获取表 {table_name} 行数失败: {e}") - return 0 - -def create_test_data(): - """创建测试数据""" - print("📝 创建测试数据...") - - test_data_created = [] - - try: - # 1. 创建测试账号 - test_cookie_id = "test_backup_001" - success = db_manager.save_cookie(test_cookie_id, "test_cookie_value_for_backup") - if success: - test_data_created.append(f"账号: {test_cookie_id}") - - # 2. 创建关键词 - keywords = [("测试关键词1", "测试回复1"), ("测试关键词2", "测试回复2")] - success = db_manager.save_keywords(test_cookie_id, keywords) - if success: - test_data_created.append(f"关键词: {len(keywords)} 个") - - # 3. 创建AI回复设置 - ai_settings = { - 'ai_enabled': True, - 'model_name': 'qwen-plus', - 'api_key': 'test-backup-key', - 'base_url': 'https://test.com', - 'max_discount_percent': 10, - 'max_discount_amount': 100, - 'max_bargain_rounds': 3, - 'custom_prompts': '{"test": "prompt"}' - } - success = db_manager.save_ai_reply_settings(test_cookie_id, ai_settings) - if success: - test_data_created.append("AI回复设置") - - # 4. 创建默认回复 - success = db_manager.save_default_reply(test_cookie_id, True, "测试默认回复内容") - if success: - test_data_created.append("默认回复") - - # 5. 创建商品信息 - success = db_manager.save_item_basic_info( - test_cookie_id, "test_item_001", - "测试商品", "测试描述", "测试分类", "100", "测试详情" - ) - if success: - test_data_created.append("商品信息") - - print(f" ✅ 测试数据创建成功: {', '.join(test_data_created)}") - return True - - except Exception as e: - print(f" ❌ 创建测试数据失败: {e}") - return False - -def test_backup_export(): - """测试备份导出功能""" - print("\n📤 测试备份导出功能...") - - try: - # 获取所有表 - all_tables = get_all_tables() - print(f" 数据库中的表: {all_tables}") - - # 导出备份 - backup_data = db_manager.export_backup() - - if not backup_data: - print(" ❌ 备份导出失败") - return None - - # 检查备份数据结构 - print(f" ✅ 备份导出成功") - print(f" 备份版本: {backup_data.get('version')}") - print(f" 备份时间: {backup_data.get('timestamp')}") - - # 检查包含的表 - backed_up_tables = list(backup_data['data'].keys()) - print(f" 备份的表: {sorted(backed_up_tables)}") - - # 检查是否有遗漏的表 - missing_tables = set(all_tables) - set(backed_up_tables) - if missing_tables: - print(f" ⚠️ 未备份的表: {sorted(missing_tables)}") - else: - print(f" ✅ 所有表都已备份") - - # 检查每个表的数据量 - print(f"\n 📊 各表数据统计:") - for table in sorted(backed_up_tables): - row_count = len(backup_data['data'][table]['rows']) - print(f" {table}: {row_count} 行") - - return backup_data - - except Exception as e: - print(f" ❌ 备份导出异常: {e}") - return None - -def test_backup_import(backup_data): - """测试备份导入功能""" - print("\n📥 测试备份导入功能...") - - if not backup_data: - print(" ❌ 没有备份数据可导入") - return False - - try: - # 记录导入前的数据量 - print(" 📊 导入前数据统计:") - all_tables = get_all_tables() - before_counts = {} - for table in all_tables: - count = get_table_row_count(table) - before_counts[table] = count - print(f" {table}: {count} 行") - - # 执行导入 - success = db_manager.import_backup(backup_data) - - if not success: - print(" ❌ 备份导入失败") - return False - - print(" ✅ 备份导入成功") - - # 记录导入后的数据量 - print("\n 📊 导入后数据统计:") - after_counts = {} - for table in all_tables: - count = get_table_row_count(table) - after_counts[table] = count - print(f" {table}: {count} 行") - - # 检查数据一致性 - print("\n 🔍 数据一致性检查:") - for table in sorted(backup_data['data'].keys()): - expected_count = len(backup_data['data'][table]['rows']) - actual_count = after_counts.get(table, 0) - - if table == 'system_settings': - # 系统设置表可能保留管理员密码,所以数量可能不完全一致 - print(f" {table}: 期望 {expected_count}, 实际 {actual_count} (系统设置表)") - elif expected_count == actual_count: - print(f" {table}: ✅ 一致 ({actual_count} 行)") - else: - print(f" {table}: ❌ 不一致 (期望 {expected_count}, 实际 {actual_count})") - - return True - - except Exception as e: - print(f" ❌ 备份导入异常: {e}") - return False - -def test_backup_file_operations(): - """测试备份文件操作""" - print("\n💾 测试备份文件操作...") - - try: - # 导出备份 - backup_data = db_manager.export_backup() - if not backup_data: - print(" ❌ 导出备份失败") - return False - - # 保存到临时文件 - with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f: - json.dump(backup_data, f, indent=2, ensure_ascii=False) - temp_file = f.name - - print(f" ✅ 备份保存到临时文件: {temp_file}") - - # 从文件读取 - with open(temp_file, 'r', encoding='utf-8') as f: - loaded_backup = json.load(f) - - print(f" ✅ 从文件读取备份成功") - - # 验证数据完整性 - if loaded_backup == backup_data: - print(f" ✅ 文件数据完整性验证通过") - else: - print(f" ❌ 文件数据完整性验证失败") - return False - - # 清理临时文件 - os.unlink(temp_file) - print(f" ✅ 临时文件清理完成") - - return True - - except Exception as e: - print(f" ❌ 备份文件操作异常: {e}") - return False - -def main(): - """主测试函数""" - print("🚀 备份和导入功能测试开始") - print("=" * 50) - - # 创建测试数据 - data_ok = create_test_data() - if not data_ok: - print("\n❌ 测试数据创建失败") - return - - # 测试备份导出 - backup_data = test_backup_export() - if not backup_data: - print("\n❌ 备份导出测试失败") - return - - # 测试备份导入 - import_ok = test_backup_import(backup_data) - if not import_ok: - print("\n❌ 备份导入测试失败") - return - - # 测试文件操作 - file_ok = test_backup_file_operations() - if not file_ok: - print("\n❌ 备份文件操作测试失败") - return - - print("\n" + "=" * 50) - print("🎉 所有测试通过!备份和导入功能正常!") - print("\n✅ 功能验证:") - print(" • 所有13个表都包含在备份中") - print(" • 备份导出功能正常") - print(" • 备份导入功能正常") - print(" • 数据完整性保持") - print(" • 文件操作正常") - print("\n📋 包含的表:") - - # 显示所有备份的表 - if backup_data and 'data' in backup_data: - for table in sorted(backup_data['data'].keys()): - row_count = len(backup_data['data'][table]['rows']) - print(f" • {table}: {row_count} 行数据") - -if __name__ == "__main__": - main() diff --git a/test_bargain_limit.py b/test_bargain_limit.py deleted file mode 100644 index f73e9bd..0000000 --- a/test_bargain_limit.py +++ /dev/null @@ -1,267 +0,0 @@ -#!/usr/bin/env python3 -""" -议价轮数限制功能测试脚本 -用于验证最大议价轮数是否生效 -""" - -import asyncio -import sys -import os -import time - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from ai_reply_engine import ai_reply_engine -from db_manager import db_manager -from loguru import logger - -def setup_test_account(): - """设置测试账号的AI回复配置""" - print("⚙️ 设置测试账号配置...") - - test_cookie_id = "test_bargain_001" - - # 配置AI回复设置 - ai_settings = { - 'ai_enabled': True, - 'model_name': 'qwen-plus', - 'api_key': 'test-api-key-for-bargain-test', # 测试用的假密钥 - 'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1', - 'max_discount_percent': 15, # 最大优惠15% - 'max_discount_amount': 50, # 最大优惠50元 - 'max_bargain_rounds': 3, # 最大议价3轮 - 'custom_prompts': '' - } - - try: - success = db_manager.save_ai_reply_settings(test_cookie_id, ai_settings) - if success: - print(f" ✅ 测试账号配置成功") - print(f" 账号ID: {test_cookie_id}") - print(f" 最大议价轮数: {ai_settings['max_bargain_rounds']}") - print(f" 最大优惠百分比: {ai_settings['max_discount_percent']}%") - print(f" 最大优惠金额: {ai_settings['max_discount_amount']}元") - return test_cookie_id - else: - print(f" ❌ 测试账号配置失败") - return None - except Exception as e: - print(f" ❌ 配置异常: {e}") - return None - -def clear_test_conversations(cookie_id: str, chat_id: str): - """清理测试对话记录""" - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute(''' - DELETE FROM ai_conversations - WHERE cookie_id = ? AND chat_id = ? - ''', (cookie_id, chat_id)) - db_manager.conn.commit() - print(f" ✅ 清理对话记录成功") - except Exception as e: - print(f" ❌ 清理对话记录失败: {e}") - -def test_bargain_count_tracking(): - """测试议价次数统计""" - print("\n📊 测试议价次数统计...") - - test_cookie_id = "test_bargain_001" - test_chat_id = "test_chat_bargain_001" - - # 清理测试数据 - clear_test_conversations(test_cookie_id, test_chat_id) - - # 模拟保存几条议价对话 - test_conversations = [ - ("user", "能便宜点吗?", "price"), - ("assistant", "可以优惠5元", "price"), - ("user", "再便宜点呢?", "price"), - ("assistant", "最多优惠10元", "price"), - ("user", "还能再便宜吗?", "price"), - ("assistant", "这已经是最低价了", "price"), - ] - - print(f"\n1️⃣ 模拟保存对话记录...") - try: - for i, (role, content, intent) in enumerate(test_conversations): - ai_reply_engine.save_conversation( - chat_id=test_chat_id, - cookie_id=test_cookie_id, - user_id="test_user_001", - item_id="test_item_001", - role=role, - content=content, - intent=intent - ) - print(f" 保存第{i+1}条: {role} - {content}") - except Exception as e: - print(f" ❌ 保存对话记录失败: {e}") - return False - - print(f"\n2️⃣ 测试议价次数统计...") - try: - bargain_count = ai_reply_engine.get_bargain_count(test_chat_id, test_cookie_id) - expected_count = 3 # 3条用户的price消息 - - if bargain_count == expected_count: - print(f" ✅ 议价次数统计正确: {bargain_count}") - else: - print(f" ❌ 议价次数统计错误: 期望 {expected_count}, 实际 {bargain_count}") - return False - except Exception as e: - print(f" ❌ 议价次数统计异常: {e}") - return False - - return True - -def test_bargain_limit_logic(): - """测试议价轮数限制逻辑""" - print("\n🚫 测试议价轮数限制逻辑...") - - test_cookie_id = "test_bargain_001" - test_chat_id = "test_chat_limit_001" - - # 清理测试数据 - clear_test_conversations(test_cookie_id, test_chat_id) - - # 获取配置 - settings = db_manager.get_ai_reply_settings(test_cookie_id) - max_rounds = settings.get('max_bargain_rounds', 3) - - print(f" 配置的最大议价轮数: {max_rounds}") - - # 模拟达到最大议价轮数 - print(f"\n1️⃣ 模拟 {max_rounds} 轮议价...") - for i in range(max_rounds): - try: - ai_reply_engine.save_conversation( - chat_id=test_chat_id, - cookie_id=test_cookie_id, - user_id="test_user_001", - item_id="test_item_001", - role="user", - content=f"第{i+1}次议价:能便宜点吗?", - intent="price" - ) - print(f" 第{i+1}轮议价记录已保存") - except Exception as e: - print(f" ❌ 保存第{i+1}轮议价失败: {e}") - return False - - # 验证议价次数 - print(f"\n2️⃣ 验证当前议价次数...") - try: - current_count = ai_reply_engine.get_bargain_count(test_chat_id, test_cookie_id) - print(f" 当前议价次数: {current_count}") - - if current_count >= max_rounds: - print(f" ✅ 已达到最大议价轮数限制") - else: - print(f" ❌ 未达到最大议价轮数") - return False - except Exception as e: - print(f" ❌ 验证议价次数异常: {e}") - return False - - # 测试超出限制时的逻辑(模拟) - print(f"\n3️⃣ 测试超出限制时的逻辑...") - try: - # 直接测试议价轮数检查逻辑 - current_count = ai_reply_engine.get_bargain_count(test_chat_id, test_cookie_id) - settings = db_manager.get_ai_reply_settings(test_cookie_id) - max_rounds = settings.get('max_bargain_rounds', 3) - - print(f" 当前议价次数: {current_count}") - print(f" 最大议价轮数: {max_rounds}") - - if current_count >= max_rounds: - print(f" ✅ 检测到议价次数已达上限") - print(f" ✅ 系统应该拒绝继续议价") - - # 模拟拒绝回复 - refuse_reply = f"抱歉,这个价格已经是最优惠的了,不能再便宜了哦!" - print(f" ✅ 拒绝回复示例: {refuse_reply}") - else: - print(f" ❌ 议价次数检查逻辑错误") - return False - - except Exception as e: - print(f" ❌ 测试超出限制逻辑异常: {e}") - return False - - return True - -def test_bargain_settings_integration(): - """测试议价设置集成""" - print("\n🔧 测试议价设置集成...") - - test_cookie_id = "test_bargain_001" - - # 获取设置 - try: - settings = db_manager.get_ai_reply_settings(test_cookie_id) - - print(f" AI回复启用: {settings.get('ai_enabled', False)}") - print(f" 最大议价轮数: {settings.get('max_bargain_rounds', 3)}") - print(f" 最大优惠百分比: {settings.get('max_discount_percent', 10)}%") - print(f" 最大优惠金额: {settings.get('max_discount_amount', 100)}元") - - # 验证设置是否正确 - if settings.get('max_bargain_rounds') == 3: - print(f" ✅ 议价设置读取正确") - else: - print(f" ❌ 议价设置读取错误") - return False - - except Exception as e: - print(f" ❌ 获取议价设置异常: {e}") - return False - - return True - -async def main(): - """主测试函数""" - print("🚀 议价轮数限制功能测试开始") - print("=" * 50) - - # 设置测试账号 - test_cookie_id = setup_test_account() - if not test_cookie_id: - print("\n❌ 测试账号设置失败") - return - - # 测试议价设置集成 - settings_ok = test_bargain_settings_integration() - if not settings_ok: - print("\n❌ 议价设置集成测试失败") - return - - # 测试议价次数统计 - count_ok = test_bargain_count_tracking() - if not count_ok: - print("\n❌ 议价次数统计测试失败") - return - - # 测试议价轮数限制 - limit_ok = test_bargain_limit_logic() - if not limit_ok: - print("\n❌ 议价轮数限制测试失败") - return - - print("\n" + "=" * 50) - print("🎉 所有测试通过!最大议价轮数功能正常!") - print("\n📋 功能说明:") - print("1. ✅ 议价次数统计:正确统计用户的议价消息数量") - print("2. ✅ 轮数限制检查:达到最大轮数时拒绝继续议价") - print("3. ✅ 拒绝回复生成:超出限制时返回友好的拒绝消息") - print("4. ✅ 设置参数传递:AI可以获取到完整的议价设置") - print("\n💡 使用建议:") - print("- 合理设置最大议价轮数(建议3-5轮)") - print("- 配合最大优惠百分比和金额使用") - print("- 在提示词中强调议价策略") - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/test_bargain_limit_direct.py b/test_bargain_limit_direct.py deleted file mode 100644 index b6f0c54..0000000 --- a/test_bargain_limit_direct.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python3 -""" -直接测试议价轮数限制功能 -不依赖真实API调用,直接测试逻辑 -""" - -import asyncio -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from ai_reply_engine import ai_reply_engine -from db_manager import db_manager - -class MockAIReplyEngine: - """模拟AI回复引擎,用于测试议价轮数限制""" - - def __init__(self): - self.ai_engine = ai_reply_engine - - def test_bargain_limit_logic(self, cookie_id: str, chat_id: str, message: str, - item_info: dict, user_id: str, item_id: str): - """直接测试议价轮数限制逻辑""" - try: - # 1. 获取AI回复设置 - settings = db_manager.get_ai_reply_settings(cookie_id) - print(f" 获取设置成功: 最大议价轮数 {settings.get('max_bargain_rounds', 3)}") - - # 2. 模拟意图检测为price - intent = "price" - print(f" 模拟意图检测: {intent}") - - # 3. 获取议价次数 - bargain_count = self.ai_engine.get_bargain_count(chat_id, cookie_id) - print(f" 当前议价次数: {bargain_count}") - - # 4. 检查议价轮数限制 - max_bargain_rounds = settings.get('max_bargain_rounds', 3) - if bargain_count >= max_bargain_rounds: - print(f" 🚫 议价次数已达上限 ({bargain_count}/{max_bargain_rounds}),拒绝继续议价") - # 返回拒绝议价的回复 - refuse_reply = f"抱歉,这个价格已经是最优惠的了,不能再便宜了哦!" - # 保存对话记录 - self.ai_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "user", message, intent) - self.ai_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "assistant", refuse_reply, intent) - return refuse_reply - else: - print(f" ✅ 议价次数未达上限,可以继续议价") - # 模拟AI回复 - mock_reply = f"好的,我们可以优惠一点,这是第{bargain_count + 1}轮议价" - # 保存对话记录 - self.ai_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "user", message, intent) - self.ai_engine.save_conversation(chat_id, cookie_id, user_id, item_id, "assistant", mock_reply, intent) - return mock_reply - - except Exception as e: - print(f" ❌ 测试异常: {e}") - return None - -def test_complete_bargain_flow(): - """测试完整的议价流程""" - print("🎯 测试完整议价流程...") - - # 测试参数 - test_cookie_id = "test_bargain_flow_001" - test_chat_id = "test_chat_flow_001" - - # 设置测试账号 - ai_settings = { - 'ai_enabled': True, - 'model_name': 'qwen-plus', - 'api_key': 'test-key', - 'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1', - 'max_discount_percent': 15, - 'max_discount_amount': 200, - 'max_bargain_rounds': 3, # 设置最大3轮 - 'custom_prompts': '' - } - - db_manager.save_ai_reply_settings(test_cookie_id, ai_settings) - - # 清理测试数据 - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute('DELETE FROM ai_conversations WHERE cookie_id = ? AND chat_id = ?', - (test_cookie_id, test_chat_id)) - db_manager.conn.commit() - except: - pass - - # 创建模拟引擎 - mock_engine = MockAIReplyEngine() - - # 测试商品信息 - item_info = { - 'title': '测试商品', - 'price': 1000, - 'desc': '这是一个测试商品' - } - - # 模拟议价对话 - bargain_messages = [ - "能便宜点吗?", - "800元行不行?", - "900元怎么样?", - "850元,最后一次了" # 这一轮应该被拒绝 - ] - - print(f"\n📋 测试设置:") - print(f" 账号ID: {test_cookie_id}") - print(f" 最大议价轮数: {ai_settings['max_bargain_rounds']}") - print(f" 商品价格: ¥{item_info['price']}") - - print(f"\n💬 开始议价测试:") - print("-" * 40) - - for i, message in enumerate(bargain_messages, 1): - print(f"\n第{i}轮议价:") - print(f"👤 用户: {message}") - - # 测试议价逻辑 - reply = mock_engine.test_bargain_limit_logic( - cookie_id=test_cookie_id, - chat_id=test_chat_id, - message=message, - item_info=item_info, - user_id="test_user", - item_id="test_item" - ) - - if reply: - print(f"🤖 AI回复: {reply}") - - # 检查是否是拒绝回复 - if "不能再便宜" in reply: - print(f"✋ 议价被拒绝,测试结束") - break - else: - print(f"❌ 回复生成失败") - break - - # 最终统计 - print(f"\n📊 最终统计:") - final_count = ai_reply_engine.get_bargain_count(test_chat_id, test_cookie_id) - max_rounds = ai_settings['max_bargain_rounds'] - print(f" 实际议价轮数: {final_count}") - print(f" 最大允许轮数: {max_rounds}") - print(f" 是否达到限制: {'是' if final_count >= max_rounds else '否'}") - - return final_count >= max_rounds - -def main(): - """主测试函数""" - print("🚀 议价轮数限制直接测试") - print("=" * 50) - - # 测试完整流程 - limit_works = test_complete_bargain_flow() - - print("\n" + "=" * 50) - if limit_works: - print("🎉 议价轮数限制功能正常工作!") - print("\n✅ 验证结果:") - print(" • settings变量作用域问题已修复") - print(" • 议价次数统计准确") - print(" • 轮数限制逻辑正确") - print(" • 拒绝回复生成正常") - print(" • 对话记录保存完整") - - print("\n🎯 功能特点:") - print(" • 在AI API调用前检查轮数限制") - print(" • 超出限制时直接返回拒绝回复") - print(" • 节省API调用成本") - print(" • 保持用户体验友好") - else: - print("❌ 议价轮数限制功能异常") - print(" 请检查代码实现") - -if __name__ == "__main__": - main() diff --git a/test_cache_refresh.py b/test_cache_refresh.py deleted file mode 100644 index db3f767..0000000 --- a/test_cache_refresh.py +++ /dev/null @@ -1,202 +0,0 @@ -#!/usr/bin/env python3 -""" -测试缓存刷新功能 -验证备份导入后关键字数据是否能正确刷新 -""" - -import json -import time -import asyncio -from db_manager import db_manager -import cookie_manager as cm - -def test_cache_refresh(): - """测试缓存刷新功能""" - print("🧪 测试缓存刷新功能") - print("=" * 50) - - # 1. 创建测试数据 - print("\n1️⃣ 创建测试数据...") - test_cookie_id = "test_cache_refresh" - test_cookie_value = "test_cookie_value_123" - test_keywords = [ - ("测试关键字1", "测试回复1"), - ("测试关键字2", "测试回复2") - ] - - # 保存到数据库 - db_manager.save_cookie(test_cookie_id, test_cookie_value) - db_manager.save_keywords(test_cookie_id, test_keywords) - print(f" ✅ 已保存测试账号: {test_cookie_id}") - print(f" ✅ 已保存 {len(test_keywords)} 个关键字") - - # 2. 创建 CookieManager 并加载数据 - print("\n2️⃣ 创建 CookieManager...") - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - manager = cm.CookieManager(loop) - print(f" ✅ CookieManager 已创建") - print(f" 📊 加载的关键字: {manager.keywords.get(test_cookie_id, [])}") - - # 3. 直接修改数据库(模拟备份导入) - print("\n3️⃣ 模拟备份导入(直接修改数据库)...") - new_keywords = [ - ("新关键字1", "新回复1"), - ("新关键字2", "新回复2"), - ("新关键字3", "新回复3") - ] - db_manager.save_keywords(test_cookie_id, new_keywords) - print(f" ✅ 数据库已更新为 {len(new_keywords)} 个新关键字") - - # 4. 检查 CookieManager 缓存(应该还是旧数据) - print("\n4️⃣ 检查 CookieManager 缓存...") - cached_keywords = manager.keywords.get(test_cookie_id, []) - print(f" 📊 缓存中的关键字: {cached_keywords}") - - if len(cached_keywords) == len(test_keywords): - print(" ✅ 确认:缓存中仍是旧数据(符合预期)") - else: - print(" ❌ 意外:缓存已更新(不符合预期)") - - # 5. 调用刷新方法 - print("\n5️⃣ 调用缓存刷新方法...") - success = manager.reload_from_db() - print(f" 刷新结果: {success}") - - # 6. 检查刷新后的缓存 - print("\n6️⃣ 检查刷新后的缓存...") - refreshed_keywords = manager.keywords.get(test_cookie_id, []) - print(f" 📊 刷新后的关键字: {refreshed_keywords}") - - if len(refreshed_keywords) == len(new_keywords): - print(" ✅ 成功:缓存已更新为新数据") - - # 验证内容是否正确 - db_keywords = db_manager.get_keywords(test_cookie_id) - if refreshed_keywords == db_keywords: - print(" ✅ 验证:缓存数据与数据库一致") - else: - print(" ❌ 错误:缓存数据与数据库不一致") - print(f" 缓存: {refreshed_keywords}") - print(f" 数据库: {db_keywords}") - else: - print(" ❌ 失败:缓存未正确更新") - - # 7. 清理测试数据 - print("\n7️⃣ 清理测试数据...") - db_manager.delete_cookie(test_cookie_id) - print(" ✅ 测试数据已清理") - - print("\n" + "=" * 50) - print("🎉 缓存刷新功能测试完成!") - -def test_backup_import_scenario(): - """测试完整的备份导入场景""" - print("\n\n🔄 测试完整备份导入场景") - print("=" * 50) - - # 1. 创建初始数据 - print("\n1️⃣ 创建初始数据...") - initial_data = { - "account1": [("hello", "你好"), ("price", "价格是100元")], - "account2": [("bye", "再见"), ("thanks", "谢谢")] - } - - for cookie_id, keywords in initial_data.items(): - db_manager.save_cookie(cookie_id, f"cookie_value_{cookie_id}") - db_manager.save_keywords(cookie_id, keywords) - - print(f" ✅ 已创建 {len(initial_data)} 个账号的初始数据") - - # 2. 导出备份 - print("\n2️⃣ 导出备份...") - backup_data = db_manager.export_backup() - print(f" ✅ 备份导出成功,包含 {len(backup_data['data'])} 个表") - - # 3. 修改数据(模拟用户操作) - print("\n3️⃣ 修改数据...") - modified_data = { - "account1": [("modified1", "修改后的回复1")], - "account3": [("new", "新账号的回复")] - } - - for cookie_id, keywords in modified_data.items(): - db_manager.save_cookie(cookie_id, f"cookie_value_{cookie_id}") - db_manager.save_keywords(cookie_id, keywords) - - print(" ✅ 数据已修改") - - # 4. 创建 CookieManager(加载修改后的数据) - print("\n4️⃣ 创建 CookieManager...") - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - manager = cm.CookieManager(loop) - print(f" ✅ CookieManager 已创建,加载了修改后的数据") - - # 5. 导入备份(恢复初始数据) - print("\n5️⃣ 导入备份...") - success = db_manager.import_backup(backup_data) - print(f" 导入结果: {success}") - - # 6. 检查 CookieManager 缓存(应该还是修改后的数据) - print("\n6️⃣ 检查导入后的缓存...") - for cookie_id in ["account1", "account2", "account3"]: - cached = manager.keywords.get(cookie_id, []) - db_data = db_manager.get_keywords(cookie_id) - print(f" {cookie_id}:") - print(f" 缓存: {cached}") - print(f" 数据库: {db_data}") - - if cached != db_data: - print(f" ❌ 不一致!需要刷新缓存") - else: - print(f" ✅ 一致") - - # 7. 刷新缓存 - print("\n7️⃣ 刷新缓存...") - manager.reload_from_db() - - # 8. 再次检查 - print("\n8️⃣ 检查刷新后的缓存...") - all_consistent = True - for cookie_id in ["account1", "account2"]: # account3 应该被删除了 - cached = manager.keywords.get(cookie_id, []) - db_data = db_manager.get_keywords(cookie_id) - print(f" {cookie_id}:") - print(f" 缓存: {cached}") - print(f" 数据库: {db_data}") - - if cached != db_data: - print(f" ❌ 仍然不一致!") - all_consistent = False - else: - print(f" ✅ 一致") - - # 检查 account3 是否被正确删除 - if "account3" not in manager.keywords: - print(" ✅ account3 已从缓存中删除") - else: - print(" ❌ account3 仍在缓存中") - all_consistent = False - - # 9. 清理 - print("\n9️⃣ 清理测试数据...") - for cookie_id in ["account1", "account2", "account3"]: - db_manager.delete_cookie(cookie_id) - - print("\n" + "=" * 50) - if all_consistent: - print("🎉 备份导入场景测试成功!") - else: - print("❌ 备份导入场景测试失败!") - -if __name__ == "__main__": - try: - test_cache_refresh() - test_backup_import_scenario() - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_captcha.png b/test_captcha.png deleted file mode 100644 index 0dd14aa..0000000 Binary files a/test_captcha.png and /dev/null differ diff --git a/test_captcha_system.py b/test_captcha_system.py deleted file mode 100644 index 10a2580..0000000 --- a/test_captcha_system.py +++ /dev/null @@ -1,240 +0,0 @@ -#!/usr/bin/env python3 -""" -图形验证码系统测试 -""" - -import requests -import json -import sqlite3 -import base64 -from io import BytesIO -from PIL import Image - -def test_captcha_generation(): - """测试图形验证码生成""" - print("🧪 测试图形验证码生成") - print("-" * 40) - - session_id = "test_session_123" - - # 1. 生成图形验证码 - print("1️⃣ 生成图形验证码...") - response = requests.post('http://localhost:8080/generate-captcha', - json={'session_id': session_id}) - - print(f" 状态码: {response.status_code}") - - if response.status_code == 200: - result = response.json() - print(f" 成功: {result['success']}") - print(f" 消息: {result['message']}") - - if result['success']: - captcha_image = result['captcha_image'] - print(f" 图片数据长度: {len(captcha_image)}") - - # 保存图片到文件(用于调试) - if captcha_image.startswith('data:image/png;base64,'): - image_data = captcha_image.split(',')[1] - image_bytes = base64.b64decode(image_data) - - with open('test_captcha.png', 'wb') as f: - f.write(image_bytes) - print(" ✅ 图片已保存为 test_captcha.png") - - # 从数据库获取验证码文本 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id,)) - result = cursor.fetchone() - if result: - captcha_text = result[0] - print(f" 验证码文本: {captcha_text}") - conn.close() - return session_id, captcha_text - conn.close() - else: - print(" ❌ 图形验证码生成失败") - else: - print(f" ❌ 请求失败: {response.text}") - - return None, None - -def test_captcha_verification(session_id, captcha_text): - """测试图形验证码验证""" - print("\n🧪 测试图形验证码验证") - print("-" * 40) - - # 2. 验证正确的验证码 - print("2️⃣ 验证正确的验证码...") - response = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': session_id, - 'captcha_code': captcha_text - }) - - print(f" 状态码: {response.status_code}") - if response.status_code == 200: - result = response.json() - print(f" 成功: {result['success']}") - print(f" 消息: {result['message']}") - - if result['success']: - print(" ✅ 正确验证码验证成功") - else: - print(" ❌ 正确验证码验证失败") - - # 3. 验证错误的验证码 - print("\n3️⃣ 验证错误的验证码...") - response = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': session_id, - 'captcha_code': 'WRONG' - }) - - print(f" 状态码: {response.status_code}") - if response.status_code == 200: - result = response.json() - print(f" 成功: {result['success']}") - print(f" 消息: {result['message']}") - - if not result['success']: - print(" ✅ 错误验证码被正确拒绝") - else: - print(" ❌ 错误验证码验证成功(不应该)") - -def test_captcha_expiry(): - """测试图形验证码过期""" - print("\n🧪 测试图形验证码过期") - print("-" * 40) - - # 直接在数据库中插入过期的验证码 - import time - expired_session = "expired_session_123" - expired_time = time.time() - 3600 # 1小时前 - - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute(''' - INSERT INTO captcha_codes (session_id, code, expires_at) - VALUES (?, ?, ?) - ''', (expired_session, 'EXPIRED', expired_time)) - conn.commit() - conn.close() - - print("4️⃣ 验证过期的验证码...") - response = requests.post('http://localhost:8080/verify-captcha', - json={ - 'session_id': expired_session, - 'captcha_code': 'EXPIRED' - }) - - print(f" 状态码: {response.status_code}") - if response.status_code == 200: - result = response.json() - print(f" 成功: {result['success']}") - print(f" 消息: {result['message']}") - - if not result['success']: - print(" ✅ 过期验证码被正确拒绝") - else: - print(" ❌ 过期验证码验证成功(不应该)") - -def test_database_cleanup(): - """测试数据库清理""" - print("\n🧪 测试数据库清理") - print("-" * 40) - - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 清理测试数据 - cursor.execute('DELETE FROM captcha_codes WHERE session_id LIKE "test%" OR session_id LIKE "expired%"') - deleted_count = cursor.rowcount - conn.commit() - conn.close() - - print(f"5️⃣ 清理测试数据: 删除了 {deleted_count} 条记录") - print(" ✅ 数据库清理完成") - -def test_frontend_integration(): - """测试前端集成""" - print("\n🧪 测试前端集成") - print("-" * 40) - - # 测试注册页面是否可以访问 - print("6️⃣ 测试注册页面...") - response = requests.get('http://localhost:8080/register.html') - - print(f" 状态码: {response.status_code}") - if response.status_code == 200: - content = response.text - - # 检查是否包含图形验证码相关元素 - checks = [ - ('captchaCode', '图形验证码输入框'), - ('captchaImage', '图形验证码图片'), - ('refreshCaptcha', '刷新验证码函数'), - ('verifyCaptcha', '验证验证码函数'), - ('loadCaptcha', '加载验证码函数') - ] - - for check_item, description in checks: - if check_item in content: - print(f" ✅ {description}: 存在") - else: - print(f" ❌ {description}: 缺失") - - print(" ✅ 注册页面加载成功") - else: - print(f" ❌ 注册页面加载失败: {response.status_code}") - -def main(): - """主测试函数""" - print("🚀 图形验证码系统测试") - print("=" * 60) - - try: - # 测试图形验证码生成 - session_id, captcha_text = test_captcha_generation() - - if session_id and captcha_text: - # 测试图形验证码验证 - test_captcha_verification(session_id, captcha_text) - - # 测试验证码过期 - test_captcha_expiry() - - # 测试前端集成 - test_frontend_integration() - - # 清理测试数据 - test_database_cleanup() - - print("\n" + "=" * 60) - print("🎉 图形验证码系统测试完成!") - - print("\n📋 测试总结:") - print("✅ 图形验证码生成功能正常") - print("✅ 图形验证码验证功能正常") - print("✅ 过期验证码处理正常") - print("✅ 前端页面集成正常") - print("✅ 数据库操作正常") - - print("\n💡 下一步:") - print("1. 访问 http://localhost:8080/register.html") - print("2. 测试图形验证码功能") - print("3. 验证邮箱验证码发送需要先通过图形验证码") - print("4. 完成用户注册流程") - - except Exception as e: - print(f"\n❌ 测试失败: {e}") - import traceback - traceback.print_exc() - return False - - return True - -if __name__ == "__main__": - main() diff --git a/test_complete_isolation.py b/test_complete_isolation.py deleted file mode 100644 index 7bdf02f..0000000 --- a/test_complete_isolation.py +++ /dev/null @@ -1,347 +0,0 @@ -#!/usr/bin/env python3 -""" -完整的多用户数据隔离测试 -""" - -import requests -import json -import time -import sqlite3 -from loguru import logger - -BASE_URL = "http://localhost:8080" - -def create_test_users(): - """创建测试用户""" - logger.info("创建测试用户...") - - users = [ - {"username": "testuser1", "email": "user1@test.com", "password": "test123456"}, - {"username": "testuser2", "email": "user2@test.com", "password": "test123456"} - ] - - created_users = [] - - for user in users: - try: - # 清理可能存在的用户 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('DELETE FROM users WHERE username = ? OR email = ?', (user['username'], user['email'])) - cursor.execute('DELETE FROM email_verifications WHERE email = ?', (user['email'],)) - conn.commit() - conn.close() - - # 生成验证码 - session_id = f"test_{user['username']}_{int(time.time())}" - - # 生成图形验证码 - captcha_response = requests.post(f"{BASE_URL}/generate-captcha", - json={'session_id': session_id}) - if not captcha_response.json()['success']: - logger.error(f"图形验证码生成失败: {user['username']}") - continue - - # 获取图形验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id,)) - captcha_result = cursor.fetchone() - conn.close() - - if not captcha_result: - logger.error(f"无法获取图形验证码: {user['username']}") - continue - - captcha_code = captcha_result[0] - - # 验证图形验证码 - verify_response = requests.post(f"{BASE_URL}/verify-captcha", - json={'session_id': session_id, 'captcha_code': captcha_code}) - if not verify_response.json()['success']: - logger.error(f"图形验证码验证失败: {user['username']}") - continue - - # 发送邮箱验证码 - email_response = requests.post(f"{BASE_URL}/send-verification-code", - json={'email': user['email'], 'session_id': session_id}) - if not email_response.json()['success']: - logger.error(f"邮箱验证码发送失败: {user['username']}") - continue - - # 获取邮箱验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM email_verifications WHERE email = ? ORDER BY created_at DESC LIMIT 1', - (user['email'],)) - email_result = cursor.fetchone() - conn.close() - - if not email_result: - logger.error(f"无法获取邮箱验证码: {user['username']}") - continue - - email_code = email_result[0] - - # 注册用户 - register_response = requests.post(f"{BASE_URL}/register", - json={ - 'username': user['username'], - 'email': user['email'], - 'verification_code': email_code, - 'password': user['password'] - }) - - if register_response.json()['success']: - logger.info(f"用户注册成功: {user['username']}") - - # 登录获取token - login_response = requests.post(f"{BASE_URL}/login", - json={'username': user['username'], 'password': user['password']}) - - if login_response.json()['success']: - token = login_response.json()['token'] - user_id = login_response.json()['user_id'] - created_users.append({ - 'username': user['username'], - 'user_id': user_id, - 'token': token, - 'headers': {'Authorization': f'Bearer {token}'} - }) - logger.info(f"用户登录成功: {user['username']}") - else: - logger.error(f"用户登录失败: {user['username']}") - else: - logger.error(f"用户注册失败: {user['username']} - {register_response.json()['message']}") - - except Exception as e: - logger.error(f"创建用户失败: {user['username']} - {e}") - - return created_users - -def test_cards_isolation(users): - """测试卡券管理的用户隔离""" - logger.info("测试卡券管理的用户隔离...") - - if len(users) < 2: - logger.error("需要至少2个用户进行隔离测试") - return False - - user1, user2 = users[0], users[1] - - # 用户1创建卡券 - card1_data = { - "name": "用户1的卡券", - "type": "text", - "text_content": "这是用户1的卡券内容", - "description": "用户1创建的测试卡券" - } - - response1 = requests.post(f"{BASE_URL}/cards", json=card1_data, headers=user1['headers']) - if response1.status_code == 200: - card1_id = response1.json()['id'] - logger.info(f"用户1创建卡券成功: ID={card1_id}") - else: - logger.error(f"用户1创建卡券失败: {response1.text}") - return False - - # 用户2创建卡券 - card2_data = { - "name": "用户2的卡券", - "type": "text", - "text_content": "这是用户2的卡券内容", - "description": "用户2创建的测试卡券" - } - - response2 = requests.post(f"{BASE_URL}/cards", json=card2_data, headers=user2['headers']) - if response2.status_code == 200: - card2_id = response2.json()['id'] - logger.info(f"用户2创建卡券成功: ID={card2_id}") - else: - logger.error(f"用户2创建卡券失败: {response2.text}") - return False - - # 验证用户1只能看到自己的卡券 - response1_list = requests.get(f"{BASE_URL}/cards", headers=user1['headers']) - if response1_list.status_code == 200: - user1_cards = response1_list.json() - user1_card_names = [card['name'] for card in user1_cards] - - if "用户1的卡券" in user1_card_names and "用户2的卡券" not in user1_card_names: - logger.info("✅ 用户1卡券隔离验证通过") - else: - logger.error("❌ 用户1卡券隔离验证失败") - return False - else: - logger.error(f"获取用户1卡券列表失败: {response1_list.text}") - return False - - # 验证用户2只能看到自己的卡券 - response2_list = requests.get(f"{BASE_URL}/cards", headers=user2['headers']) - if response2_list.status_code == 200: - user2_cards = response2_list.json() - user2_card_names = [card['name'] for card in user2_cards] - - if "用户2的卡券" in user2_card_names and "用户1的卡券" not in user2_card_names: - logger.info("✅ 用户2卡券隔离验证通过") - else: - logger.error("❌ 用户2卡券隔离验证失败") - return False - else: - logger.error(f"获取用户2卡券列表失败: {response2_list.text}") - return False - - # 验证跨用户访问被拒绝 - response_cross = requests.get(f"{BASE_URL}/cards/{card2_id}", headers=user1['headers']) - if response_cross.status_code == 403 or response_cross.status_code == 404: - logger.info("✅ 跨用户卡券访问被正确拒绝") - else: - logger.error("❌ 跨用户卡券访问未被拒绝") - return False - - return True - -def test_user_settings(users): - """测试用户设置功能""" - logger.info("测试用户设置功能...") - - if len(users) < 2: - logger.error("需要至少2个用户进行设置测试") - return False - - user1, user2 = users[0], users[1] - - # 用户1设置主题颜色 - setting1_data = {"value": "#ff0000", "description": "用户1的红色主题"} - response1 = requests.put(f"{BASE_URL}/user-settings/theme_color", - json=setting1_data, headers=user1['headers']) - - if response1.status_code == 200: - logger.info("用户1主题颜色设置成功") - else: - logger.error(f"用户1主题颜色设置失败: {response1.text}") - return False - - # 用户2设置主题颜色 - setting2_data = {"value": "#00ff00", "description": "用户2的绿色主题"} - response2 = requests.put(f"{BASE_URL}/user-settings/theme_color", - json=setting2_data, headers=user2['headers']) - - if response2.status_code == 200: - logger.info("用户2主题颜色设置成功") - else: - logger.error(f"用户2主题颜色设置失败: {response2.text}") - return False - - # 验证用户1的设置 - response1_get = requests.get(f"{BASE_URL}/user-settings/theme_color", headers=user1['headers']) - if response1_get.status_code == 200: - user1_color = response1_get.json()['value'] - if user1_color == "#ff0000": - logger.info("✅ 用户1主题颜色隔离验证通过") - else: - logger.error(f"❌ 用户1主题颜色错误: {user1_color}") - return False - else: - logger.error(f"获取用户1主题颜色失败: {response1_get.text}") - return False - - # 验证用户2的设置 - response2_get = requests.get(f"{BASE_URL}/user-settings/theme_color", headers=user2['headers']) - if response2_get.status_code == 200: - user2_color = response2_get.json()['value'] - if user2_color == "#00ff00": - logger.info("✅ 用户2主题颜色隔离验证通过") - else: - logger.error(f"❌ 用户2主题颜色错误: {user2_color}") - return False - else: - logger.error(f"获取用户2主题颜色失败: {response2_get.text}") - return False - - return True - -def cleanup_test_data(users): - """清理测试数据""" - logger.info("清理测试数据...") - - try: - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 清理测试用户 - test_usernames = [user['username'] for user in users] - if test_usernames: - placeholders = ','.join(['?' for _ in test_usernames]) - cursor.execute(f'DELETE FROM users WHERE username IN ({placeholders})', test_usernames) - user_count = cursor.rowcount - else: - user_count = 0 - - # 清理测试卡券 - cursor.execute('DELETE FROM cards WHERE name LIKE "用户%的卡券"') - card_count = cursor.rowcount - - # 清理测试验证码 - cursor.execute('DELETE FROM email_verifications WHERE email LIKE "%@test.com"') - email_count = cursor.rowcount - - cursor.execute('DELETE FROM captcha_codes WHERE session_id LIKE "test_%"') - captcha_count = cursor.rowcount - - conn.commit() - conn.close() - - logger.info(f"清理完成: 用户{user_count}个, 卡券{card_count}个, 邮箱验证码{email_count}个, 图形验证码{captcha_count}个") - - except Exception as e: - logger.error(f"清理失败: {e}") - -def main(): - """主测试函数""" - print("🚀 完整的多用户数据隔离测试") - print("=" * 60) - - try: - # 创建测试用户 - users = create_test_users() - - if len(users) < 2: - print("❌ 测试失败:无法创建足够的测试用户") - return False - - print(f"✅ 成功创建 {len(users)} 个测试用户") - - # 测试卡券管理隔离 - cards_success = test_cards_isolation(users) - - # 测试用户设置 - settings_success = test_user_settings(users) - - # 清理测试数据 - cleanup_test_data(users) - - print("\n" + "=" * 60) - if cards_success and settings_success: - print("🎉 完整的多用户数据隔离测试全部通过!") - - print("\n📋 测试总结:") - print("✅ 卡券管理完全隔离") - print("✅ 用户设置完全隔离") - print("✅ 跨用户访问被正确拒绝") - print("✅ 数据库层面用户绑定正确") - - return True - else: - print("❌ 多用户数据隔离测试失败!") - return False - - except Exception as e: - print(f"💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/test_cookie_log_display.py b/test_cookie_log_display.py deleted file mode 100644 index 1834a30..0000000 --- a/test_cookie_log_display.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python3 -""" -测试Cookie ID在日志中的显示 -""" - -import time -import asyncio -from loguru import logger - -# 模拟多个Cookie的日志输出 -async def test_cookie_log_display(): - """测试Cookie ID在日志中的显示效果""" - - print("🧪 测试Cookie ID日志显示") - print("=" * 50) - - # 模拟不同Cookie的日志输出 - cookies = [ - {"id": "user1_cookie", "name": "用户1的账号"}, - {"id": "user2_cookie", "name": "用户2的账号"}, - {"id": "admin_cookie", "name": "管理员账号"} - ] - - print("📋 模拟多用户系统日志输出:") - print("-" * 50) - - for i, cookie in enumerate(cookies): - cookie_id = cookie["id"] - cookie_name = cookie["name"] - - # 模拟各种类型的日志 - msg_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) - - # 1. Token相关日志 - logger.info(f"【{cookie_id}】开始刷新token...") - await asyncio.sleep(0.1) - logger.info(f"【{cookie_id}】Token刷新成功") - - # 2. 连接相关日志 - logger.info(f"【{cookie_id}】连接注册完成") - - # 3. 系统消息日志 - logger.info(f"[{msg_time}] 【{cookie_id}】【系统】小闲鱼智能提示:") - logger.info(f" - 欢迎使用闲鱼智能助手") - - # 4. 消息处理日志 - logger.info(f"[{msg_time}] 【{cookie_id}】【系统】买家已付款,准备自动发货") - logger.info(f"【{cookie_id}】准备自动发货: item_id=123456, item_title=测试商品") - - # 5. 回复相关日志 - logger.info(f"【{cookie_id}】使用默认回复: 您好,感谢您的咨询!") - logger.info(f"【{cookie_id}】AI回复生成成功: 这是AI生成的回复") - - # 6. 错误日志 - if i == 1: # 只在第二个Cookie上模拟错误 - logger.error(f"【{cookie_id}】Token刷新失败: 网络连接超时") - - print() # 空行分隔 - await asyncio.sleep(0.2) - - print("=" * 50) - print("✅ 日志显示测试完成") - - print("\n📊 日志格式说明:") - print("• 【Cookie_ID】- 标识具体的用户账号") - print("• 【系统】- 系统级别的消息") - print("• [时间戳] - 消息发生的具体时间") - print("• 不同用户的操作现在可以清晰区分") - - print("\n🎯 改进效果:") - print("• ✅ 多用户环境下可以快速定位问题") - print("• ✅ 日志分析更加高效") - print("• ✅ 运维监控更加精准") - print("• ✅ 调试过程更加清晰") - -def test_log_format_comparison(): - """对比改进前后的日志格式""" - - print("\n🔍 日志格式对比") - print("=" * 50) - - print("📝 改进前的日志格式:") - print("2025-07-25 14:23:47.770 | INFO | XianyuAutoAsync:init:1360 - 获取初始token...") - print("2025-07-25 14:23:47.771 | INFO | XianyuAutoAsync:refresh_token:134 - 开始刷新token...") - print("2025-07-25 14:23:48.269 | INFO | XianyuAutoAsync:refresh_token:200 - Token刷新成功") - print("2025-07-25 14:23:49.286 | INFO | XianyuAutoAsync:init:1407 - 连接注册完成") - print("2025-07-25 14:23:49.288 | INFO | XianyuAutoAsync:handle_message:1663 - [2025-07-25 14:23:49] 【系统】小闲鱼智能提示:") - - print("\n📝 改进后的日志格式:") - print("2025-07-25 14:23:47.770 | INFO | XianyuAutoAsync:init:1360 - 【user1_cookie】获取初始token...") - print("2025-07-25 14:23:47.771 | INFO | XianyuAutoAsync:refresh_token:134 - 【user1_cookie】开始刷新token...") - print("2025-07-25 14:23:48.269 | INFO | XianyuAutoAsync:refresh_token:200 - 【user1_cookie】Token刷新成功") - print("2025-07-25 14:23:49.286 | INFO | XianyuAutoAsync:init:1407 - 【user1_cookie】连接注册完成") - print("2025-07-25 14:23:49.288 | INFO | XianyuAutoAsync:handle_message:1663 - [2025-07-25 14:23:49] 【user1_cookie】【系统】小闲鱼智能提示:") - - print("\n🎯 改进优势:") - print("• 🔍 快速识别: 一眼就能看出是哪个用户的操作") - print("• 🐛 问题定位: 多用户环境下快速定位问题源头") - print("• 📈 监控分析: 可以按用户统计操作频率和成功率") - print("• 🔧 运维管理: 便于针对特定用户进行故障排查") - -def generate_log_analysis_tips(): - """生成日志分析技巧""" - - print("\n💡 日志分析技巧") - print("=" * 50) - - tips = [ - { - "title": "按用户过滤日志", - "command": "grep '【user1_cookie】' xianyu_2025-07-25.log", - "description": "查看特定用户的所有操作日志" - }, - { - "title": "查看Token刷新情况", - "command": "grep '【.*】.*Token' xianyu_2025-07-25.log", - "description": "监控所有用户的Token刷新状态" - }, - { - "title": "统计用户活跃度", - "command": "grep -o '【[^】]*】' xianyu_2025-07-25.log | sort | uniq -c", - "description": "统计各用户的操作次数" - }, - { - "title": "查看系统消息", - "command": "grep '【系统】' xianyu_2025-07-25.log", - "description": "查看所有系统级别的消息" - }, - { - "title": "监控错误日志", - "command": "grep 'ERROR.*【.*】' xianyu_2025-07-25.log", - "description": "查看特定用户的错误信息" - } - ] - - for i, tip in enumerate(tips, 1): - print(f"{i}. {tip['title']}") - print(f" 命令: {tip['command']}") - print(f" 说明: {tip['description']}") - print() - -async def main(): - """主函数""" - print("🚀 Cookie ID日志显示测试工具") - print("=" * 60) - - # 测试日志显示 - await test_cookie_log_display() - - # 对比日志格式 - test_log_format_comparison() - - # 生成分析技巧 - generate_log_analysis_tips() - - print("=" * 60) - print("🎉 测试完成!现在您可以在多用户环境下清晰地识别每个用户的操作。") - - print("\n📋 下一步建议:") - print("1. 重启服务以应用日志改进") - print("2. 观察实际运行中的日志输出") - print("3. 使用提供的命令进行日志分析") - print("4. 根据需要调整日志级别和格式") - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/test_database_backup.py b/test_database_backup.py deleted file mode 100644 index a98a005..0000000 --- a/test_database_backup.py +++ /dev/null @@ -1,254 +0,0 @@ -#!/usr/bin/env python3 -""" -测试数据库备份和恢复功能 -""" - -import requests -import os -import time -import sqlite3 -from loguru import logger - -BASE_URL = "http://localhost:8080" - -def test_admin_login(): - """测试管理员登录""" - logger.info("测试管理员登录...") - - response = requests.post(f"{BASE_URL}/login", - json={'username': 'admin', 'password': 'admin123'}) - - if response.json()['success']: - token = response.json()['token'] - user_id = response.json()['user_id'] - - logger.info(f"管理员登录成功,token: {token[:20]}...") - return { - 'token': token, - 'user_id': user_id, - 'headers': {'Authorization': f'Bearer {token}'} - } - else: - logger.error("管理员登录失败") - return None - -def test_database_download(admin): - """测试数据库下载""" - logger.info("测试数据库下载...") - - try: - response = requests.get(f"{BASE_URL}/admin/backup/download", - headers=admin['headers']) - - if response.status_code == 200: - # 保存下载的文件 - timestamp = int(time.time()) - backup_filename = f"test_backup_{timestamp}.db" - - with open(backup_filename, 'wb') as f: - f.write(response.content) - - # 验证下载的文件 - file_size = os.path.getsize(backup_filename) - logger.info(f"✅ 数据库下载成功: {backup_filename} ({file_size} bytes)") - - # 验证是否为有效的SQLite数据库 - try: - conn = sqlite3.connect(backup_filename) - cursor = conn.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") - tables = cursor.fetchall() - conn.close() - - table_names = [table[0] for table in tables] - logger.info(f" 数据库包含 {len(table_names)} 个表: {', '.join(table_names[:5])}...") - - return backup_filename - - except sqlite3.Error as e: - logger.error(f"❌ 下载的文件不是有效的SQLite数据库: {e}") - return None - - else: - logger.error(f"❌ 数据库下载失败: {response.status_code}") - return None - - except Exception as e: - logger.error(f"❌ 数据库下载异常: {e}") - return None - -def test_backup_file_list(admin): - """测试备份文件列表""" - logger.info("测试备份文件列表...") - - try: - response = requests.get(f"{BASE_URL}/admin/backup/list", - headers=admin['headers']) - - if response.status_code == 200: - data = response.json() - backups = data.get('backups', []) - logger.info(f"✅ 获取备份文件列表成功,共 {len(backups)} 个备份文件") - - for backup in backups[:3]: # 显示前3个 - logger.info(f" {backup['filename']} - {backup['size_mb']}MB - {backup['created_time']}") - - return True - else: - logger.error(f"❌ 获取备份文件列表失败: {response.status_code}") - return False - - except Exception as e: - logger.error(f"❌ 获取备份文件列表异常: {e}") - return False - -def test_database_upload(admin, backup_file): - """测试数据库上传(模拟,不实际执行)""" - logger.info("测试数据库上传准备...") - - if not backup_file or not os.path.exists(backup_file): - logger.error("❌ 没有有效的备份文件进行上传测试") - return False - - try: - # 检查文件大小 - file_size = os.path.getsize(backup_file) - if file_size > 100 * 1024 * 1024: # 100MB - logger.warning(f"⚠️ 备份文件过大: {file_size} bytes") - return False - - # 验证文件格式 - try: - conn = sqlite3.connect(backup_file) - cursor = conn.cursor() - cursor.execute("SELECT COUNT(*) FROM users") - user_count = cursor.fetchone()[0] - conn.close() - - logger.info(f"✅ 备份文件验证通过,包含 {user_count} 个用户") - logger.info(" 注意:实际上传会替换当前数据库,此处仅验证文件有效性") - - return True - - except sqlite3.Error as e: - logger.error(f"❌ 备份文件验证失败: {e}") - return False - - except Exception as e: - logger.error(f"❌ 数据库上传准备异常: {e}") - return False - -def cleanup_test_files(): - """清理测试文件""" - logger.info("清理测试文件...") - - import glob - test_files = glob.glob("test_backup_*.db") - - for file_path in test_files: - try: - os.remove(file_path) - logger.info(f" 删除测试文件: {file_path}") - except Exception as e: - logger.warning(f" 删除文件失败: {file_path} - {e}") - -def main(): - """主测试函数""" - print("🚀 数据库备份和恢复功能测试") - print("=" * 60) - - print("📋 测试内容:") - print("• 管理员登录") - print("• 数据库备份下载") - print("• 备份文件列表查询") - print("• 备份文件验证") - print("• 数据库上传准备(不实际执行)") - - try: - # 管理员登录 - admin = test_admin_login() - if not admin: - print("❌ 测试失败:管理员登录失败") - return False - - print("✅ 管理员登录成功") - - # 测试各项功能 - tests = [ - ("数据库下载", lambda: test_database_download(admin)), - ("备份文件列表", lambda: test_backup_file_list(admin)), - ] - - results = [] - backup_file = None - - for test_name, test_func in tests: - print(f"\n🧪 测试 {test_name}...") - try: - result = test_func() - if test_name == "数据库下载" and result: - backup_file = result - result = True - - results.append((test_name, result)) - if result: - print(f"✅ {test_name} 测试通过") - else: - print(f"❌ {test_name} 测试失败") - except Exception as e: - print(f"💥 {test_name} 测试异常: {e}") - results.append((test_name, False)) - - # 测试数据库上传准备 - print(f"\n🧪 测试数据库上传准备...") - upload_result = test_database_upload(admin, backup_file) - results.append(("数据库上传准备", upload_result)) - if upload_result: - print(f"✅ 数据库上传准备 测试通过") - else: - print(f"❌ 数据库上传准备 测试失败") - - # 清理测试文件 - cleanup_test_files() - - print("\n" + "=" * 60) - print("🎉 数据库备份和恢复功能测试完成!") - - print("\n📊 测试结果:") - passed = 0 - for test_name, result in results: - status = "✅ 通过" if result else "❌ 失败" - print(f" {test_name}: {status}") - if result: - passed += 1 - - print(f"\n📈 总体结果: {passed}/{len(results)} 项测试通过") - - if passed == len(results): - print("🎊 所有测试都通过了!数据库备份功能正常工作。") - - print("\n💡 使用说明:") - print("1. 登录admin账号,进入系统设置") - print("2. 在备份管理区域点击'下载数据库'") - print("3. 数据库文件会自动下载到本地") - print("4. 需要恢复时,选择.db文件并点击'恢复数据库'") - print("5. 系统会自动验证文件并替换数据库") - - print("\n⚠️ 重要提醒:") - print("• 数据库恢复会完全替换当前所有数据") - print("• 建议在恢复前先下载当前数据库作为备份") - print("• 恢复后建议刷新页面以加载新数据") - - return True - else: - print("⚠️ 部分测试失败,请检查相关功能。") - return False - - except Exception as e: - print(f"💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/test_docker_deployment.py b/test_docker_deployment.py deleted file mode 100644 index 1d0f2a6..0000000 --- a/test_docker_deployment.py +++ /dev/null @@ -1,331 +0,0 @@ -#!/usr/bin/env python3 -""" -Docker部署配置验证脚本 -检查Docker部署是否包含所有必要的组件和配置 -""" - -import os -import sys -import yaml -import json -from pathlib import Path - -def check_file_exists(file_path, description): - """检查文件是否存在""" - if os.path.exists(file_path): - print(f" ✅ {description}: {file_path}") - return True - else: - print(f" ❌ {description}: {file_path} (缺失)") - return False - -def check_requirements_txt(): - """检查requirements.txt中的依赖""" - print("📦 检查Python依赖...") - - if not check_file_exists("requirements.txt", "依赖文件"): - return False - - required_packages = [ - "fastapi", - "uvicorn", - "pydantic", - "loguru", - "websockets", - "aiohttp", - "PyYAML", - "PyExecJS", - "blackboxprotobuf", - "psutil", - "requests", - "python-multipart", - "openai", - "python-dotenv" - ] - - try: - with open("requirements.txt", "r", encoding="utf-8") as f: - content = f.read() - - missing_packages = [] - for package in required_packages: - if package.lower() not in content.lower(): - missing_packages.append(package) - - if missing_packages: - print(f" ❌ 缺失依赖: {', '.join(missing_packages)}") - return False - else: - print(f" ✅ 所有必要依赖都已包含 ({len(required_packages)} 个)") - return True - - except Exception as e: - print(f" ❌ 读取requirements.txt失败: {e}") - return False - -def check_dockerfile(): - """检查Dockerfile配置""" - print("\n🐳 检查Dockerfile...") - - if not check_file_exists("Dockerfile", "Docker镜像文件"): - return False - - try: - with open("Dockerfile", "r", encoding="utf-8") as f: - content = f.read() - - required_elements = [ - ("FROM python:", "Python基础镜像"), - ("WORKDIR", "工作目录设置"), - ("COPY requirements.txt", "依赖文件复制"), - ("RUN pip install", "依赖安装"), - ("EXPOSE", "端口暴露"), - ("CMD", "启动命令") - ] - - missing_elements = [] - for element, description in required_elements: - if element not in content: - missing_elements.append(description) - - if missing_elements: - print(f" ❌ 缺失配置: {', '.join(missing_elements)}") - return False - else: - print(f" ✅ Dockerfile配置完整") - return True - - except Exception as e: - print(f" ❌ 读取Dockerfile失败: {e}") - return False - -def check_docker_compose(): - """检查docker-compose.yml配置""" - print("\n🔧 检查Docker Compose配置...") - - if not check_file_exists("docker-compose.yml", "Docker Compose文件"): - return False - - try: - with open("docker-compose.yml", "r", encoding="utf-8") as f: - compose_config = yaml.safe_load(f) - - # 检查服务配置 - if "services" not in compose_config: - print(" ❌ 缺失services配置") - return False - - services = compose_config["services"] - if "xianyu-app" not in services: - print(" ❌ 缺失xianyu-app服务") - return False - - app_service = services["xianyu-app"] - - # 检查必要配置 - required_configs = [ - ("ports", "端口映射"), - ("volumes", "数据挂载"), - ("environment", "环境变量"), - ("healthcheck", "健康检查") - ] - - missing_configs = [] - for config, description in required_configs: - if config not in app_service: - missing_configs.append(description) - - if missing_configs: - print(f" ❌ 缺失配置: {', '.join(missing_configs)}") - return False - - # 检查AI相关环境变量 - env_vars = app_service.get("environment", []) - ai_env_vars = [ - "AI_REPLY_ENABLED", - "DEFAULT_AI_MODEL", - "DEFAULT_AI_BASE_URL", - "AI_REQUEST_TIMEOUT" - ] - - missing_ai_vars = [] - env_str = str(env_vars) - for var in ai_env_vars: - if var not in env_str: - missing_ai_vars.append(var) - - if missing_ai_vars: - print(f" ⚠️ 缺失AI环境变量: {', '.join(missing_ai_vars)}") - else: - print(f" ✅ AI环境变量配置完整") - - print(f" ✅ Docker Compose配置完整") - return True - - except Exception as e: - print(f" ❌ 读取docker-compose.yml失败: {e}") - return False - -def check_env_example(): - """检查.env.example配置""" - print("\n⚙️ 检查环境变量模板...") - - if not check_file_exists(".env.example", "环境变量模板"): - return False - - try: - with open(".env.example", "r", encoding="utf-8") as f: - content = f.read() - - # 检查AI相关配置 - ai_configs = [ - "AI_REPLY_ENABLED", - "DEFAULT_AI_MODEL", - "DEFAULT_AI_BASE_URL", - "AI_REQUEST_TIMEOUT", - "AI_MAX_TOKENS" - ] - - missing_configs = [] - for config in ai_configs: - if config not in content: - missing_configs.append(config) - - if missing_configs: - print(f" ❌ 缺失AI配置: {', '.join(missing_configs)}") - return False - else: - print(f" ✅ AI配置完整") - - # 检查基础配置 - basic_configs = [ - "ADMIN_USERNAME", - "ADMIN_PASSWORD", - "JWT_SECRET_KEY", - "AUTO_REPLY_ENABLED", - "AUTO_DELIVERY_ENABLED" - ] - - missing_basic = [] - for config in basic_configs: - if config not in content: - missing_basic.append(config) - - if missing_basic: - print(f" ❌ 缺失基础配置: {', '.join(missing_basic)}") - return False - else: - print(f" ✅ 基础配置完整") - - return True - - except Exception as e: - print(f" ❌ 读取.env.example失败: {e}") - return False - -def check_documentation(): - """检查部署文档""" - print("\n📚 检查部署文档...") - - docs = [ - ("Docker部署说明.md", "Docker部署说明"), - ("README.md", "项目说明文档") - ] - - all_exist = True - for doc_file, description in docs: - if not check_file_exists(doc_file, description): - all_exist = False - - return all_exist - -def check_directory_structure(): - """检查目录结构""" - print("\n📁 检查目录结构...") - - required_dirs = [ - ("static", "静态文件目录"), - ("templates", "模板目录(如果存在)") - ] - - required_files = [ - ("Start.py", "主程序文件"), - ("db_manager.py", "数据库管理"), - ("XianyuAutoAsync.py", "闲鱼自动化"), - ("ai_reply_engine.py", "AI回复引擎"), - ("global_config.yml", "全局配置") - ] - - all_exist = True - - # 检查目录 - for dir_name, description in required_dirs: - if os.path.exists(dir_name) and os.path.isdir(dir_name): - print(f" ✅ {description}: {dir_name}") - else: - if dir_name == "templates": # templates是可选的 - print(f" ⚠️ {description}: {dir_name} (可选)") - else: - print(f" ❌ {description}: {dir_name} (缺失)") - all_exist = False - - # 检查文件 - for file_name, description in required_files: - if not check_file_exists(file_name, description): - all_exist = False - - return all_exist - -def main(): - """主检查函数""" - print("🚀 Docker部署配置验证") - print("=" * 50) - - checks = [ - ("Python依赖", check_requirements_txt), - ("Dockerfile", check_dockerfile), - ("Docker Compose", check_docker_compose), - ("环境变量", check_env_example), - ("目录结构", check_directory_structure), - ("文档", check_documentation) - ] - - results = [] - for check_name, check_func in checks: - try: - result = check_func() - results.append((check_name, result)) - except Exception as e: - print(f" ❌ {check_name}检查异常: {e}") - results.append((check_name, False)) - - # 总结结果 - print("\n" + "=" * 50) - print("📊 检查结果总结") - - passed = 0 - total = len(results) - - for check_name, result in results: - status = "✅ 通过" if result else "❌ 失败" - print(f" {check_name}: {status}") - if result: - passed += 1 - - print(f"\n📈 总体评分: {passed}/{total} ({passed/total*100:.1f}%)") - - if passed == total: - print("\n🎉 所有检查通过!Docker部署配置完整!") - print("\n🚀 可以直接使用以下命令部署:") - print(" docker-compose up -d") - elif passed >= total * 0.8: - print("\n⚠️ 大部分检查通过,有少量问题需要修复") - print(" 建议修复上述问题后再部署") - else: - print("\n❌ 多项检查失败,需要完善配置后再部署") - - return passed == total - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/test_docker_deployment.sh b/test_docker_deployment.sh deleted file mode 100644 index f50051c..0000000 --- a/test_docker_deployment.sh +++ /dev/null @@ -1,192 +0,0 @@ -#!/bin/bash - -# Docker多用户系统部署测试脚本 - -echo "🚀 Docker多用户系统部署测试" -echo "==================================" - -# 颜色定义 -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# 检查Docker和Docker Compose -echo -e "${BLUE}1. 检查Docker环境${NC}" -if ! command -v docker &> /dev/null; then - echo -e "${RED}❌ Docker未安装${NC}" - exit 1 -fi - -if ! command -v docker-compose &> /dev/null; then - echo -e "${RED}❌ Docker Compose未安装${NC}" - exit 1 -fi - -echo -e "${GREEN}✅ Docker环境检查通过${NC}" -echo " Docker版本: $(docker --version)" -echo " Docker Compose版本: $(docker-compose --version)" - -# 检查必要文件 -echo -e "\n${BLUE}2. 检查部署文件${NC}" -required_files=("Dockerfile" "docker-compose.yml" "requirements.txt") - -for file in "${required_files[@]}"; do - if [ -f "$file" ]; then - echo -e "${GREEN}✅ $file${NC}" - else - echo -e "${RED}❌ $file 不存在${NC}" - exit 1 - fi -done - -# 检查新增依赖 -echo -e "\n${BLUE}3. 检查新增依赖${NC}" -if grep -q "Pillow" requirements.txt; then - echo -e "${GREEN}✅ Pillow依赖已添加${NC}" -else - echo -e "${RED}❌ Pillow依赖缺失${NC}" - exit 1 -fi - -# 停止现有容器 -echo -e "\n${BLUE}4. 停止现有容器${NC}" -docker-compose down -echo -e "${GREEN}✅ 容器已停止${NC}" - -# 构建镜像 -echo -e "\n${BLUE}5. 构建Docker镜像${NC}" -echo "这可能需要几分钟时间..." -if docker-compose build --no-cache; then - echo -e "${GREEN}✅ 镜像构建成功${NC}" -else - echo -e "${RED}❌ 镜像构建失败${NC}" - exit 1 -fi - -# 启动服务 -echo -e "\n${BLUE}6. 启动服务${NC}" -if docker-compose up -d; then - echo -e "${GREEN}✅ 服务启动成功${NC}" -else - echo -e "${RED}❌ 服务启动失败${NC}" - exit 1 -fi - -# 等待服务就绪 -echo -e "\n${BLUE}7. 等待服务就绪${NC}" -echo "等待30秒让服务完全启动..." -sleep 30 - -# 检查容器状态 -echo -e "\n${BLUE}8. 检查容器状态${NC}" -if docker-compose ps | grep -q "Up"; then - echo -e "${GREEN}✅ 容器运行正常${NC}" - docker-compose ps -else - echo -e "${RED}❌ 容器运行异常${NC}" - docker-compose ps - echo -e "\n${YELLOW}查看日志:${NC}" - docker-compose logs --tail=20 - exit 1 -fi - -# 健康检查 -echo -e "\n${BLUE}9. 健康检查${NC}" -max_attempts=10 -attempt=1 - -while [ $attempt -le $max_attempts ]; do - if curl -s http://localhost:8080/health > /dev/null; then - echo -e "${GREEN}✅ 健康检查通过${NC}" - break - else - echo -e "${YELLOW}⏳ 尝试 $attempt/$max_attempts - 等待服务响应...${NC}" - sleep 3 - ((attempt++)) - fi -done - -if [ $attempt -gt $max_attempts ]; then - echo -e "${RED}❌ 健康检查失败${NC}" - echo -e "\n${YELLOW}查看日志:${NC}" - docker-compose logs --tail=20 - exit 1 -fi - -# 测试图形验证码API -echo -e "\n${BLUE}10. 测试图形验证码功能${NC}" -response=$(curl -s -X POST http://localhost:8080/generate-captcha \ - -H "Content-Type: application/json" \ - -d '{"session_id": "test_session"}') - -if echo "$response" | grep -q '"success":true'; then - echo -e "${GREEN}✅ 图形验证码API正常${NC}" -else - echo -e "${RED}❌ 图形验证码API异常${NC}" - echo "响应: $response" -fi - -# 测试注册页面 -echo -e "\n${BLUE}11. 测试注册页面${NC}" -if curl -s http://localhost:8080/register.html | grep -q "用户注册"; then - echo -e "${GREEN}✅ 注册页面可访问${NC}" -else - echo -e "${RED}❌ 注册页面访问失败${NC}" -fi - -# 测试登录页面 -echo -e "\n${BLUE}12. 测试登录页面${NC}" -if curl -s http://localhost:8080/login.html | grep -q "登录"; then - echo -e "${GREEN}✅ 登录页面可访问${NC}" -else - echo -e "${RED}❌ 登录页面访问失败${NC}" -fi - -# 检查Pillow安装 -echo -e "\n${BLUE}13. 检查Pillow安装${NC}" -if docker-compose exec -T xianyu-app python -c "from PIL import Image; print('Pillow OK')" 2>/dev/null | grep -q "Pillow OK"; then - echo -e "${GREEN}✅ Pillow安装正常${NC}" -else - echo -e "${RED}❌ Pillow安装异常${NC}" -fi - -# 检查字体支持 -echo -e "\n${BLUE}14. 检查字体支持${NC}" -if docker-compose exec -T xianyu-app ls /usr/share/fonts/ 2>/dev/null | grep -q "dejavu"; then - echo -e "${GREEN}✅ 字体支持正常${NC}" -else - echo -e "${YELLOW}⚠️ 字体支持可能有问题${NC}" -fi - -# 显示访问信息 -echo -e "\n${GREEN}🎉 Docker部署测试完成!${NC}" -echo "==================================" -echo -e "${BLUE}访问信息:${NC}" -echo "• 主页: http://localhost:8080" -echo "• 登录页面: http://localhost:8080/login.html" -echo "• 注册页面: http://localhost:8080/register.html" -echo "• 健康检查: http://localhost:8080/health" -echo "" -echo -e "${BLUE}默认管理员账号:${NC}" -echo "• 用户名: admin" -echo "• 密码: admin123" -echo "" -echo -e "${BLUE}多用户功能:${NC}" -echo "• ✅ 用户注册" -echo "• ✅ 图形验证码" -echo "• ✅ 邮箱验证" -echo "• ✅ 数据隔离" -echo "" -echo -e "${YELLOW}管理命令:${NC}" -echo "• 查看日志: docker-compose logs -f" -echo "• 停止服务: docker-compose down" -echo "• 重启服务: docker-compose restart" -echo "• 查看状态: docker-compose ps" - -# 可选:显示资源使用情况 -echo -e "\n${BLUE}资源使用情况:${NC}" -docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" | grep xianyu || echo "无法获取资源使用情况" - -echo -e "\n${GREEN}部署测试完成!系统已就绪。${NC}" diff --git a/test_duplicate_notification_fix.py b/test_duplicate_notification_fix.py deleted file mode 100644 index 74231e8..0000000 --- a/test_duplicate_notification_fix.py +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env python3 -""" -测试重复通知修复 -验证Token刷新失败时不会发送重复通知 -""" - -import asyncio -import time -from unittest.mock import AsyncMock, patch, MagicMock -import sys -import os - -# 添加项目根目录到路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -async def test_duplicate_notification_fix(): - """测试重复通知修复""" - print("🧪 测试Token刷新失败重复通知修复") - print("=" * 60) - - # 动态导入,避免配置问题 - try: - from XianyuAutoAsync import XianyuLive - print("✅ 成功导入 XianyuLive") - except Exception as e: - print(f"❌ 导入失败: {e}") - return - - # 创建测试用的XianyuLive实例 - test_cookies = "unb=test123; _m_h5_tk=test_token_123456789" - - try: - xianyu = XianyuLive(test_cookies, "test_account") - print("✅ XianyuLive 实例创建成功") - except Exception as e: - print(f"❌ 创建 XianyuLive 实例失败: {e}") - return - - # Mock外部依赖 - with patch('XianyuAutoAsync.db_manager') as mock_db, \ - patch('aiohttp.ClientSession') as mock_session: - - # 配置数据库mock - mock_db.get_account_notifications.return_value = [ - { - 'enabled': True, - 'channel_type': 'qq', - 'channel_name': 'Test QQ', - 'channel_config': {'qq_number': '123456', 'api_url': 'http://test.com'} - } - ] - - # Mock HTTP session - mock_response = MagicMock() - mock_response.status = 200 - mock_response.text = AsyncMock(return_value='{"ret": ["FAIL_SYS_SESSION_EXPIRED::Session过期"]}') - mock_session_instance = AsyncMock() - mock_session_instance.post.return_value.__aenter__.return_value = mock_response - mock_session.return_value = mock_session_instance - xianyu.session = mock_session_instance - - # Mock QQ通知发送方法 - xianyu._send_qq_notification = AsyncMock() - - print("\n📋 测试场景: Cookie过期导致Token刷新失败") - print("-" * 40) - - # 重置状态 - xianyu.current_token = None - xianyu.last_token_refresh_time = 0 - xianyu._send_qq_notification.reset_mock() - - print("1️⃣ 模拟 init() 方法调用...") - - # 创建一个mock websocket - mock_ws = MagicMock() - - try: - # 调用init方法,这会触发refresh_token,然后检查token - await xianyu.init(mock_ws) - except Exception as e: - print(f" 预期的异常: {e}") - - # 检查通知发送次数 - call_count = xianyu._send_qq_notification.call_count - print(f"\n📊 通知发送统计:") - print(f" 总调用次数: {call_count}") - - if call_count == 1: - print(" ✅ 成功!只发送了一次通知") - print(" 💡 说明: refresh_token失败后,init不会发送重复通知") - elif call_count == 2: - print(" ❌ 失败!发送了两次重复通知") - print(" 🔧 需要进一步优化防重复机制") - elif call_count == 0: - print(" ⚠️ 没有发送通知(可能是mock配置问题)") - else: - print(f" ❓ 异常的调用次数: {call_count}") - - # 显示调用详情 - if xianyu._send_qq_notification.call_args_list: - print(f"\n📝 通知调用详情:") - for i, call in enumerate(xianyu._send_qq_notification.call_args_list, 1): - args, kwargs = call - if len(args) >= 2: - message = args[1] - # 提取关键信息 - if "异常信息:" in message: - error_info = message.split("异常信息:")[1].split("\n")[0].strip() - print(f" 第{i}次: {error_info}") - - print("\n🔍 防重复机制分析:") - print(" • 方案1: 时间冷却期 - 5分钟内不重复发送相同类型通知") - print(" • 方案2: 逻辑判断 - init()检查是否刚刚尝试过refresh_token") - print(" • 当前使用: 方案2 (更精确,避免逻辑重复)") - - print(f"\n⏰ 通知时间记录:") - for notification_type, last_time in xianyu.last_notification_time.items(): - print(f" {notification_type}: {time.strftime('%H:%M:%S', time.localtime(last_time))}") - -def show_optimization_summary(): - """显示优化总结""" - print("\n\n📋 优化总结") - print("=" * 60) - - print("🎯 问题描述:") - print(" 用户反馈每次Token刷新异常都会收到两个相同的通知") - - print("\n🔍 问题根因:") - print(" 1. refresh_token() 失败时发送第一次通知") - print(" 2. init() 检查 current_token 为空时发送第二次通知") - print(" 3. 两次通知内容基本相同,造成用户困扰") - - print("\n🛠️ 解决方案:") - print(" 方案A: 添加通知防重复机制") - print(" • 为不同场景使用不同的通知类型") - print(" • 设置5分钟冷却期,避免短时间重复通知") - print(" • 保留详细的错误信息用于调试") - - print("\n 方案B: 优化逻辑判断") - print(" • 在 init() 中跟踪是否刚刚尝试过 refresh_token") - print(" • 如果刚刚尝试过且失败,则不发送重复通知") - print(" • 更精确地避免逻辑重复") - - print("\n✅ 实施的优化:") - print(" • 采用方案A + 方案B的组合") - print(" • 添加了通知防重复机制(时间冷却)") - print(" • 优化了 init() 方法的逻辑判断") - print(" • 为不同错误场景使用不同的通知类型") - - print("\n🎉 预期效果:") - print(" • 用户只会收到一次Token刷新异常通知") - print(" • 通知内容更加精确,便于问题定位") - print(" • 避免了通知轰炸,改善用户体验") - print(" • 保留了完整的错误信息用于调试") - -if __name__ == "__main__": - try: - asyncio.run(test_duplicate_notification_fix()) - show_optimization_summary() - - print("\n" + "=" * 60) - print("🎊 Token刷新重复通知修复测试完成!") - - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_fix.py b/test_fix.py deleted file mode 100644 index c8360e4..0000000 --- a/test_fix.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 -""" -测试修复 -""" - -def test_imports(): - print("🧪 测试导入修复") - - try: - from file_log_collector import setup_file_logging, get_file_log_collector - print("✅ file_log_collector 导入成功") - - # 测试初始化 - collector = setup_file_logging() - print("✅ 文件日志收集器初始化成功") - - # 生成测试日志 - from loguru import logger - logger.info("测试日志修复") - - print("✅ 所有导入和初始化都正常") - - except Exception as e: - print(f"❌ 导入失败: {e}") - -if __name__ == "__main__": - test_imports() diff --git a/test_gitignore.py b/test_gitignore.py deleted file mode 100644 index d8ecf7b..0000000 --- a/test_gitignore.py +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/env python3 -""" -测试 .gitignore 规则是否正确 -验证 static/lib/ 目录不被忽略,而其他 lib/ 目录被忽略 -""" - -import os -import subprocess -import tempfile - -def test_gitignore_rules(): - """测试 .gitignore 规则""" - print("🧪 测试 .gitignore 规则") - print("=" * 50) - - # 检查文件是否存在 - static_lib_files = [ - "static/lib/bootstrap/bootstrap.min.css", - "static/lib/bootstrap/bootstrap.bundle.min.js", - "static/lib/bootstrap-icons/bootstrap-icons.css", - "static/lib/bootstrap-icons/fonts/bootstrap-icons.woff", - "static/lib/bootstrap-icons/fonts/bootstrap-icons.woff2" - ] - - print("\n1️⃣ 检查静态文件是否存在...") - all_exist = True - for file_path in static_lib_files: - if os.path.exists(file_path): - size = os.path.getsize(file_path) - print(f" ✅ {file_path} ({size:,} bytes)") - else: - print(f" ❌ {file_path} (不存在)") - all_exist = False - - if all_exist: - print(" 🎉 所有静态文件都存在!") - else: - print(" ⚠️ 部分静态文件缺失") - - # 检查 .gitignore 内容 - print("\n2️⃣ 检查 .gitignore 规则...") - try: - with open('.gitignore', 'r', encoding='utf-8') as f: - gitignore_content = f.read() - - if 'lib/' in gitignore_content and '!static/lib/' in gitignore_content: - print(" ✅ .gitignore 规则正确配置") - print(" 📝 规则说明:") - print(" - lib/ : 忽略所有 lib 目录") - print(" - !static/lib/ : 但不忽略 static/lib 目录") - else: - print(" ❌ .gitignore 规则配置不正确") - - except Exception as e: - print(f" ❌ 读取 .gitignore 失败: {e}") - - # 模拟测试(创建临时文件) - print("\n3️⃣ 模拟测试 gitignore 行为...") - - # 创建测试目录和文件 - test_dirs = [ - "lib/test_file.txt", # 应该被忽略 - "static/lib/test_file.txt", # 不应该被忽略 - "some_other_lib/test_file.txt" # 不应该被忽略 - ] - - created_files = [] - try: - for test_path in test_dirs: - os.makedirs(os.path.dirname(test_path), exist_ok=True) - with open(test_path, 'w') as f: - f.write("test content") - created_files.append(test_path) - print(f" 📁 创建测试文件: {test_path}") - - print("\n 📋 根据 .gitignore 规则预期:") - print(" - lib/test_file.txt : 应该被忽略") - print(" - static/lib/test_file.txt : 不应该被忽略") - print(" - some_other_lib/test_file.txt : 不应该被忽略") - - except Exception as e: - print(f" ❌ 创建测试文件失败: {e}") - - finally: - # 清理测试文件 - print("\n4️⃣ 清理测试文件...") - for file_path in created_files: - try: - if os.path.exists(file_path): - os.remove(file_path) - print(f" 🗑️ 删除: {file_path}") - except Exception as e: - print(f" ⚠️ 删除失败: {file_path} - {e}") - - # 清理空目录 - test_cleanup_dirs = ["lib", "some_other_lib"] - for dir_path in test_cleanup_dirs: - try: - if os.path.exists(dir_path) and not os.listdir(dir_path): - os.rmdir(dir_path) - print(f" 🗑️ 删除空目录: {dir_path}") - except Exception as e: - print(f" ⚠️ 删除目录失败: {dir_path} - {e}") - - print("\n" + "=" * 50) - print("🎯 总结:") - print("✅ static/lib/ 目录下的静态文件现在不会被 Git 忽略") - print("✅ 其他 lib/ 目录仍然会被正常忽略") - print("✅ 本地 CDN 资源可以正常提交到版本控制") - -def check_file_sizes(): - """检查静态文件大小""" - print("\n\n📊 静态文件大小统计") - print("=" * 50) - - files_info = [ - ("Bootstrap CSS", "static/lib/bootstrap/bootstrap.min.css"), - ("Bootstrap JS", "static/lib/bootstrap/bootstrap.bundle.min.js"), - ("Bootstrap Icons CSS", "static/lib/bootstrap-icons/bootstrap-icons.css"), - ("Bootstrap Icons WOFF2", "static/lib/bootstrap-icons/fonts/bootstrap-icons.woff2"), - ("Bootstrap Icons WOFF", "static/lib/bootstrap-icons/fonts/bootstrap-icons.woff") - ] - - total_size = 0 - for name, path in files_info: - if os.path.exists(path): - size = os.path.getsize(path) - total_size += size - print(f"📄 {name:<25} : {size:>8,} bytes ({size/1024:.1f} KB)") - else: - print(f"❌ {name:<25} : 文件不存在") - - print("-" * 50) - print(f"📦 总大小 : {total_size:>8,} bytes ({total_size/1024:.1f} KB)") - - if total_size > 0: - print(f"\n💡 优势:") - print(f" - 不再依赖 CDN,提升中国大陆访问速度") - print(f" - 离线可用,提高系统稳定性") - print(f" - 版本固定,避免 CDN 更新导致的兼容性问题") - -if __name__ == "__main__": - try: - test_gitignore_rules() - check_file_sizes() - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_gitignore_db.py b/test_gitignore_db.py deleted file mode 100644 index a60bda2..0000000 --- a/test_gitignore_db.py +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/env python3 -""" -测试 .gitignore 数据库文件忽略规则 -""" - -import os -import tempfile - -def test_database_gitignore(): - """测试数据库文件忽略规则""" - print("🧪 测试数据库文件 .gitignore 规则") - print("=" * 50) - - # 检查当前项目中的数据库文件 - print("\n1️⃣ 检查项目中的数据库文件...") - - db_patterns = ["*.db", "*.sqlite", "*.sqlite3"] - found_db_files = [] - - for root, dirs, files in os.walk("."): - for file in files: - file_path = os.path.join(root, file) - for pattern in db_patterns: - if file.endswith(pattern.replace("*", "")): - size = os.path.getsize(file_path) - found_db_files.append((file_path, size)) - print(f" 📄 {file_path} ({size:,} bytes)") - - if found_db_files: - print(f" 📊 找到 {len(found_db_files)} 个数据库文件") - else: - print(" ✅ 未找到数据库文件") - - # 检查 .gitignore 规则 - print("\n2️⃣ 检查 .gitignore 数据库规则...") - try: - with open('.gitignore', 'r', encoding='utf-8') as f: - gitignore_content = f.read() - - db_rules = ['*.db', '*.sqlite', '*.sqlite3'] - missing_rules = [] - - for rule in db_rules: - if rule in gitignore_content: - print(f" ✅ {rule} - 已配置") - else: - print(f" ❌ {rule} - 未配置") - missing_rules.append(rule) - - if not missing_rules: - print(" 🎉 所有数据库文件规则都已正确配置!") - else: - print(f" ⚠️ 缺少规则: {missing_rules}") - - except Exception as e: - print(f" ❌ 读取 .gitignore 失败: {e}") - - # 测试其他新增的忽略规则 - print("\n3️⃣ 检查其他新增的忽略规则...") - - other_rules = [ - ("临时文件", ["*.tmp", "*.temp", "temp/", "tmp/"]), - ("操作系统文件", [".DS_Store", "Thumbs.db"]), - ("IDE文件", [".vscode/", ".idea/", "*.swp"]), - ("环境文件", [".env", ".env.local"]) - ] - - for category, rules in other_rules: - print(f"\n 📂 {category}:") - for rule in rules: - if rule in gitignore_content: - print(f" ✅ {rule}") - else: - print(f" ❌ {rule}") - - # 模拟创建测试文件 - print("\n4️⃣ 模拟测试文件创建...") - - test_files = [ - "test.db", - "test.sqlite", - "test.sqlite3", - "test.tmp", - ".env", - "temp/test.txt" - ] - - created_files = [] - try: - for test_file in test_files: - # 创建目录(如果需要) - dir_path = os.path.dirname(test_file) - if dir_path: - os.makedirs(dir_path, exist_ok=True) - - # 创建文件 - with open(test_file, 'w') as f: - f.write("test content") - created_files.append(test_file) - print(f" 📁 创建测试文件: {test_file}") - - print("\n 📋 这些文件应该被 .gitignore 忽略:") - for file in test_files: - print(f" - {file}") - - except Exception as e: - print(f" ❌ 创建测试文件失败: {e}") - - finally: - # 清理测试文件 - print("\n5️⃣ 清理测试文件...") - for file_path in created_files: - try: - if os.path.exists(file_path): - os.remove(file_path) - print(f" 🗑️ 删除: {file_path}") - except Exception as e: - print(f" ⚠️ 删除失败: {file_path} - {e}") - - # 清理测试目录 - if os.path.exists("temp") and not os.listdir("temp"): - os.rmdir("temp") - print(" 🗑️ 删除空目录: temp") - - print("\n" + "=" * 50) - print("🎯 .gitignore 数据库文件忽略规则测试完成!") - -def show_gitignore_summary(): - """显示 .gitignore 规则总结""" - print("\n\n📋 .gitignore 规则总结") - print("=" * 50) - - categories = { - "Python 相关": [ - "__pycache__", "*.so", ".Python", "build/", "dist/", - "*.egg-info/", "__pypackages__/", ".venv", "venv/", "ENV/" - ], - "数据库文件": [ - "*.db", "*.sqlite", "*.sqlite3", "db.sqlite3" - ], - "静态资源": [ - "lib/ (但不包括 static/lib/)" - ], - "临时文件": [ - "*.tmp", "*.temp", "temp/", "tmp/", "*.log", ".cache" - ], - "操作系统": [ - ".DS_Store", "Thumbs.db", "ehthumbs.db" - ], - "IDE 和编辑器": [ - ".vscode/", ".idea/", "*.swp", "*.swo", "*~" - ], - "环境配置": [ - ".env", ".env.local", ".env.*.local", "local_settings.py" - ], - "Node.js": [ - "*node_modules/*" - ] - } - - for category, rules in categories.items(): - print(f"\n📂 {category}:") - for rule in rules: - print(f" • {rule}") - - print(f"\n💡 特别说明:") - print(f" • static/lib/ 目录不被忽略,用于存放本地 CDN 资源") - print(f" • 数据库文件被忽略,避免敏感数据泄露") - print(f" • 环境配置文件被忽略,保护敏感配置信息") - -if __name__ == "__main__": - try: - test_database_gitignore() - show_gitignore_summary() - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_improvements.py b/test_improvements.py deleted file mode 100644 index b60429b..0000000 --- a/test_improvements.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python3 -""" -测试系统改进功能 -""" - -import requests -import time -from loguru import logger - -BASE_URL = "http://localhost:8080" - -def test_admin_login(): - """测试管理员登录""" - logger.info("测试管理员登录...") - - response = requests.post(f"{BASE_URL}/login", - json={'username': 'admin', 'password': 'admin123'}) - - if response.json()['success']: - token = response.json()['token'] - user_id = response.json()['user_id'] - - logger.info(f"管理员登录成功,token: {token[:20]}...") - return { - 'token': token, - 'user_id': user_id, - 'headers': {'Authorization': f'Bearer {token}'} - } - else: - logger.error("管理员登录失败") - return None - -def test_page_access(): - """测试页面访问""" - logger.info("测试页面访问...") - - pages = [ - ("用户管理", "/user_management.html"), - ("日志管理", "/log_management.html"), - ("数据管理", "/data_management.html") - ] - - results = [] - for page_name, page_url in pages: - try: - response = requests.get(f"{BASE_URL}{page_url}", timeout=5) - - if response.status_code == 200: - logger.info(f"✅ {page_name} 页面访问成功 (200)") - results.append((page_name, True)) - else: - logger.error(f"❌ {page_name} 页面访问失败 ({response.status_code})") - results.append((page_name, False)) - - except Exception as e: - logger.error(f"❌ {page_name} 页面访问异常: {e}") - results.append((page_name, False)) - - return results - -def test_data_management_api(admin): - """测试数据管理API""" - logger.info("测试数据管理API...") - - # 测试获取表数据 - tables_to_test = ['users', 'cookies', 'cards'] - - for table in tables_to_test: - try: - response = requests.get(f"{BASE_URL}/admin/data/{table}", - headers=admin['headers']) - - if response.status_code == 200: - data = response.json() - if data['success']: - logger.info(f"✅ 获取 {table} 表数据成功,共 {data['count']} 条记录") - else: - logger.error(f"❌ 获取 {table} 表数据失败: {data.get('message', '未知错误')}") - return False - else: - logger.error(f"❌ 获取 {table} 表数据失败: {response.status_code}") - return False - - except Exception as e: - logger.error(f"❌ 获取 {table} 表数据异常: {e}") - return False - - return True - -def test_log_management_api(admin): - """测试日志管理API""" - logger.info("测试日志管理API...") - - try: - # 测试获取日志 - response = requests.get(f"{BASE_URL}/admin/logs?lines=10", - headers=admin['headers']) - - if response.status_code == 200: - data = response.json() - logs = data.get('logs', []) - logger.info(f"✅ 获取系统日志成功,共 {len(logs)} 条") - - # 测试日志级别过滤 - response = requests.get(f"{BASE_URL}/admin/logs?lines=5&level=info", - headers=admin['headers']) - - if response.status_code == 200: - data = response.json() - info_logs = data.get('logs', []) - logger.info(f"✅ INFO级别日志过滤成功,共 {len(info_logs)} 条") - return True - else: - logger.error(f"❌ 日志级别过滤失败: {response.status_code}") - return False - else: - logger.error(f"❌ 获取系统日志失败: {response.status_code}") - return False - - except Exception as e: - logger.error(f"❌ 日志管理API测试异常: {e}") - return False - -def test_database_backup_api(admin): - """测试数据库备份API""" - logger.info("测试数据库备份API...") - - try: - # 测试数据库下载 - response = requests.get(f"{BASE_URL}/admin/backup/download", - headers=admin['headers']) - - if response.status_code == 200: - logger.info(f"✅ 数据库备份下载成功,文件大小: {len(response.content)} bytes") - - # 测试备份文件列表 - response = requests.get(f"{BASE_URL}/admin/backup/list", - headers=admin['headers']) - - if response.status_code == 200: - data = response.json() - backups = data.get('backups', []) - logger.info(f"✅ 获取备份文件列表成功,共 {len(backups)} 个备份") - return True - else: - logger.error(f"❌ 获取备份文件列表失败: {response.status_code}") - return False - else: - logger.error(f"❌ 数据库备份下载失败: {response.status_code}") - return False - - except Exception as e: - logger.error(f"❌ 数据库备份API测试异常: {e}") - return False - -def main(): - """主测试函数""" - print("🚀 系统改进功能测试") - print("=" * 60) - - print("📋 测试内容:") - print("• 页面访问测试") - print("• 日志管理功能") - print("• 数据管理功能") - print("• 数据库备份功能") - - try: - # 管理员登录 - admin = test_admin_login() - if not admin: - print("❌ 测试失败:管理员登录失败") - return False - - print("✅ 管理员登录成功") - - # 测试页面访问 - print(f"\n🧪 测试页面访问...") - page_results = test_page_access() - - page_success = all(result[1] for result in page_results) - for page_name, success in page_results: - status = "✅ 通过" if success else "❌ 失败" - print(f" {page_name}: {status}") - - # 测试API功能 - tests = [ - ("数据管理API", lambda: test_data_management_api(admin)), - ("日志管理API", lambda: test_log_management_api(admin)), - ("数据库备份API", lambda: test_database_backup_api(admin)), - ] - - api_results = [] - for test_name, test_func in tests: - print(f"\n🧪 测试 {test_name}...") - try: - result = test_func() - api_results.append((test_name, result)) - if result: - print(f"✅ {test_name} 测试通过") - else: - print(f"❌ {test_name} 测试失败") - except Exception as e: - print(f"💥 {test_name} 测试异常: {e}") - api_results.append((test_name, False)) - - print("\n" + "=" * 60) - print("🎉 系统改进功能测试完成!") - - print("\n📊 测试结果:") - - # 页面访问结果 - print("页面访问:") - for page_name, success in page_results: - status = "✅ 通过" if success else "❌ 失败" - print(f" {page_name}: {status}") - - # API功能结果 - print("API功能:") - for test_name, success in api_results: - status = "✅ 通过" if success else "❌ 失败" - print(f" {test_name}: {status}") - - # 总体结果 - all_results = page_results + api_results - passed = sum(1 for _, success in all_results if success) - total = len(all_results) - - print(f"\n📈 总体结果: {passed}/{total} 项测试通过") - - if passed == total: - print("🎊 所有测试都通过了!系统改进功能正常工作。") - - print("\n💡 功能说明:") - print("1. 日志管理:最新日志显示在最上面") - print("2. 系统设置:只保留数据库备份模式") - print("3. 数据管理:新增管理员专用的数据表管理功能") - print("4. 所有管理员功能都有严格的权限控制") - - print("\n🎯 使用方法:") - print("• 使用admin账号登录系统") - print("• 在侧边栏可以看到管理员功能菜单") - print("• 点击相应功能进入管理页面") - print("• 数据管理可以查看和删除表中的数据") - - return True - else: - print("⚠️ 部分测试失败,请检查相关功能。") - return False - - except Exception as e: - print(f"💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/test_keyword_reply.py b/test_keyword_reply.py deleted file mode 100644 index 3958915..0000000 --- a/test_keyword_reply.py +++ /dev/null @@ -1,290 +0,0 @@ -#!/usr/bin/env python3 -""" -关键词回复功能测试脚本 -用于验证关键词匹配是否正常工作 -""" - -import asyncio -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from db_manager import db_manager -from XianyuAutoAsync import XianyuLive -from loguru import logger - -def test_keyword_database(): - """测试关键词数据库操作""" - print("🗄️ 开始测试关键词数据库操作...") - - test_cookie_id = "test_cookie_001" - - # 1. 清理测试数据 - print("\n1️⃣ 清理测试数据...") - try: - with db_manager.lock: - cursor = db_manager.conn.cursor() - cursor.execute("DELETE FROM keywords WHERE cookie_id = ?", (test_cookie_id,)) - db_manager.conn.commit() - print(" ✅ 测试数据清理完成") - except Exception as e: - print(f" ❌ 清理测试数据失败: {e}") - return False - - # 2. 添加测试关键词 - print("\n2️⃣ 添加测试关键词...") - test_keywords = [ - ("你好", "您好!欢迎咨询,有什么可以帮助您的吗?"), - ("价格", "这个商品的价格很优惠哦,{send_user_name}!"), - ("包邮", "全国包邮,放心购买!"), - ("发货", "我们会在24小时内发货"), - ("退换", "支持7天无理由退换货") - ] - - try: - success = db_manager.save_keywords(test_cookie_id, test_keywords) - if success: - print(f" ✅ 成功添加 {len(test_keywords)} 个关键词") - else: - print(" ❌ 添加关键词失败") - return False - except Exception as e: - print(f" ❌ 添加关键词异常: {e}") - return False - - # 3. 验证关键词保存 - print("\n3️⃣ 验证关键词保存...") - try: - saved_keywords = db_manager.get_keywords(test_cookie_id) - if len(saved_keywords) == len(test_keywords): - print(f" ✅ 关键词保存验证成功: {len(saved_keywords)} 个") - for keyword, reply in saved_keywords: - print(f" '{keyword}' -> '{reply[:30]}...'") - else: - print(f" ❌ 关键词数量不匹配: 期望 {len(test_keywords)}, 实际 {len(saved_keywords)}") - return False - except Exception as e: - print(f" ❌ 验证关键词异常: {e}") - return False - - print("\n✅ 关键词数据库操作测试完成!") - return True - -async def test_keyword_matching(): - """测试关键词匹配功能""" - print("\n🔍 开始测试关键词匹配功能...") - - test_cookie_id = "test_cookie_001" - - # 创建一个简化的测试类 - class TestKeywordMatcher: - def __init__(self, cookie_id): - self.cookie_id = cookie_id - - async def get_keyword_reply(self, send_user_name: str, send_user_id: str, send_message: str) -> str: - """获取关键词匹配回复""" - try: - from db_manager import db_manager - - # 获取当前账号的关键词列表 - keywords = db_manager.get_keywords(self.cookie_id) - - if not keywords: - print(f" 调试: 账号 {self.cookie_id} 没有配置关键词") - return None - - # 遍历关键词,查找匹配 - for keyword, reply in keywords: - if keyword.lower() in send_message.lower(): - # 进行变量替换 - try: - formatted_reply = reply.format( - send_user_name=send_user_name, - send_user_id=send_user_id, - send_message=send_message - ) - print(f" 调试: 关键词匹配成功: '{keyword}' -> {formatted_reply}") - return f"[关键词回复] {formatted_reply}" - except Exception as format_error: - print(f" 调试: 关键词回复变量替换失败: {format_error}") - # 如果变量替换失败,返回原始内容 - return f"[关键词回复] {reply}" - - print(f" 调试: 未找到匹配的关键词: {send_message}") - return None - - except Exception as e: - print(f" 调试: 获取关键词回复失败: {e}") - return None - - # 创建测试实例 - test_matcher = TestKeywordMatcher(test_cookie_id) - - # 测试消息和期望结果 - test_cases = [ - { - "message": "你好", - "expected_keyword": "你好", - "should_match": True - }, - { - "message": "请问价格多少?", - "expected_keyword": "价格", - "should_match": True - }, - { - "message": "包邮吗?", - "expected_keyword": "包邮", - "should_match": True - }, - { - "message": "什么时候发货?", - "expected_keyword": "发货", - "should_match": True - }, - { - "message": "可以退换吗?", - "expected_keyword": "退换", - "should_match": True - }, - { - "message": "这是什么材质的?", - "expected_keyword": None, - "should_match": False - } - ] - - success_count = 0 - - for i, test_case in enumerate(test_cases, 1): - print(f"\n{i}️⃣ 测试消息: '{test_case['message']}'") - - try: - reply = await test_matcher.get_keyword_reply( - send_user_name="测试用户", - send_user_id="test_user_001", - send_message=test_case['message'] - ) - - if test_case['should_match']: - if reply: - print(f" ✅ 匹配成功: {reply}") - if test_case['expected_keyword'] in reply or test_case['expected_keyword'] in test_case['message']: - success_count += 1 - else: - print(f" ⚠️ 匹配的关键词不符合预期") - else: - print(f" ❌ 期望匹配但未匹配") - else: - if reply: - print(f" ❌ 不应该匹配但却匹配了: {reply}") - else: - print(f" ✅ 正确未匹配") - success_count += 1 - - except Exception as e: - print(f" ❌ 测试异常: {e}") - - print(f"\n📊 测试结果: {success_count}/{len(test_cases)} 个测试通过") - - if success_count == len(test_cases): - print("✅ 关键词匹配功能测试完成!") - return True - else: - print("❌ 部分测试失败") - return False - -def test_reply_priority(): - """测试回复优先级""" - print("\n🎯 开始测试回复优先级...") - - test_cookie_id = "test_cookie_001" - - # 检查AI回复状态 - print("\n1️⃣ 检查AI回复状态...") - try: - ai_settings = db_manager.get_ai_reply_settings(test_cookie_id) - ai_enabled = ai_settings.get('ai_enabled', False) - print(f" AI回复状态: {'启用' if ai_enabled else '禁用'}") - except Exception as e: - print(f" ❌ 检查AI回复状态失败: {e}") - return False - - # 检查关键词数量 - print("\n2️⃣ 检查关键词配置...") - try: - keywords = db_manager.get_keywords(test_cookie_id) - print(f" 关键词数量: {len(keywords)} 个") - if len(keywords) > 0: - print(" 关键词列表:") - for keyword, reply in keywords[:3]: # 只显示前3个 - print(f" '{keyword}' -> '{reply[:30]}...'") - except Exception as e: - print(f" ❌ 检查关键词配置失败: {e}") - return False - - # 检查默认回复 - print("\n3️⃣ 检查默认回复配置...") - try: - default_reply = db_manager.get_default_reply(test_cookie_id) - if default_reply and default_reply.get('enabled', False): - print(f" 默认回复: 启用") - print(f" 默认回复内容: {default_reply.get('reply_content', '')[:50]}...") - else: - print(f" 默认回复: 禁用") - except Exception as e: - print(f" ❌ 检查默认回复配置失败: {e}") - return False - - print("\n📋 回复优先级说明:") - print(" 1. API回复 (最高优先级)") - print(" 2. AI回复 (如果启用)") - print(" 3. 关键词匹配 (如果AI禁用)") - print(" 4. 默认回复 (最低优先级)") - - if not ai_enabled and len(keywords) > 0: - print("\n✅ 当前配置下,关键词匹配应该正常工作!") - return True - elif ai_enabled: - print("\n⚠️ 当前AI回复已启用,关键词匹配会被跳过") - print(" 如需测试关键词匹配,请先禁用AI回复") - return True - else: - print("\n⚠️ 当前没有配置关键词,将使用默认回复") - return True - -async def main(): - """主测试函数""" - print("🚀 关键词回复功能测试开始") - print("=" * 50) - - # 测试数据库操作 - db_ok = test_keyword_database() - if not db_ok: - print("\n❌ 数据库操作测试失败") - return - - # 测试关键词匹配 - match_ok = await test_keyword_matching() - if not match_ok: - print("\n❌ 关键词匹配测试失败") - return - - # 测试回复优先级 - priority_ok = test_reply_priority() - if not priority_ok: - print("\n❌ 回复优先级测试失败") - return - - print("\n" + "=" * 50) - print("🎉 所有测试通过!关键词回复功能正常!") - print("\n📋 使用说明:") - print("1. 在Web界面的'自动回复'页面配置关键词") - print("2. 确保AI回复已禁用(如果要使用关键词匹配)") - print("3. 发送包含关键词的消息进行测试") - print("4. 关键词匹配支持变量替换:{send_user_name}, {send_user_id}, {send_message}") - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/test_multiuser_system.py b/test_multiuser_system.py deleted file mode 100644 index 0c841ce..0000000 --- a/test_multiuser_system.py +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env python3 -""" -多用户系统功能测试 -""" - -import asyncio -import json -import time -from db_manager import db_manager - -async def test_user_registration(): - """测试用户注册功能""" - print("🧪 测试用户注册功能") - print("-" * 40) - - # 测试邮箱验证码生成 - print("1️⃣ 测试验证码生成...") - code = db_manager.generate_verification_code() - print(f" 生成的验证码: {code}") - assert len(code) == 6 and code.isdigit(), "验证码应该是6位数字" - print(" ✅ 验证码生成正常") - - # 测试保存验证码 - print("\n2️⃣ 测试验证码保存...") - test_email = "test@example.com" - success = db_manager.save_verification_code(test_email, code) - assert success, "验证码保存应该成功" - print(" ✅ 验证码保存成功") - - # 测试验证码验证 - print("\n3️⃣ 测试验证码验证...") - valid = db_manager.verify_email_code(test_email, code) - assert valid, "正确的验证码应该验证成功" - print(" ✅ 验证码验证成功") - - # 测试验证码重复使用 - print("\n4️⃣ 测试验证码重复使用...") - valid_again = db_manager.verify_email_code(test_email, code) - assert not valid_again, "已使用的验证码不应该再次验证成功" - print(" ✅ 验证码重复使用被正确阻止") - - # 测试用户创建 - print("\n5️⃣ 测试用户创建...") - test_username = "testuser" - test_password = "testpass123" - - # 先清理可能存在的测试用户 - try: - db_manager.conn.execute("DELETE FROM users WHERE username = ? OR email = ?", (test_username, test_email)) - db_manager.conn.commit() - except: - pass - - success = db_manager.create_user(test_username, test_email, test_password) - assert success, "用户创建应该成功" - print(" ✅ 用户创建成功") - - # 测试重复用户名 - print("\n6️⃣ 测试重复用户名...") - success = db_manager.create_user(test_username, "another@example.com", test_password) - assert not success, "重复用户名应该创建失败" - print(" ✅ 重复用户名被正确拒绝") - - # 测试重复邮箱 - print("\n7️⃣ 测试重复邮箱...") - success = db_manager.create_user("anotheruser", test_email, test_password) - assert not success, "重复邮箱应该创建失败" - print(" ✅ 重复邮箱被正确拒绝") - - # 测试用户查询 - print("\n8️⃣ 测试用户查询...") - user = db_manager.get_user_by_username(test_username) - assert user is not None, "应该能查询到创建的用户" - assert user['username'] == test_username, "用户名应该匹配" - assert user['email'] == test_email, "邮箱应该匹配" - print(" ✅ 用户查询成功") - - # 测试密码验证 - print("\n9️⃣ 测试密码验证...") - valid = db_manager.verify_user_password(test_username, test_password) - assert valid, "正确密码应该验证成功" - - invalid = db_manager.verify_user_password(test_username, "wrongpassword") - assert not invalid, "错误密码应该验证失败" - print(" ✅ 密码验证正常") - - # 清理测试数据 - print("\n🧹 清理测试数据...") - db_manager.conn.execute("DELETE FROM users WHERE username = ?", (test_username,)) - db_manager.conn.execute("DELETE FROM email_verifications WHERE email = ?", (test_email,)) - db_manager.conn.commit() - print(" ✅ 测试数据清理完成") - -def test_user_isolation(): - """测试用户数据隔离""" - print("\n🧪 测试用户数据隔离") - print("-" * 40) - - # 创建测试用户 - print("1️⃣ 创建测试用户...") - user1_name = "testuser1" - user2_name = "testuser2" - user1_email = "user1@test.com" - user2_email = "user2@test.com" - password = "testpass123" - - # 清理可能存在的测试数据 - try: - db_manager.conn.execute("DELETE FROM cookies WHERE id LIKE 'test_%'") - db_manager.conn.execute("DELETE FROM users WHERE username IN (?, ?)", (user1_name, user2_name)) - db_manager.conn.commit() - except: - pass - - # 创建用户 - success1 = db_manager.create_user(user1_name, user1_email, password) - success2 = db_manager.create_user(user2_name, user2_email, password) - assert success1 and success2, "用户创建应该成功" - - user1 = db_manager.get_user_by_username(user1_name) - user2 = db_manager.get_user_by_username(user2_name) - user1_id = user1['id'] - user2_id = user2['id'] - print(f" ✅ 用户创建成功: {user1_name}(ID:{user1_id}), {user2_name}(ID:{user2_id})") - - # 测试Cookie隔离 - print("\n2️⃣ 测试Cookie数据隔离...") - - # 用户1添加cookies - db_manager.save_cookie("test_cookie_1", "cookie_value_1", user1_id) - db_manager.save_cookie("test_cookie_2", "cookie_value_2", user1_id) - - # 用户2添加cookies - db_manager.save_cookie("test_cookie_3", "cookie_value_3", user2_id) - db_manager.save_cookie("test_cookie_4", "cookie_value_4", user2_id) - - # 验证用户1只能看到自己的cookies - user1_cookies = db_manager.get_all_cookies(user1_id) - user1_cookie_ids = set(user1_cookies.keys()) - expected_user1_cookies = {"test_cookie_1", "test_cookie_2"} - - assert expected_user1_cookies.issubset(user1_cookie_ids), f"用户1应该能看到自己的cookies: {expected_user1_cookies}" - assert "test_cookie_3" not in user1_cookie_ids, "用户1不应该看到用户2的cookies" - assert "test_cookie_4" not in user1_cookie_ids, "用户1不应该看到用户2的cookies" - print(" ✅ 用户1的Cookie隔离正常") - - # 验证用户2只能看到自己的cookies - user2_cookies = db_manager.get_all_cookies(user2_id) - user2_cookie_ids = set(user2_cookies.keys()) - expected_user2_cookies = {"test_cookie_3", "test_cookie_4"} - - assert expected_user2_cookies.issubset(user2_cookie_ids), f"用户2应该能看到自己的cookies: {expected_user2_cookies}" - assert "test_cookie_1" not in user2_cookie_ids, "用户2不应该看到用户1的cookies" - assert "test_cookie_2" not in user2_cookie_ids, "用户2不应该看到用户1的cookies" - print(" ✅ 用户2的Cookie隔离正常") - - # 测试关键字隔离 - print("\n3️⃣ 测试关键字数据隔离...") - - # 添加关键字 - user1_keywords = [("hello", "user1 reply"), ("price", "user1 price")] - user2_keywords = [("hello", "user2 reply"), ("info", "user2 info")] - - db_manager.save_keywords("test_cookie_1", user1_keywords) - db_manager.save_keywords("test_cookie_3", user2_keywords) - - # 验证关键字隔离 - user1_all_keywords = db_manager.get_all_keywords(user1_id) - user2_all_keywords = db_manager.get_all_keywords(user2_id) - - assert "test_cookie_1" in user1_all_keywords, "用户1应该能看到自己的关键字" - assert "test_cookie_3" not in user1_all_keywords, "用户1不应该看到用户2的关键字" - - assert "test_cookie_3" in user2_all_keywords, "用户2应该能看到自己的关键字" - assert "test_cookie_1" not in user2_all_keywords, "用户2不应该看到用户1的关键字" - print(" ✅ 关键字数据隔离正常") - - # 测试备份隔离 - print("\n4️⃣ 测试备份数据隔离...") - - # 用户1备份 - user1_backup = db_manager.export_backup(user1_id) - user1_backup_cookies = [row[0] for row in user1_backup['data']['cookies']['rows']] - - assert "test_cookie_1" in user1_backup_cookies, "用户1备份应该包含自己的cookies" - assert "test_cookie_2" in user1_backup_cookies, "用户1备份应该包含自己的cookies" - assert "test_cookie_3" not in user1_backup_cookies, "用户1备份不应该包含其他用户的cookies" - assert "test_cookie_4" not in user1_backup_cookies, "用户1备份不应该包含其他用户的cookies" - print(" ✅ 用户1备份隔离正常") - - # 用户2备份 - user2_backup = db_manager.export_backup(user2_id) - user2_backup_cookies = [row[0] for row in user2_backup['data']['cookies']['rows']] - - assert "test_cookie_3" in user2_backup_cookies, "用户2备份应该包含自己的cookies" - assert "test_cookie_4" in user2_backup_cookies, "用户2备份应该包含自己的cookies" - assert "test_cookie_1" not in user2_backup_cookies, "用户2备份不应该包含其他用户的cookies" - assert "test_cookie_2" not in user2_backup_cookies, "用户2备份不应该包含其他用户的cookies" - print(" ✅ 用户2备份隔离正常") - - # 清理测试数据 - print("\n🧹 清理测试数据...") - db_manager.conn.execute("DELETE FROM keywords WHERE cookie_id LIKE 'test_%'") - db_manager.conn.execute("DELETE FROM cookies WHERE id LIKE 'test_%'") - db_manager.conn.execute("DELETE FROM users WHERE username IN (?, ?)", (user1_name, user2_name)) - db_manager.conn.commit() - print(" ✅ 测试数据清理完成") - -async def test_email_sending(): - """测试邮件发送功能(模拟)""" - print("\n🧪 测试邮件发送功能") - print("-" * 40) - - print("📧 邮件发送功能测试(需要网络连接)") - print(" 注意:这将发送真实的邮件,请确保邮箱地址正确") - - test_email = input("请输入测试邮箱地址(回车跳过): ").strip() - - if test_email: - print(f" 正在发送测试邮件到: {test_email}") - code = db_manager.generate_verification_code() - - try: - success = await db_manager.send_verification_email(test_email, code) - if success: - print(" ✅ 邮件发送成功!请检查邮箱") - else: - print(" ❌ 邮件发送失败") - except Exception as e: - print(f" ❌ 邮件发送异常: {e}") - else: - print(" ⏭️ 跳过邮件发送测试") - -async def main(): - """主测试函数""" - print("🚀 多用户系统功能测试") - print("=" * 60) - - try: - # 测试用户注册功能 - await test_user_registration() - - # 测试用户数据隔离 - test_user_isolation() - - # 测试邮件发送(可选) - await test_email_sending() - - print("\n" + "=" * 60) - print("🎉 所有测试通过!多用户系统功能正常") - - print("\n📋 测试总结:") - print("✅ 用户注册功能正常") - print("✅ 邮箱验证码功能正常") - print("✅ 用户数据隔离正常") - print("✅ Cookie数据隔离正常") - print("✅ 关键字数据隔离正常") - print("✅ 备份数据隔离正常") - - print("\n💡 下一步:") - print("1. 运行迁移脚本: python migrate_to_multiuser.py") - print("2. 重启应用程序") - print("3. 访问 /register.html 测试用户注册") - print("4. 测试多用户登录和数据隔离") - - except AssertionError as e: - print(f"\n❌ 测试失败: {e}") - return False - except Exception as e: - print(f"\n💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - - return True - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/test_notification_deduplication.py b/test_notification_deduplication.py deleted file mode 100644 index 484eee5..0000000 --- a/test_notification_deduplication.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python3 -""" -测试通知防重复机制 -验证Token刷新异常通知不会重复发送 -""" - -import asyncio -import time -from unittest.mock import AsyncMock, patch, MagicMock -from XianyuAutoAsync import XianyuLive - -async def test_notification_deduplication(): - """测试通知防重复机制""" - print("🧪 测试通知防重复机制") - print("=" * 50) - - # 创建测试用的XianyuLive实例 - test_cookies = "unb=test123; _m_h5_tk=test_token_123456789" - - try: - xianyu = XianyuLive(test_cookies, "test_account") - print("✅ XianyuLive 实例创建成功") - except Exception as e: - print(f"❌ 创建 XianyuLive 实例失败: {e}") - return - - # Mock数据库和通知方法 - with patch('XianyuAutoAsync.db_manager') as mock_db: - # 配置mock返回值 - mock_db.get_account_notifications.return_value = [ - { - 'enabled': True, - 'channel_type': 'qq', - 'channel_name': 'Test QQ', - 'channel_config': {'qq_number': '123456', 'api_url': 'http://test.com'} - } - ] - - # Mock QQ通知发送方法 - xianyu._send_qq_notification = AsyncMock() - - print("\n1️⃣ 测试首次发送通知...") - - # 第一次发送通知 - start_time = time.time() - await xianyu.send_token_refresh_notification("Token刷新失败: Session过期", "token_refresh_failed") - - # 验证通知是否发送 - if xianyu._send_qq_notification.called: - print("✅ 首次通知发送成功") - print(f" 发送时间: {time.strftime('%H:%M:%S', time.localtime(start_time))}") - else: - print("❌ 首次通知发送失败") - return - - print("\n2️⃣ 测试冷却期内重复发送...") - - # 重置mock调用计数 - xianyu._send_qq_notification.reset_mock() - - # 立即再次发送相同类型的通知 - await xianyu.send_token_refresh_notification("Token刷新失败: Session过期", "token_refresh_failed") - - # 验证通知是否被阻止 - if not xianyu._send_qq_notification.called: - print("✅ 冷却期内的重复通知被正确阻止") - cooldown_end = start_time + xianyu.notification_cooldown - print(f" 冷却期结束时间: {time.strftime('%H:%M:%S', time.localtime(cooldown_end))}") - else: - print("❌ 冷却期内的重复通知未被阻止") - - print("\n3️⃣ 测试不同类型的通知...") - - # 重置mock调用计数 - xianyu._send_qq_notification.reset_mock() - - # 发送不同类型的通知 - await xianyu.send_token_refresh_notification("初始化时无法获取有效Token", "token_init_failed") - - # 验证不同类型的通知是否正常发送 - if xianyu._send_qq_notification.called: - print("✅ 不同类型的通知正常发送") - else: - print("❌ 不同类型的通知发送失败") - - print("\n4️⃣ 测试通知类型统计...") - - # 显示当前的通知时间记录 - print(" 当前通知时间记录:") - for notification_type, last_time in xianyu.last_notification_time.items(): - print(f" {notification_type}: {time.strftime('%H:%M:%S', time.localtime(last_time))}") - - print(f" 通知冷却时间: {xianyu.notification_cooldown} 秒 ({xianyu.notification_cooldown // 60} 分钟)") - - print("\n5️⃣ 测试模拟真实场景...") - - # 模拟真实的Token刷新失败场景 - print(" 模拟场景: refresh_token() 失败 + init() 检查失败") - - # 重置mock和时间记录 - xianyu._send_qq_notification.reset_mock() - xianyu.last_notification_time.clear() - - # 模拟refresh_token失败 - await xianyu.send_token_refresh_notification("Token刷新失败: {'ret': ['FAIL_SYS_SESSION_EXPIRED::Session过期']}", "token_refresh_failed") - first_call_count = xianyu._send_qq_notification.call_count - - # 模拟init检查失败(这应该被阻止,因为是相同的根本原因) - await xianyu.send_token_refresh_notification("初始化时无法获取有效Token", "token_init_failed") - second_call_count = xianyu._send_qq_notification.call_count - - print(f" refresh_token 通知调用次数: {first_call_count}") - print(f" init 通知调用次数: {second_call_count - first_call_count}") - print(f" 总调用次数: {second_call_count}") - - if second_call_count == 2: - print("✅ 不同阶段的通知都正常发送(因为使用了不同的通知类型)") - elif second_call_count == 1: - print("⚠️ 只发送了一次通知(可能需要调整策略)") - else: - print(f"❌ 异常的调用次数: {second_call_count}") - -def test_notification_types(): - """测试通知类型分类""" - print("\n\n📋 通知类型分类说明") - print("=" * 50) - - notification_types = { - "token_refresh_failed": "Token刷新API调用失败", - "token_refresh_exception": "Token刷新过程中发生异常", - "token_init_failed": "初始化时无法获取有效Token", - "token_scheduled_refresh_failed": "定时Token刷新失败", - "db_update_failed": "数据库Cookie更新失败", - "cookie_id_missing": "Cookie ID不存在", - "cookie_update_failed": "Cookie更新失败" - } - - print("🏷️ 通知类型及其含义:") - for type_name, description in notification_types.items(): - print(f" • {type_name:<30} : {description}") - - print(f"\n⏰ 防重复机制:") - print(f" • 冷却时间: 5分钟 (300秒)") - print(f" • 相同类型的通知在冷却期内不会重复发送") - print(f" • 不同类型的通知可以正常发送") - print(f" • 成功发送后才会更新冷却时间") - -async def test_real_scenario_simulation(): - """测试真实场景模拟""" - print("\n\n🎭 真实场景模拟") - print("=" * 50) - - print("📋 场景描述:") - print(" 1. 用户的Cookie过期") - print(" 2. refresh_token() 调用失败,返回 Session过期") - print(" 3. init() 检查 current_token 为空,也发送通知") - print(" 4. 期望结果: 只收到一次通知,而不是两次") - - print("\n🔧 解决方案:") - print(" • 为不同阶段使用不同的通知类型") - print(" • token_refresh_failed: refresh_token API失败") - print(" • token_init_failed: 初始化检查失败") - print(" • 这样可以区分问题发生的具体阶段") - print(" • 但仍然避免短时间内的重复通知") - -if __name__ == "__main__": - try: - asyncio.run(test_notification_deduplication()) - test_notification_types() - asyncio.run(test_real_scenario_simulation()) - - print("\n" + "=" * 50) - print("🎉 通知防重复机制测试完成!") - print("\n💡 优化效果:") - print(" ✅ 避免了短时间内的重复通知") - print(" ✅ 保留了不同阶段的错误信息") - print(" ✅ 提供了5分钟的冷却期") - print(" ✅ 用户体验得到改善") - - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_page_access.py b/test_page_access.py deleted file mode 100644 index f76bdae..0000000 --- a/test_page_access.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python3 -""" -测试页面访问 -""" - -import requests -import time - -BASE_URL = "http://localhost:8080" - -def test_page_access(): - """测试页面访问""" - print("🚀 测试管理员页面访问") - print("=" * 50) - - pages = [ - ("主页", "/"), - ("登录页", "/login.html"), - ("注册页", "/register.html"), - ("管理页", "/admin"), - ("用户管理", "/user_management.html"), - ("日志管理", "/log_management.html") - ] - - for page_name, page_url in pages: - try: - print(f"测试 {page_name} ({page_url})...", end=" ") - response = requests.get(f"{BASE_URL}{page_url}", timeout=5) - - if response.status_code == 200: - print(f"✅ {response.status_code}") - else: - print(f"❌ {response.status_code}") - - except requests.exceptions.ConnectionError: - print("❌ 连接失败") - except requests.exceptions.Timeout: - print("❌ 超时") - except Exception as e: - print(f"❌ 错误: {e}") - - print("\n" + "=" * 50) - print("测试完成!") - -if __name__ == "__main__": - test_page_access() diff --git a/test_simple_token_filter.py b/test_simple_token_filter.py deleted file mode 100644 index 2ea3dfb..0000000 --- a/test_simple_token_filter.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/env python3 -""" -简单测试令牌过期过滤逻辑 -""" - -import sys -import os - -# 添加项目根目录到路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -def test_token_expiry_filter_logic(): - """测试令牌过期过滤逻辑""" - print("🧪 测试令牌过期过滤逻辑") - print("=" * 50) - - # 直接测试过滤逻辑,不依赖完整的XianyuLive实例 - def _is_normal_token_expiry(error_message: str) -> bool: - """检查是否是正常的令牌过期(这种情况不需要发送通知)""" - # 正常的令牌过期关键词 - normal_expiry_keywords = [ - 'FAIL_SYS_TOKEN_EXOIRED::令牌过期', - 'FAIL_SYS_TOKEN_EXPIRED::令牌过期', - 'FAIL_SYS_TOKEN_EXOIRED', - 'FAIL_SYS_TOKEN_EXPIRED', - '令牌过期' - ] - - # 检查错误消息是否包含正常的令牌过期关键词 - for keyword in normal_expiry_keywords: - if keyword in error_message: - return True - - return False - - # 测试用例 - test_cases = [ - # 应该被过滤的消息(返回True) - ("Token刷新失败: {'ret': ['FAIL_SYS_TOKEN_EXOIRED::令牌过期']}", True, "标准令牌过期"), - ("Token刷新失败: {'ret': ['FAIL_SYS_TOKEN_EXPIRED::令牌过期']}", True, "标准令牌过期(EXPIRED)"), - ("Token刷新异常: FAIL_SYS_TOKEN_EXOIRED", True, "简单令牌过期"), - ("Token刷新异常: FAIL_SYS_TOKEN_EXPIRED", True, "简单令牌过期(EXPIRED)"), - ("Token刷新失败: 令牌过期", True, "中文令牌过期"), - ("其他错误信息包含FAIL_SYS_TOKEN_EXOIRED的情况", True, "包含关键词"), - - # 不应该被过滤的消息(返回False) - ("Token刷新失败: {'ret': ['FAIL_SYS_SESSION_EXPIRED::Session过期']}", False, "Session过期"), - ("Token刷新异常: 网络连接超时", False, "网络异常"), - ("Token刷新失败: Cookie无效", False, "Cookie问题"), - ("初始化时无法获取有效Token", False, "初始化失败"), - ("Token刷新失败: 未知错误", False, "未知错误"), - ("Token刷新失败: API调用失败", False, "API失败"), - ("", False, "空消息"), - ] - - print("📋 测试用例:") - print("-" * 50) - - passed = 0 - total = len(test_cases) - - for i, (message, expected, description) in enumerate(test_cases, 1): - result = _is_normal_token_expiry(message) - - if result == expected: - status = "✅ 通过" - passed += 1 - else: - status = "❌ 失败" - - filter_action = "过滤" if result else "不过滤" - expected_action = "过滤" if expected else "不过滤" - - print(f"{i:2d}. {status} {description}") - print(f" 消息: {message[:60]}{'...' if len(message) > 60 else ''}") - print(f" 结果: {filter_action} | 期望: {expected_action}") - print() - - print("=" * 50) - print(f"📊 测试结果: {passed}/{total} 通过") - - if passed == total: - print("🎉 所有测试通过!过滤逻辑工作正常") - return True - else: - print("⚠️ 部分测试失败,需要检查过滤逻辑") - return False - -def show_real_world_examples(): - """显示真实世界的例子""" - print("\n\n📋 真实场景示例") - print("=" * 50) - - print("🚫 以下情况将不再发送通知(被过滤):") - examples_filtered = [ - "Token刷新失败: {'api': 'mtop.taobao.idlemessage.pc.login.token', 'data': {}, 'ret': ['FAIL_SYS_TOKEN_EXOIRED::令牌过期'], 'v': '1.0'}", - "Token刷新异常: FAIL_SYS_TOKEN_EXPIRED", - "Token刷新失败: 令牌过期" - ] - - for i, example in enumerate(examples_filtered, 1): - print(f"{i}. {example}") - - print("\n✅ 以下情况仍会发送通知(不被过滤):") - examples_not_filtered = [ - "Token刷新失败: {'api': 'mtop.taobao.idlemessage.pc.login.token', 'data': {}, 'ret': ['FAIL_SYS_SESSION_EXPIRED::Session过期'], 'v': '1.0'}", - "Token刷新异常: 网络连接超时", - "初始化时无法获取有效Token" - ] - - for i, example in enumerate(examples_not_filtered, 1): - print(f"{i}. {example}") - - print("\n💡 设计理念:") - print("• 令牌过期是正常现象,系统会自动重试刷新") - print("• Session过期通常意味着Cookie过期,需要用户手动更新") - print("• 网络异常等其他错误也需要用户关注") - print("• 减少无用通知,提升用户体验") - -def show_implementation_details(): - """显示实现细节""" - print("\n\n🔧 实现细节") - print("=" * 50) - - print("📍 修改位置:") - print("• 文件: XianyuAutoAsync.py") - print("• 方法: send_token_refresh_notification()") - print("• 新增: _is_normal_token_expiry() 过滤方法") - - print("\n🔍 过滤关键词:") - keywords = [ - 'FAIL_SYS_TOKEN_EXOIRED::令牌过期', - 'FAIL_SYS_TOKEN_EXPIRED::令牌过期', - 'FAIL_SYS_TOKEN_EXOIRED', - 'FAIL_SYS_TOKEN_EXPIRED', - '令牌过期' - ] - - for keyword in keywords: - print(f"• {keyword}") - - print("\n⚡ 执行流程:") - print("1. 调用 send_token_refresh_notification()") - print("2. 检查 _is_normal_token_expiry(error_message)") - print("3. 如果是正常令牌过期,记录调试日志并返回") - print("4. 如果不是,继续原有的通知发送流程") - - print("\n📝 日志记录:") - print("• 被过滤的消息会记录调试日志") - print("• 格式: '检测到正常的令牌过期,跳过通知: {error_message}'") - print("• 便于问题排查和功能验证") - -if __name__ == "__main__": - try: - success = test_token_expiry_filter_logic() - show_real_world_examples() - show_implementation_details() - - print("\n" + "=" * 50) - if success: - print("🎊 令牌过期通知过滤功能测试完成!") - print("✅ 用户将不再收到正常令牌过期的通知") - else: - print("❌ 测试失败,需要检查实现") - - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_status_display.html b/test_status_display.html deleted file mode 100644 index cee4dc2..0000000 --- a/test_status_display.html +++ /dev/null @@ -1,250 +0,0 @@ - - - - - - 状态显示测试 - - - - - -
-

账号状态显示测试

- -
-

修改前 vs 修改后对比

- -
-
-
修改前(带文字)
-
- - - - 启用 - -
- -
- - - - 禁用 - -
-
- -
-
修改后(仅图标)
-
- - - - -
- -
- - - - -
-
-
-
- -
-

表格中的效果预览

- - - - - - - - - - - - - - - - - - - - - - - - - - -
账号ID状态默认回复AI回复操作
测试账号001 -
- - - - -
-
启用AI启用 - -
测试账号002 -
- - - - -
-
禁用AI禁用 - -
-
- -
-

优势说明

-
-
-
✅ 修改后的优势
-
    -
  • ✓ 界面更简洁
  • -
  • ✓ 节省空间
  • -
  • ✓ 图标直观易懂
  • -
  • ✓ 视觉焦点更集中
  • -
  • ✓ 现代化设计风格
  • -
-
-
-
🎨 设计细节
-
    -
  • • 图标居中对齐
  • -
  • • 徽章尺寸优化
  • -
  • • 颜色保持一致
  • -
  • • 响应式设计
  • -
  • • 无障碍访问友好
  • -
-
-
-
- -
-
说明
-

- 状态栏现在只显示图标,不显示"启用"/"禁用"文字。 - 绿色勾号表示启用状态,红色叉号表示禁用状态。 - 鼠标悬停时可以显示提示信息。 -

-
-
- - - - - diff --git a/test_token_expiry_filter.py b/test_token_expiry_filter.py deleted file mode 100644 index ae6bb17..0000000 --- a/test_token_expiry_filter.py +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env python3 -""" -测试令牌过期通知过滤功能 -验证正常的令牌过期不会发送通知 -""" - -import asyncio -import time -from unittest.mock import AsyncMock, patch, MagicMock -import sys -import os - -# 添加项目根目录到路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -async def test_token_expiry_filter(): - """测试令牌过期通知过滤""" - print("🧪 测试令牌过期通知过滤功能") - print("=" * 60) - - # 动态导入 - try: - from XianyuAutoAsync import XianyuLive - print("✅ 成功导入 XianyuLive") - except Exception as e: - print(f"❌ 导入失败: {e}") - return - - # 创建测试实例 - test_cookies = "unb=test123; _m_h5_tk=test_token_123456789" - - try: - xianyu = XianyuLive(test_cookies, "test_account") - print("✅ XianyuLive 实例创建成功") - except Exception as e: - print(f"❌ 创建实例失败: {e}") - return - - # Mock外部依赖 - with patch('db_manager.db_manager') as mock_db: - # 配置数据库mock - mock_db.get_account_notifications.return_value = [ - { - 'enabled': True, - 'channel_type': 'qq', - 'channel_name': 'Test QQ', - 'channel_config': {'qq_number': '123456', 'api_url': 'http://test.com'} - } - ] - - # Mock QQ通知发送方法 - xianyu._send_qq_notification = AsyncMock() - - print("\n📋 测试用例设计") - print("-" * 40) - - # 测试用例:应该被过滤的错误消息(不发送通知) - filtered_messages = [ - "Token刷新失败: {'ret': ['FAIL_SYS_TOKEN_EXOIRED::令牌过期']}", - "Token刷新失败: {'ret': ['FAIL_SYS_TOKEN_EXPIRED::令牌过期']}", - "Token刷新异常: FAIL_SYS_TOKEN_EXOIRED", - "Token刷新异常: FAIL_SYS_TOKEN_EXPIRED", - "Token刷新失败: 令牌过期", - ] - - # 测试用例:不应该被过滤的错误消息(需要发送通知) - unfiltered_messages = [ - "Token刷新失败: {'ret': ['FAIL_SYS_SESSION_EXPIRED::Session过期']}", - "Token刷新异常: 网络连接超时", - "Token刷新失败: Cookie无效", - "初始化时无法获取有效Token", - "Token刷新失败: 未知错误" - ] - - print("🚫 应该被过滤的消息(不发送通知):") - for i, msg in enumerate(filtered_messages, 1): - print(f" {i}. {msg}") - - print("\n✅ 不应该被过滤的消息(需要发送通知):") - for i, msg in enumerate(unfiltered_messages, 1): - print(f" {i}. {msg}") - - print("\n" + "=" * 60) - print("🧪 开始测试") - - # 测试1: 验证过滤功能 - print("\n1️⃣ 测试令牌过期消息过滤...") - - filtered_count = 0 - for i, message in enumerate(filtered_messages, 1): - xianyu._send_qq_notification.reset_mock() - await xianyu.send_token_refresh_notification(message, f"test_filtered_{i}") - - if not xianyu._send_qq_notification.called: - print(f" ✅ 消息 {i} 被正确过滤") - filtered_count += 1 - else: - print(f" ❌ 消息 {i} 未被过滤(应该被过滤)") - - print(f"\n 📊 过滤结果: {filtered_count}/{len(filtered_messages)} 条消息被正确过滤") - - # 测试2: 验证非过滤消息正常发送 - print("\n2️⃣ 测试非令牌过期消息正常发送...") - - sent_count = 0 - for i, message in enumerate(unfiltered_messages, 1): - xianyu._send_qq_notification.reset_mock() - await xianyu.send_token_refresh_notification(message, f"test_unfiltered_{i}") - - if xianyu._send_qq_notification.called: - print(f" ✅ 消息 {i} 正常发送") - sent_count += 1 - else: - print(f" ❌ 消息 {i} 未发送(应该发送)") - - print(f"\n 📊 发送结果: {sent_count}/{len(unfiltered_messages)} 条消息正常发送") - - # 测试3: 验证过滤逻辑 - print("\n3️⃣ 测试过滤逻辑详情...") - - test_cases = [ - ("FAIL_SYS_TOKEN_EXOIRED::令牌过期", True), - ("FAIL_SYS_TOKEN_EXPIRED::令牌过期", True), - ("FAIL_SYS_TOKEN_EXOIRED", True), - ("FAIL_SYS_TOKEN_EXPIRED", True), - ("令牌过期", True), - ("FAIL_SYS_SESSION_EXPIRED::Session过期", False), - ("网络连接超时", False), - ("Cookie无效", False), - ] - - for message, should_be_filtered in test_cases: - is_filtered = xianyu._is_normal_token_expiry(message) - if is_filtered == should_be_filtered: - status = "✅ 正确" - else: - status = "❌ 错误" - - filter_status = "过滤" if is_filtered else "不过滤" - expected_status = "过滤" if should_be_filtered else "不过滤" - print(f" {status} '{message}' -> {filter_status} (期望: {expected_status})") - - # 总结 - print("\n" + "=" * 60) - print("📊 测试总结") - - total_filtered = len([msg for msg in filtered_messages if xianyu._is_normal_token_expiry(msg)]) - total_unfiltered = len([msg for msg in unfiltered_messages if not xianyu._is_normal_token_expiry(msg)]) - - print(f"✅ 令牌过期消息过滤: {total_filtered}/{len(filtered_messages)} 正确") - print(f"✅ 非令牌过期消息: {total_unfiltered}/{len(unfiltered_messages)} 正确") - - if total_filtered == len(filtered_messages) and total_unfiltered == len(unfiltered_messages): - print("🎉 所有测试通过!令牌过期通知过滤功能正常工作") - else: - print("⚠️ 部分测试失败,需要检查过滤逻辑") - -def show_filter_explanation(): - """显示过滤机制说明""" - print("\n\n📋 令牌过期通知过滤机制说明") - print("=" * 60) - - print("🎯 设计目标:") - print(" • 避免正常的令牌过期发送通知") - print(" • 令牌过期是正常现象,系统会自动重试") - print(" • 只有真正的异常才需要通知用户") - - print("\n🔍 过滤规则:") - print(" 以下关键词的错误消息将被过滤(不发送通知):") - print(" • FAIL_SYS_TOKEN_EXOIRED::令牌过期") - print(" • FAIL_SYS_TOKEN_EXPIRED::令牌过期") - print(" • FAIL_SYS_TOKEN_EXOIRED") - print(" • FAIL_SYS_TOKEN_EXPIRED") - print(" • 令牌过期") - - print("\n✅ 仍会发送通知的情况:") - print(" • FAIL_SYS_SESSION_EXPIRED::Session过期 (Cookie过期)") - print(" • 网络连接异常") - print(" • API调用失败") - print(" • 其他未知错误") - - print("\n💡 优势:") - print(" • 减少无用通知,避免用户困扰") - print(" • 保留重要异常通知,便于及时处理") - print(" • 提升用户体验,通知更有价值") - - print("\n🔧 实现方式:") - print(" • 在发送通知前检查错误消息") - print(" • 使用关键词匹配识别正常的令牌过期") - print(" • 记录调试日志,便于问题排查") - -if __name__ == "__main__": - try: - asyncio.run(test_token_expiry_filter()) - show_filter_explanation() - - print("\n" + "=" * 60) - print("🎊 令牌过期通知过滤测试完成!") - - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/test_token_fix.py b/test_token_fix.py deleted file mode 100644 index 3c76623..0000000 --- a/test_token_fix.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python3 -""" -测试token修复 -""" - -import requests -import json - -BASE_URL = "http://localhost:8080" - -def test_admin_api_access(): - """测试管理员API访问""" - print("🚀 测试管理员API访问") - print("=" * 50) - - # 1. 管理员登录 - print("1. 管理员登录...") - login_response = requests.post(f"{BASE_URL}/login", - json={'username': 'admin', 'password': 'admin123'}) - - if not login_response.json()['success']: - print("❌ 管理员登录失败") - return False - - token = login_response.json()['token'] - headers = {'Authorization': f'Bearer {token}'} - print(f"✅ 管理员登录成功,token: {token[:20]}...") - - # 2. 测试管理员API - apis = [ - ("获取用户列表", "GET", "/admin/users"), - ("获取系统统计", "GET", "/admin/stats"), - ("获取系统日志", "GET", "/admin/logs?lines=10") - ] - - for api_name, method, endpoint in apis: - print(f"2. 测试 {api_name}...") - - if method == "GET": - response = requests.get(f"{BASE_URL}{endpoint}", headers=headers) - else: - response = requests.post(f"{BASE_URL}{endpoint}", headers=headers) - - if response.status_code == 200: - print(f" ✅ {api_name} 成功 (200)") - - # 显示部分数据 - try: - data = response.json() - if endpoint == "/admin/users": - users = data.get('users', []) - print(f" 用户数量: {len(users)}") - elif endpoint == "/admin/stats": - print(f" 总用户数: {data.get('users', {}).get('total', 0)}") - print(f" 总Cookie数: {data.get('cookies', {}).get('total', 0)}") - elif endpoint.startswith("/admin/logs"): - logs = data.get('logs', []) - print(f" 日志条数: {len(logs)}") - except: - pass - - elif response.status_code == 401: - print(f" ❌ {api_name} 失败 - 401 未授权") - return False - elif response.status_code == 403: - print(f" ❌ {api_name} 失败 - 403 权限不足") - return False - else: - print(f" ❌ {api_name} 失败 - {response.status_code}") - return False - - print("\n✅ 所有管理员API测试通过!") - return True - -def test_non_admin_access(): - """测试非管理员访问""" - print("\n🔒 测试非管理员访问限制") - print("=" * 50) - - # 使用无效token测试 - fake_headers = {'Authorization': 'Bearer invalid_token'} - - response = requests.get(f"{BASE_URL}/admin/users", headers=fake_headers) - if response.status_code == 401: - print("✅ 无效token被正确拒绝 (401)") - else: - print(f"❌ 无效token未被拒绝 ({response.status_code})") - return False - - # 测试无token访问 - response = requests.get(f"{BASE_URL}/admin/users") - if response.status_code == 401: - print("✅ 无token访问被正确拒绝 (401)") - else: - print(f"❌ 无token访问未被拒绝 ({response.status_code})") - return False - - return True - -def main(): - """主测试函数""" - print("🔧 Token修复验证测试") - print("=" * 60) - - print("📋 测试目标:") - print("• 验证管理员可以正常访问API") - print("• 验证token认证正常工作") - print("• 验证非管理员访问被拒绝") - - try: - # 测试管理员API访问 - admin_success = test_admin_api_access() - - # 测试非管理员访问限制 - security_success = test_non_admin_access() - - print("\n" + "=" * 60) - - if admin_success and security_success: - print("🎉 Token修复验证成功!") - - print("\n💡 现在可以正常使用:") - print("1. 使用admin账号登录主页") - print("2. 点击侧边栏的'用户管理'") - print("3. 点击侧边栏的'系统日志'") - print("4. 所有管理员功能都应该正常工作") - - print("\n🔑 Token存储统一:") - print("• 登录页面: 设置 'auth_token'") - print("• 主页面: 读取 'auth_token'") - print("• 管理员页面: 读取 'auth_token'") - print("• 所有页面现在使用统一的token key") - - return True - else: - print("❌ Token修复验证失败!") - return False - - except Exception as e: - print(f"💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/test_user_isolation_complete.py b/test_user_isolation_complete.py deleted file mode 100644 index a5b3e98..0000000 --- a/test_user_isolation_complete.py +++ /dev/null @@ -1,333 +0,0 @@ -#!/usr/bin/env python3 -""" -完整的多用户数据隔离测试 -""" - -import requests -import json -import sqlite3 -import time - -BASE_URL = "http://localhost:8080" - -def create_test_users(): - """创建测试用户""" - print("🧪 创建测试用户") - print("-" * 40) - - users = [ - {"username": "testuser1", "email": "user1@test.com", "password": "test123456"}, - {"username": "testuser2", "email": "user2@test.com", "password": "test123456"} - ] - - created_users = [] - - for user in users: - try: - # 清理可能存在的用户 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('DELETE FROM users WHERE username = ? OR email = ?', (user['username'], user['email'])) - cursor.execute('DELETE FROM email_verifications WHERE email = ?', (user['email'],)) - conn.commit() - conn.close() - - # 生成验证码 - session_id = f"test_{user['username']}_{int(time.time())}" - - # 生成图形验证码 - captcha_response = requests.post(f"{BASE_URL}/generate-captcha", - json={'session_id': session_id}) - if not captcha_response.json()['success']: - print(f" ❌ {user['username']}: 图形验证码生成失败") - continue - - # 获取图形验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id,)) - captcha_result = cursor.fetchone() - conn.close() - - if not captcha_result: - print(f" ❌ {user['username']}: 无法获取图形验证码") - continue - - captcha_code = captcha_result[0] - - # 验证图形验证码 - verify_response = requests.post(f"{BASE_URL}/verify-captcha", - json={'session_id': session_id, 'captcha_code': captcha_code}) - if not verify_response.json()['success']: - print(f" ❌ {user['username']}: 图形验证码验证失败") - continue - - # 发送邮箱验证码 - email_response = requests.post(f"{BASE_URL}/send-verification-code", - json={'email': user['email'], 'session_id': session_id}) - if not email_response.json()['success']: - print(f" ❌ {user['username']}: 邮箱验证码发送失败") - continue - - # 获取邮箱验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM email_verifications WHERE email = ? ORDER BY created_at DESC LIMIT 1', - (user['email'],)) - email_result = cursor.fetchone() - conn.close() - - if not email_result: - print(f" ❌ {user['username']}: 无法获取邮箱验证码") - continue - - email_code = email_result[0] - - # 注册用户 - register_response = requests.post(f"{BASE_URL}/register", - json={ - 'username': user['username'], - 'email': user['email'], - 'verification_code': email_code, - 'password': user['password'] - }) - - if register_response.json()['success']: - print(f" ✅ {user['username']}: 注册成功") - - # 登录获取token - login_response = requests.post(f"{BASE_URL}/login", - json={'username': user['username'], 'password': user['password']}) - - if login_response.json()['success']: - token = login_response.json()['token'] - user_id = login_response.json()['user_id'] - created_users.append({ - 'username': user['username'], - 'user_id': user_id, - 'token': token, - 'headers': {'Authorization': f'Bearer {token}'} - }) - print(f" ✅ {user['username']}: 登录成功,用户ID: {user_id}") - else: - print(f" ❌ {user['username']}: 登录失败") - else: - print(f" ❌ {user['username']}: 注册失败 - {register_response.json()['message']}") - - except Exception as e: - print(f" ❌ {user['username']}: 创建失败 - {e}") - - return created_users - -def test_cookie_isolation(users): - """测试Cookie数据隔离""" - print("\n🧪 测试Cookie数据隔离") - print("-" * 40) - - if len(users) < 2: - print("❌ 需要至少2个用户进行隔离测试") - return False - - user1, user2 = users[0], users[1] - - # 用户1添加cookies - print(f"1️⃣ {user1['username']} 添加cookies...") - cookies1 = [ - {"id": "test_cookie_user1_1", "value": "cookie_value_1"}, - {"id": "test_cookie_user1_2", "value": "cookie_value_2"} - ] - - for cookie in cookies1: - response = requests.post(f"{BASE_URL}/cookies", - json=cookie, - headers=user1['headers']) - if response.status_code == 200: - print(f" ✅ 添加cookie: {cookie['id']}") - else: - print(f" ❌ 添加cookie失败: {cookie['id']}") - - # 用户2添加cookies - print(f"\n2️⃣ {user2['username']} 添加cookies...") - cookies2 = [ - {"id": "test_cookie_user2_1", "value": "cookie_value_3"}, - {"id": "test_cookie_user2_2", "value": "cookie_value_4"} - ] - - for cookie in cookies2: - response = requests.post(f"{BASE_URL}/cookies", - json=cookie, - headers=user2['headers']) - if response.status_code == 200: - print(f" ✅ 添加cookie: {cookie['id']}") - else: - print(f" ❌ 添加cookie失败: {cookie['id']}") - - # 验证用户1只能看到自己的cookies - print(f"\n3️⃣ 验证 {user1['username']} 的cookie隔离...") - response1 = requests.get(f"{BASE_URL}/cookies", headers=user1['headers']) - if response1.status_code == 200: - user1_cookies = response1.json() - user1_cookie_ids = set(user1_cookies) - expected_user1 = {"test_cookie_user1_1", "test_cookie_user1_2"} - - if expected_user1.issubset(user1_cookie_ids): - print(f" ✅ {user1['username']} 能看到自己的cookies") - else: - print(f" ❌ {user1['username']} 看不到自己的cookies") - - if "test_cookie_user2_1" not in user1_cookie_ids and "test_cookie_user2_2" not in user1_cookie_ids: - print(f" ✅ {user1['username']} 看不到其他用户的cookies") - else: - print(f" ❌ {user1['username']} 能看到其他用户的cookies(隔离失败)") - - # 验证用户2只能看到自己的cookies - print(f"\n4️⃣ 验证 {user2['username']} 的cookie隔离...") - response2 = requests.get(f"{BASE_URL}/cookies", headers=user2['headers']) - if response2.status_code == 200: - user2_cookies = response2.json() - user2_cookie_ids = set(user2_cookies) - expected_user2 = {"test_cookie_user2_1", "test_cookie_user2_2"} - - if expected_user2.issubset(user2_cookie_ids): - print(f" ✅ {user2['username']} 能看到自己的cookies") - else: - print(f" ❌ {user2['username']} 看不到自己的cookies") - - if "test_cookie_user1_1" not in user2_cookie_ids and "test_cookie_user1_2" not in user2_cookie_ids: - print(f" ✅ {user2['username']} 看不到其他用户的cookies") - else: - print(f" ❌ {user2['username']} 能看到其他用户的cookies(隔离失败)") - - return True - -def test_cross_user_access(users): - """测试跨用户访问权限""" - print("\n🧪 测试跨用户访问权限") - print("-" * 40) - - if len(users) < 2: - print("❌ 需要至少2个用户进行权限测试") - return False - - user1, user2 = users[0], users[1] - - # 用户1尝试访问用户2的cookie - print(f"1️⃣ {user1['username']} 尝试访问 {user2['username']} 的cookie...") - - # 尝试获取用户2的关键字 - response = requests.get(f"{BASE_URL}/keywords/test_cookie_user2_1", headers=user1['headers']) - if response.status_code == 403: - print(f" ✅ 跨用户访问被正确拒绝 (403)") - elif response.status_code == 404: - print(f" ✅ 跨用户访问被拒绝 (404)") - else: - print(f" ❌ 跨用户访问未被拒绝 (状态码: {response.status_code})") - - # 尝试更新用户2的cookie状态 - response = requests.put(f"{BASE_URL}/cookies/test_cookie_user2_1/status", - json={"enabled": False}, - headers=user1['headers']) - if response.status_code == 403: - print(f" ✅ 跨用户操作被正确拒绝 (403)") - elif response.status_code == 404: - print(f" ✅ 跨用户操作被拒绝 (404)") - else: - print(f" ❌ 跨用户操作未被拒绝 (状态码: {response.status_code})") - - return True - -def cleanup_test_data(users): - """清理测试数据""" - print("\n🧹 清理测试数据") - print("-" * 40) - - try: - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 清理测试cookies - cursor.execute('DELETE FROM cookies WHERE id LIKE "test_cookie_%"') - cookie_count = cursor.rowcount - - # 清理测试用户 - test_usernames = [user['username'] for user in users] - if test_usernames: - placeholders = ','.join(['?' for _ in test_usernames]) - cursor.execute(f'DELETE FROM users WHERE username IN ({placeholders})', test_usernames) - user_count = cursor.rowcount - else: - user_count = 0 - - # 清理测试验证码 - cursor.execute('DELETE FROM email_verifications WHERE email LIKE "%@test.com"') - email_count = cursor.rowcount - - cursor.execute('DELETE FROM captcha_codes WHERE session_id LIKE "test_%"') - captcha_count = cursor.rowcount - - conn.commit() - conn.close() - - print(f"✅ 清理完成:") - print(f" • 测试cookies: {cookie_count} 条") - print(f" • 测试用户: {user_count} 条") - print(f" • 邮箱验证码: {email_count} 条") - print(f" • 图形验证码: {captcha_count} 条") - - except Exception as e: - print(f"❌ 清理失败: {e}") - -def main(): - """主测试函数""" - print("🚀 多用户数据隔离完整测试") - print("=" * 60) - - try: - # 创建测试用户 - users = create_test_users() - - if len(users) < 2: - print("\n❌ 测试失败:无法创建足够的测试用户") - return False - - print(f"\n✅ 成功创建 {len(users)} 个测试用户") - - # 测试Cookie数据隔离 - cookie_isolation_success = test_cookie_isolation(users) - - # 测试跨用户访问权限 - cross_access_success = test_cross_user_access(users) - - # 清理测试数据 - cleanup_test_data(users) - - print("\n" + "=" * 60) - if cookie_isolation_success and cross_access_success: - print("🎉 多用户数据隔离测试全部通过!") - - print("\n📋 测试总结:") - print("✅ 用户注册和登录功能正常") - print("✅ Cookie数据完全隔离") - print("✅ 跨用户访问被正确拒绝") - print("✅ 用户权限验证正常") - - print("\n🔒 安全特性:") - print("• 每个用户只能看到自己的数据") - print("• 跨用户访问被严格禁止") - print("• API层面权限验证完整") - print("• 数据库层面用户绑定正确") - - return True - else: - print("❌ 多用户数据隔离测试失败!") - return False - - except Exception as e: - print(f"\n💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/test_user_logging.py b/test_user_logging.py deleted file mode 100644 index cd030c3..0000000 --- a/test_user_logging.py +++ /dev/null @@ -1,318 +0,0 @@ -#!/usr/bin/env python3 -""" -测试用户日志显示功能 -""" - -import requests -import json -import time -import sqlite3 -from loguru import logger - -BASE_URL = "http://localhost:8080" - -def create_test_user(): - """创建测试用户""" - logger.info("创建测试用户...") - - user_data = { - "username": "logtest_user", - "email": "logtest@test.com", - "password": "test123456" - } - - try: - # 清理可能存在的用户 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('DELETE FROM users WHERE username = ? OR email = ?', (user_data['username'], user_data['email'])) - cursor.execute('DELETE FROM email_verifications WHERE email = ?', (user_data['email'],)) - conn.commit() - conn.close() - - # 生成验证码 - session_id = f"logtest_{int(time.time())}" - - # 生成图形验证码 - captcha_response = requests.post(f"{BASE_URL}/generate-captcha", - json={'session_id': session_id}) - if not captcha_response.json()['success']: - logger.error("图形验证码生成失败") - return None - - # 获取图形验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM captcha_codes WHERE session_id = ? ORDER BY created_at DESC LIMIT 1', - (session_id,)) - captcha_result = cursor.fetchone() - conn.close() - - if not captcha_result: - logger.error("无法获取图形验证码") - return None - - captcha_code = captcha_result[0] - - # 验证图形验证码 - verify_response = requests.post(f"{BASE_URL}/verify-captcha", - json={'session_id': session_id, 'captcha_code': captcha_code}) - if not verify_response.json()['success']: - logger.error("图形验证码验证失败") - return None - - # 发送邮箱验证码 - email_response = requests.post(f"{BASE_URL}/send-verification-code", - json={'email': user_data['email'], 'session_id': session_id}) - if not email_response.json()['success']: - logger.error("邮箱验证码发送失败") - return None - - # 获取邮箱验证码 - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - cursor.execute('SELECT code FROM email_verifications WHERE email = ? ORDER BY created_at DESC LIMIT 1', - (user_data['email'],)) - email_result = cursor.fetchone() - conn.close() - - if not email_result: - logger.error("无法获取邮箱验证码") - return None - - email_code = email_result[0] - - # 注册用户 - register_response = requests.post(f"{BASE_URL}/register", - json={ - 'username': user_data['username'], - 'email': user_data['email'], - 'verification_code': email_code, - 'password': user_data['password'] - }) - - if register_response.json()['success']: - logger.info(f"用户注册成功: {user_data['username']}") - - # 登录获取token - login_response = requests.post(f"{BASE_URL}/login", - json={'username': user_data['username'], 'password': user_data['password']}) - - if login_response.json()['success']: - token = login_response.json()['token'] - user_id = login_response.json()['user_id'] - return { - 'username': user_data['username'], - 'user_id': user_id, - 'token': token, - 'headers': {'Authorization': f'Bearer {token}'} - } - else: - logger.error("用户登录失败") - return None - else: - logger.error(f"用户注册失败: {register_response.json()['message']}") - return None - - except Exception as e: - logger.error(f"创建用户失败: {e}") - return None - -def test_user_operations(user): - """测试用户操作的日志显示""" - logger.info("测试用户操作的日志显示...") - - print(f"\n🧪 开始测试用户 {user['username']} 的操作日志") - print("请观察服务器日志,应该显示用户信息...") - print("-" * 50) - - # 1. 测试Cookie操作 - print("1️⃣ 测试Cookie操作...") - cookie_data = { - "id": "logtest_cookie", - "value": "test_cookie_value" - } - - response = requests.post(f"{BASE_URL}/cookies", json=cookie_data, headers=user['headers']) - if response.status_code == 200: - print(" ✅ Cookie添加成功") - else: - print(f" ❌ Cookie添加失败: {response.text}") - - # 2. 测试获取Cookie列表 - print("2️⃣ 测试获取Cookie列表...") - response = requests.get(f"{BASE_URL}/cookies", headers=user['headers']) - if response.status_code == 200: - print(" ✅ 获取Cookie列表成功") - else: - print(f" ❌ 获取Cookie列表失败: {response.text}") - - # 3. 测试关键字操作 - print("3️⃣ 测试关键字操作...") - keywords_data = { - "keywords": { - "你好": "您好,欢迎咨询!", - "价格": "价格请看商品详情" - } - } - - response = requests.post(f"{BASE_URL}/keywords/logtest_cookie", - json=keywords_data, headers=user['headers']) - if response.status_code == 200: - print(" ✅ 关键字更新成功") - else: - print(f" ❌ 关键字更新失败: {response.text}") - - # 4. 测试卡券操作 - print("4️⃣ 测试卡券操作...") - card_data = { - "name": "测试卡券", - "type": "text", - "text_content": "这是一个测试卡券", - "description": "用于测试日志显示的卡券" - } - - response = requests.post(f"{BASE_URL}/cards", json=card_data, headers=user['headers']) - if response.status_code == 200: - print(" ✅ 卡券创建成功") - else: - print(f" ❌ 卡券创建失败: {response.text}") - - # 5. 测试用户设置 - print("5️⃣ 测试用户设置...") - setting_data = { - "value": "#ff6600", - "description": "测试主题颜色" - } - - response = requests.put(f"{BASE_URL}/user-settings/theme_color", - json=setting_data, headers=user['headers']) - if response.status_code == 200: - print(" ✅ 用户设置更新成功") - else: - print(f" ❌ 用户设置更新失败: {response.text}") - - # 6. 测试权限验证(尝试访问不存在的Cookie) - print("6️⃣ 测试权限验证...") - response = requests.get(f"{BASE_URL}/keywords/nonexistent_cookie", headers=user['headers']) - if response.status_code == 403: - print(" ✅ 权限验证正常(403错误)") - else: - print(f" ⚠️ 权限验证结果: {response.status_code}") - - print("-" * 50) - print("🎯 操作测试完成,请检查服务器日志中的用户信息显示") - -def test_admin_operations(): - """测试管理员操作""" - print("\n🔧 测试管理员操作...") - - # 管理员登录 - admin_login = requests.post(f"{BASE_URL}/login", - json={'username': 'admin', 'password': 'admin123'}) - - if admin_login.json()['success']: - admin_token = admin_login.json()['token'] - admin_headers = {'Authorization': f'Bearer {admin_token}'} - - print(" ✅ 管理员登录成功") - - # 测试管理员获取Cookie列表 - response = requests.get(f"{BASE_URL}/cookies", headers=admin_headers) - if response.status_code == 200: - print(" ✅ 管理员获取Cookie列表成功") - else: - print(f" ❌ 管理员获取Cookie列表失败: {response.text}") - else: - print(" ❌ 管理员登录失败") - -def cleanup_test_data(user): - """清理测试数据""" - logger.info("清理测试数据...") - - try: - conn = sqlite3.connect('xianyu_data.db') - cursor = conn.cursor() - - # 清理测试用户 - cursor.execute('DELETE FROM users WHERE username = ?', (user['username'],)) - user_count = cursor.rowcount - - # 清理测试Cookie - cursor.execute('DELETE FROM cookies WHERE id = "logtest_cookie"') - cookie_count = cursor.rowcount - - # 清理测试卡券 - cursor.execute('DELETE FROM cards WHERE name = "测试卡券"') - card_count = cursor.rowcount - - # 清理测试验证码 - cursor.execute('DELETE FROM email_verifications WHERE email = "logtest@test.com"') - email_count = cursor.rowcount - - cursor.execute('DELETE FROM captcha_codes WHERE session_id LIKE "logtest_%"') - captcha_count = cursor.rowcount - - conn.commit() - conn.close() - - logger.info(f"清理完成: 用户{user_count}个, Cookie{cookie_count}个, 卡券{card_count}个, 邮箱验证码{email_count}个, 图形验证码{captcha_count}个") - - except Exception as e: - logger.error(f"清理失败: {e}") - -def main(): - """主测试函数""" - print("🚀 用户日志显示功能测试") - print("=" * 60) - - print("📋 测试目标:") - print("• 验证API请求日志显示用户信息") - print("• 验证业务操作日志显示用户信息") - print("• 验证权限验证日志显示用户信息") - print("• 验证管理员操作日志显示") - - try: - # 创建测试用户 - user = create_test_user() - - if not user: - print("❌ 测试失败:无法创建测试用户") - return False - - print(f"✅ 成功创建测试用户: {user['username']}") - - # 测试用户操作 - test_user_operations(user) - - # 测试管理员操作 - test_admin_operations() - - # 清理测试数据 - cleanup_test_data(user) - - print("\n" + "=" * 60) - print("🎉 用户日志显示功能测试完成!") - - print("\n📋 检查要点:") - print("✅ 1. API请求日志应显示: 【用户名#用户ID】") - print("✅ 2. 业务操作日志应显示用户信息") - print("✅ 3. 权限验证日志应显示操作用户") - print("✅ 4. 管理员操作应显示: 【admin#1】") - - print("\n💡 日志格式示例:") - print("🌐 【logtest_user#2】 API请求: POST /cookies") - print("✅ 【logtest_user#2】 API响应: POST /cookies - 200 (0.005s)") - print("📝 【logtest_user#2】 尝试添加Cookie: logtest_cookie") - print("✅ 【logtest_user#2】 Cookie添加成功: logtest_cookie") - - return True - - except Exception as e: - print(f"💥 测试异常: {e}") - import traceback - traceback.print_exc() - return False - -if __name__ == "__main__": - main() diff --git a/utils/xianyu_utils.py b/utils/xianyu_utils.py index 5e117e3..0204150 100644 --- a/utils/xianyu_utils.py +++ b/utils/xianyu_utils.py @@ -297,26 +297,47 @@ class MessagePackDecoder: 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解码 - decoded_data = base64.b64decode(data) - + 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.dumps(decoded_value, default=json_serializer) - + + 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)}") diff --git a/wechat-group.png b/wechat-group.png new file mode 100644 index 0000000..12a2990 Binary files /dev/null and b/wechat-group.png differ diff --git a/使用说明.md b/使用说明.md deleted file mode 100644 index 008c929..0000000 --- a/使用说明.md +++ /dev/null @@ -1,178 +0,0 @@ -# 闲鱼自动回复管理系统 - 使用说明 - -## 🎉 系统功能概述 - -本系统已完全实现您要求的所有功能: - -### ✅ 已实现功能 -1. **多Cookies支持** - 支持同时管理多个闲鱼账号 -2. **美观前端界面** - 响应式设计,支持Cookies和关键词的CRUD操作 -3. **SQLite数据库存储** - 持久化存储Cookies和关键词数据 -4. **关键词管理** - 每个账号独立的关键词回复设置 -5. **API接口** - 完整实现 `/xianyu/reply` 接口 -6. **智能回复** - 根据Cookie ID匹配对应关键词进行回复 -7. **用户认证** - 安全的登录认证系统 - -## 🚀 快速开始 - -### 1. 安装依赖 -```bash -pip install -r requirements.txt -``` - -### 2. 启动系统 -```bash -python Start.py -``` - -### 3. 访问系统 -- 打开浏览器访问:`http://localhost:8080` -- 默认登录账号: - - **用户名**:`admin` - - **密码**:`admin123` - -## 📋 系统使用流程 - -### 步骤1:登录系统 -1. 访问 `http://localhost:8080` -2. 输入用户名和密码登录 -3. 成功登录后进入管理界面 - -### 步骤2:添加闲鱼账号 -1. 在"添加新账号"区域填写: - - **账号ID**:唯一标识(如:account1, 主账号等) - - **Cookie值**:完整的闲鱼Cookie字符串 -2. 点击"添加账号"按钮 - -### 步骤3:设置关键词回复 -1. 在账号列表中点击"关键词"按钮 -2. 添加关键词和对应的回复内容 -3. 支持变量替换: - - `{send_user_name}` - 发送者昵称 - - `{send_user_id}` - 发送者ID - - `{send_message}` - 发送的消息内容 -4. 点击"保存更改" - -### 步骤4:系统自动运行 -- 系统会自动监控闲鱼消息 -- 根据关键词匹配自动回复 -- 所有操作都有详细日志记录 - -## 🔧 功能详解 - -### 多账号管理 -- **添加账号**:支持添加无限数量的闲鱼账号 -- **修改Cookie**:可以随时更新账号的Cookie值 -- **删除账号**:删除不需要的账号及其关键词 -- **独立运行**:每个账号独立运行,互不干扰 - -### 关键词回复系统 -- **精确匹配**:支持关键词精确匹配 -- **变量替换**:回复内容支持动态变量 -- **优先级**:账号级关键词优先于全局关键词 -- **默认回复**:未匹配关键词时使用默认回复 - -### API接口 -- **接口地址**:`POST http://localhost:8080/xianyu/reply` -- **功能**:根据cookie_id和消息内容返回回复内容 -- **自动调用**:系统收到消息时自动调用此接口 - -## 📊 系统架构 - -``` -用户界面 (Web) ←→ FastAPI服务器 ←→ SQLite数据库 - ↓ - CookieManager - ↓ - XianyuLive (多实例) - ↓ - 闲鱼WebSocket连接 -``` - -## 🔐 安全说明 - -### 登录认证 -- 所有管理功能都需要登录认证 -- Session token有效期24小时 -- 自动登录状态检查 - -### 数据安全 -- Cookie数据加密存储在SQLite数据库 -- 界面上不显示完整Cookie值 -- 支持安全的Cookie更新机制 - -## 📝 日志系统 - -### 日志文件位置 -- 日志目录:`logs/` -- 文件格式:`xianyu_YYYY-MM-DD.log` -- 自动轮转:每天一个文件,保留7天 - -### 日志内容 -- 系统启动和关闭 -- 账号添加、修改、删除 -- 消息接收和发送 -- 错误和异常信息 - -## 🛠️ 故障排除 - -### 常见问题 - -#### 1. Cookie过期 -**现象**:日志显示"Session过期" -**解决**:在Web界面更新对应账号的Cookie值 - -#### 2. 无法连接闲鱼 -**现象**:WebSocket连接失败 -**解决**:检查网络连接和Cookie是否有效 - -#### 3. 关键词不匹配 -**现象**:收到消息但没有自动回复 -**解决**:检查关键词设置,确保关键词包含在消息中 - -#### 4. 登录失败 -**现象**:无法登录管理界面 -**解决**:确认用户名密码正确(admin/admin123) - -### 系统要求 -- Python 3.7+ -- Windows/Linux/macOS -- 网络连接 -- 有效的闲鱼账号Cookie - -## 🔄 更新和维护 - -### 配置文件 -- 主配置:`global_config.yml` -- 数据库:`xianyu_data.db` -- 静态文件:`static/` 目录 - -### 备份建议 -- 定期备份 `xianyu_data.db` 文件 -- 备份 `global_config.yml` 配置文件 -- 备份自定义的关键词文件 - -## 📞 技术支持 - -### 测试系统 -运行测试脚本检查系统状态: -```bash -python test_system.py -``` - -### 重新创建配置 -如果配置文件损坏,运行: -```bash -python create_config.py -``` - -## 🎯 使用建议 - -1. **Cookie获取**:使用浏览器开发者工具获取完整Cookie -2. **关键词设置**:设置常用的咨询关键词和回复 -3. **定期检查**:定期查看日志确保系统正常运行 -4. **备份数据**:重要数据请及时备份 - ---- - -**注意**:本系统仅供学习交流使用,请遵守相关法律法规和平台规则。 diff --git a/商品管理功能说明.md b/商品管理功能说明.md deleted file mode 100644 index 9ece907..0000000 --- a/商品管理功能说明.md +++ /dev/null @@ -1,199 +0,0 @@ -# 🛍️ 商品管理功能使用说明 - -## 📋 功能概述 - -新增的商品管理功能可以自动收集和管理各个闲鱼账号的商品信息,为自动发货提供更准确的商品数据支持。 - -## 🎯 核心特性 - -### 1. 自动商品信息收集 -- **消息触发收集**:接收消息时自动提取商品ID并保存到数据库 -- **API获取详情**:通过闲鱼API获取完整商品信息 -- **智能去重**:商品ID唯一,避免重复存储 -- **增量更新**:有详情的商品不会被空数据覆盖 - -### 2. 多账号商品管理 -- **账号隔离**:每个Cookie账号的商品信息独立管理 -- **批量查看**:支持查看所有账号或指定账号的商品 -- **筛选功能**:可按账号ID筛选商品列表 - -### 3. 商品详情编辑 -- **可视化编辑**:提供专门的编辑界面修改商品详情 -- **JSON格式**:支持复杂的商品信息结构 -- **实时保存**:修改后立即保存到数据库 - -### 4. 自动发货增强 -- **优先级策略**:优先使用API获取商品信息,失败时从数据库获取 -- **智能匹配**:基于商品标题、描述、分类进行关键词匹配 -- **容错机制**:API失败时自动降级到数据库数据 - -## 🗄️ 数据库结构 - -### 商品信息表 (item_info) -```sql -CREATE TABLE item_info ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - cookie_id TEXT NOT NULL, -- 所属账号ID - item_id TEXT NOT NULL, -- 商品ID - item_title TEXT, -- 商品标题 - item_description TEXT, -- 商品描述 - item_category TEXT, -- 商品分类 - item_price TEXT, -- 商品价格 - item_detail TEXT, -- 完整商品详情(JSON) - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - UNIQUE(cookie_id, item_id) -- 联合唯一索引 -); -``` - -## 🚀 使用方法 - -### 1. 访问商品管理 -1. 登录系统后,点击侧边栏"商品管理"菜单 -2. 系统会自动加载所有账号的商品信息 - -### 2. 筛选商品 -1. 使用"筛选账号"下拉框选择特定账号 -2. 点击"刷新"按钮更新商品列表 - -### 3. 编辑商品详情 -1. 在商品列表中点击"编辑详情"按钮 -2. 在弹出的编辑框中修改商品详情(JSON格式) -3. 点击"保存"按钮保存修改 - -### 4. 商品信息自动收集 -- **无需手动操作**:系统会在以下情况自动收集商品信息: - - 接收到闲鱼消息时 - - 自动发货时获取商品详情 - - 调用商品信息API时 - -## 🔧 技术实现 - -### 1. 数据收集流程 -``` -接收消息 → 提取商品ID → 调用API获取详情 → 保存到数据库 - ↓ -如果API失败 → 仅保存商品ID → 后续可手动补充详情 -``` - -### 2. 自动发货增强流程 -``` -触发自动发货 → 优先调用API获取商品信息 - ↓ -API成功 → 使用API数据进行关键词匹配 - ↓ -API失败 → 从数据库获取商品信息 → 使用数据库数据匹配 -``` - -### 3. 数据更新策略 -- **新商品**:直接插入数据库 -- **已存在且无详情**:更新为有详情的数据 -- **已存在且有详情**:跳过更新,保护现有数据 - -## 📊 API接口 - -### 获取所有商品 -```http -GET /items -Authorization: Bearer {token} -``` - -### 获取指定账号商品 -```http -GET /items/cookie/{cookie_id} -Authorization: Bearer {token} -``` - -### 获取商品详情 -```http -GET /items/{cookie_id}/{item_id} -Authorization: Bearer {token} -``` - -### 更新商品详情 -```http -PUT /items/{cookie_id}/{item_id} -Content-Type: application/json -Authorization: Bearer {token} - -{ - "item_detail": "{JSON格式的商品详情}" -} -``` - -## 🎨 界面功能 - -### 商品列表显示 -- **账号ID**:商品所属的闲鱼账号 -- **商品ID**:闲鱼商品的唯一标识 -- **商品标题**:从API获取的商品标题 -- **商品分类**:商品所属分类 -- **价格**:商品价格信息 -- **更新时间**:最后更新时间 -- **操作按钮**:编辑详情功能 - -### 编辑详情界面 -- **大文本框**:支持编辑大量JSON数据 -- **格式验证**:保存前验证JSON格式 -- **实时保存**:修改后立即生效 - -## 🔍 故障排除 - -### 常见问题 - -1. **商品信息为空** - - 原因:API获取失败,只保存了商品ID - - 解决:手动编辑商品详情,补充信息 - -2. **自动发货匹配失败** - - 原因:商品信息不完整,关键词匹配失败 - - 解决:编辑商品详情,添加相关关键词 - -3. **商品重复显示** - - 原因:不同账号可能有相同商品ID - - 说明:这是正常现象,系统按账号隔离 - -### 调试方法 - -1. **查看日志** - ```bash - # 查看商品信息收集日志 - grep "商品信息" logs/xianyu_*.log - - # 查看自动发货日志 - grep "自动发货" logs/xianyu_*.log - ``` - -2. **数据库查询** - ```python - from db_manager import db_manager - - # 查看所有商品 - items = db_manager.get_all_items() - print(f"共有 {len(items)} 个商品") - - # 查看特定账号商品 - items = db_manager.get_items_by_cookie("account_id") - print(f"该账号有 {len(items)} 个商品") - ``` - -## 💡 最佳实践 - -1. **定期检查商品信息** - - 定期查看商品管理页面 - - 补充缺失的商品详情 - - 优化关键词匹配规则 - -2. **合理设置发货规则** - - 根据商品信息设置精确的关键词 - - 利用商品分类进行规则匹配 - - 测试匹配效果 - -3. **监控系统日志** - - 关注商品信息收集日志 - - 监控自动发货匹配情况 - - 及时处理异常情况 - ---- - -🎉 **商品管理功能让您的闲鱼自动发货更加智能和准确!** diff --git a/日志管理功能说明.md b/日志管理功能说明.md deleted file mode 100644 index 5ed5981..0000000 --- a/日志管理功能说明.md +++ /dev/null @@ -1,296 +0,0 @@ -# 📋 实时日志管理功能说明 - -## 📋 功能概述 - -新增了**实时日志管理功能**,可以实时收集和显示系统的控制台日志输出,支持滚动查看、过滤搜索、自动刷新和统计分析。 - -## 🔥 实时日志特色 - -### 📡 真正的实时日志 -- **实时收集**:直接从Python logging系统收集日志 -- **内存缓存**:在内存中保存最新的2000条日志 -- **零延迟**:无需读取文件,直接从内存获取 -- **控制台同步**:与控制台输出完全同步 - -## ✨ 主要功能 - -### 1. 实时日志显示 -- 📊 **实时收集**:直接从Python logging系统收集日志 -- 🔄 **自动刷新**:支持每5秒自动刷新日志 -- 📜 **滚动查看**:支持滚动查看所有历史日志 -- 🎨 **语法高亮**:不同日志级别使用不同颜色显示 -- 💾 **内存缓存**:最多保存2000条最新日志 - -### 2. 强大的过滤功能 -- 🏷️ **日志级别过滤**:DEBUG、INFO、WARNING、ERROR、CRITICAL -- 📦 **来源模块过滤**:自动化模块、Web服务器、数据库管理、Cookie管理 -- 🔍 **关键词搜索**:支持实时搜索日志内容 -- 📏 **行数控制**:可选择显示100/200/500/1000行日志 -- 🎯 **服务器端过滤**:支持在API层面进行过滤,提高性能 - -### 3. 便捷的操作功能 -- 🔄 **手动刷新**:点击刷新按钮立即获取最新日志 -- 🗑️ **清空显示**:清空当前显示的日志内容 -- 💥 **清空服务器日志**:清空服务器内存中的所有日志 -- ⏯️ **自动刷新开关**:一键开启/关闭自动刷新 -- 📊 **统计信息**:显示详细的日志统计和分析 - -### 4. 统计分析功能 -- 📈 **总体统计**:总日志数、内存使用率 -- 📊 **级别分布**:各日志级别的数量和百分比 -- 🏷️ **来源分布**:各模块的日志数量和百分比 -- 📋 **实时更新**:统计信息实时更新 - -## 🎯 界面设计 - -### 菜单位置 -在左侧导航栏中,位于"商品管理"和"系统设置"之间: -``` -📦 商品管理 -📋 日志管理 ← 新增 -⚙️ 系统设置 -``` - -### 页面布局 -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ 📋 日志管理 [刷新] [清空显示] [清空服务器] [统计] [自动刷新] │ -├─────────────────────────────────────────────────────────────────────┤ -│ [日志级别▼] [来源模块▼] [搜索框] [显示行数▼] │ -├─────────────────────────────────────────────────────────────────────┤ -│ 系统日志 [1250条日志] [刚刚更新] │ -│ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 2025-01-23 12:30:45.123 [INFO] reply_server: 服务启动 │ │ -│ │ 2025-01-23 12:30:46.456 [ERROR] db_manager: 连接失败 │ │ -│ │ 2025-01-23 12:30:47.789 [WARNING] cookie_manager: 令牌过期 │ │ -│ │ 2025-01-23 12:30:48.012 [DEBUG] XianyuAutoAsync: 处理消息 │ │ -│ │ ... │ │ -│ └─────────────────────────────────────────────────────────────────┘ │ -└─────────────────────────────────────────────────────────────────────┘ -``` - -## 🔧 技术实现 - -### 核心架构:实时日志收集器 -1. **LogCollector类** - ```python - class LogCollector: - def __init__(self, max_logs: int = 2000): - self.logs = deque(maxlen=max_logs) # 循环缓冲区 - self.handler = LogHandler(self) # 自定义日志处理器 - ``` - -2. **LogHandler处理器** - ```python - class LogHandler(logging.Handler): - def emit(self, record: logging.LogRecord): - self.collector.add_log(record) # 实时收集日志 - ``` - -3. **全局集成** - - 在Start.py中初始化日志收集器 - - 自动注册到Python logging系统 - - 所有模块的日志都会被自动收集 - -### 前端实现 -1. **HTML结构** - - 添加日志管理菜单项 - - 创建日志显示页面 - - 设计过滤器和控制按钮 - - 新增统计信息模态框 - -2. **CSS样式** - - 深色主题的日志容器 - - 不同级别的颜色区分 - - 滚动条美化 - - 响应式布局 - -3. **JavaScript功能** - - 实时日志获取和显示 - - 客户端和服务器端过滤 - - 自动刷新机制 - - 统计信息展示 - - 页面切换处理 - -### 后端API接口 -1. **获取日志** - ```python - @app.get("/logs") - async def get_logs(lines: int = 200, level: str = None, source: str = None): - ``` - -2. **日志统计** - ```python - @app.get("/logs/stats") - async def get_log_stats(): - ``` - -3. **清空日志** - ```python - @app.post("/logs/clear") - async def clear_logs(): - ``` - -## 📊 实时日志格式 - -### 收集的日志信息 -```json -{ - "timestamp": "2025-01-23T12:30:45.123000", - "level": "INFO", - "source": "XianyuAutoAsync", - "function": "process_message", - "line": 1234, - "message": "处理消息成功" -} -``` - -### 日志来源 -- **XianyuAutoAsync**: 自动化核心模块 -- **reply_server**: Web服务器 -- **db_manager**: 数据库管理 -- **cookie_manager**: Cookie管理 -- **log_collector**: 日志收集器 -- **Start**: 启动模块 -- **test_***: 测试模块 - -### 支持的日志级别 -- 🔵 **DEBUG**:调试信息(蓝色) -- 🟢 **INFO**:一般信息(绿色) -- 🟡 **WARNING**:警告信息(黄色) -- 🔴 **ERROR**:错误信息(红色) -- 🟣 **CRITICAL**:严重错误(紫色,加粗) - -## 🚀 使用方法 - -### 1. 访问日志管理 -1. 登录系统后,点击左侧菜单的"日志管理" -2. 系统会自动加载最新的200条日志 -3. 日志以时间倒序显示,最新的在底部 - -### 2. 过滤日志 -- **按级别过滤**:选择特定的日志级别(如只看ERROR) -- **按来源过滤**:选择特定的模块(如只看数据库相关) -- **关键词搜索**:输入关键词实时搜索日志内容 -- **调整行数**:选择显示更多或更少的日志行数 - -### 3. 自动刷新 -1. 点击"开启自动刷新"按钮 -2. 系统每5秒自动获取最新日志 -3. 再次点击可停止自动刷新 - -### 4. 手动操作 -- **刷新**:立即获取最新日志 -- **清空显示**:清空当前显示的日志(不删除服务器数据) -- **清空服务器日志**:清空服务器内存中的所有日志 -- **统计信息**:查看详细的日志统计和分析 -- **滚动查看**:使用鼠标滚轮或滚动条查看历史日志 - -### 5. 统计分析 -- **总体统计**:查看日志总数和内存使用情况 -- **级别分布**:查看各日志级别的数量和百分比 -- **来源分布**:查看各模块的日志数量和百分比 -- **实时更新**:统计信息随日志实时更新 - -## 💾 内存日志管理 - -### 内存缓存机制 -- **循环缓冲区**:使用deque实现,最多保存2000条日志 -- **自动清理**:超出容量时自动删除最旧的日志 -- **线程安全**:使用锁机制确保多线程安全 -- **零文件依赖**:完全基于内存,无需读取日志文件 - -### 性能优势 -- **零延迟**:直接从内存获取,无文件I/O -- **实时性**:与控制台输出完全同步 -- **高效过滤**:在内存中进行过滤,速度极快 -- **低资源消耗**:内存占用可控,不会无限增长 - -## ⚠️ 注意事项 - -### 1. 性能考虑 -- 大日志文件可能影响加载速度 -- 建议设置合理的显示行数 -- 自动刷新会增加服务器负载 - -### 2. 权限要求 -- 需要管理员权限才能访问 -- 确保日志文件有读取权限 -- 网络连接稳定性影响实时性 - -### 3. 浏览器兼容性 -- 建议使用现代浏览器 -- 支持WebSocket的浏览器效果更佳 -- 移动端可能显示效果有限 - -## 🔮 未来扩展 - -### 1. 高级功能 -- 📊 **日志统计**:错误率、调用频率统计 -- 📈 **图表展示**:日志趋势图表 -- 🔔 **实时告警**:错误日志实时通知 -- 💾 **日志下载**:支持导出日志文件 - -### 2. 性能优化 -- 🚀 **WebSocket**:实时推送新日志 -- 💾 **缓存机制**:减少文件读取次数 -- 🔄 **增量更新**:只获取新增日志 -- 📦 **压缩传输**:减少网络传输量 - -### 3. 用户体验 -- 🎨 **主题切换**:支持亮色/暗色主题 -- 🔍 **高级搜索**:正则表达式搜索 -- 📌 **书签功能**:标记重要日志 -- 📱 **移动适配**:优化移动端显示 - -## 🎉 功能特色 - -### 1. 实时性 -- 自动刷新机制确保日志实时性 -- 页面切换时智能停止刷新 -- 手动刷新立即获取最新内容 - -### 2. 易用性 -- 直观的界面设计 -- 丰富的过滤选项 -- 便捷的操作按钮 - -### 3. 专业性 -- 类似IDE的日志显示效果 -- 语法高亮和颜色区分 -- 专业的等宽字体 - -### 4. 可扩展性 -- 模块化的代码结构 -- 易于添加新功能 -- 支持多种日志格式 - -## 🆚 对比:文件日志 vs 实时日志 - -| 特性 | 文件日志 | 实时日志 | -|------|---------|---------| -| **实时性** | 需要刷新文件 | 完全实时 | -| **性能** | 文件I/O开销 | 内存访问,极快 | -| **同步性** | 可能有延迟 | 与控制台同步 | -| **资源消耗** | 磁盘I/O | 内存占用 | -| **历史记录** | 永久保存 | 最新2000条 | -| **过滤效率** | 需要解析 | 内存中过滤 | -| **部署复杂度** | 需要日志文件 | 无额外依赖 | - -## 🎯 使用建议 - -### 适用场景 -- ✅ **开发调试**:实时查看程序运行状态 -- ✅ **问题排查**:快速定位错误和异常 -- ✅ **性能监控**:监控系统运行情况 -- ✅ **用户支持**:协助用户解决问题 - -### 最佳实践 -1. **开启自动刷新**:实时监控系统状态 -2. **使用过滤器**:快速找到关注的日志 -3. **查看统计信息**:了解系统整体状况 -4. **定期清空**:避免内存占用过多 - ---- - -🎉 **实时日志管理功能已完成,提供了真正的实时日志查看、过滤和分析能力!** diff --git a/自动发货功能说明.md b/自动发货功能说明.md deleted file mode 100644 index 059cdcb..0000000 --- a/自动发货功能说明.md +++ /dev/null @@ -1,265 +0,0 @@ -# 🚚 自动发货功能使用说明 - -## 📋 功能概述 - -自动发货功能可以在买家付款成功后,根据商品信息自动匹配发货规则,并发送对应的卡券内容给买家。 - -## 🎯 工作流程 - -### 1. 触发条件 -- 系统收到"等待卖家发货"消息时自动触发 -- 表示买家已完成付款,等待卖家发货 - -### 2. 商品信息获取 -``` -买家付款成功 → 提取商品ID → 调用闲鱼API → 获取商品详情 -``` - -**获取的信息包括:** -- 商品标题 -- 商品描述 -- 商品分类 -- 商品价格 -- 其他相关信息 - -### 3. 智能匹配规则 -``` -商品信息 → 组合搜索文本 → 匹配发货规则 → 选择最佳规则 -``` - -**匹配策略:** -- 优先匹配关键字长度较长的规则(更精确) -- 支持商品标题、描述、分类的综合匹配 -- 支持模糊匹配和部分匹配 - -### 4. 自动发货执行 -``` -匹配规则 → 获取卡券内容 → 发送给买家 → 更新统计 -``` - -## 🎫 卡券类型说明 - -### 1. API接口类型 -**适用场景:** 需要动态获取内容的卡券 -- 调用外部API获取实时数据 -- 支持GET/POST请求 -- 可配置请求头和参数 -- 自动处理API响应 - -**配置示例:** -```json -{ - "url": "https://api.example.com/get-card", - "method": "GET", - "timeout": 10, - "headers": "{\"Authorization\": \"Bearer token\"}", - "params": "{\"type\": \"recharge\", \"amount\": 100}" -} -``` - -### 2. 固定文字类型 -**适用场景:** 标准化的文字内容 -- 发送预设的固定文字 -- 适合使用说明、激活码等 -- 内容固定不变 - -**内容示例:** -``` -🎉 恭喜您获得VIP会员卡! - -会员卡号:VIP2024001 -有效期:2024年12月31日 - -专属权益: -✅ 免费配送 -✅ 专属客服 -✅ 会员折扣 - -感谢您的支持! -``` - -### 3. 批量数据类型 -**适用场景:** 唯一性数据,如卡密 -- 逐条消费预设数据 -- 线程安全,防止重复发送 -- 自动管理库存 - -**数据格式:** -``` -CARD001:PASS001 -CARD002:PASS002 -CARD003:PASS003 -``` - -## ⚙️ 配置步骤 - -### 1. 创建卡券 -1. 登录管理界面 -2. 点击"卡券管理"菜单 -3. 点击"添加卡券"按钮 -4. 选择卡券类型并配置相应参数 -5. 启用卡券 - -### 2. 配置发货规则 -1. 点击"自动发货"菜单 -2. 点击"添加规则"按钮 -3. 设置商品关键字 -4. 选择对应的卡券 -5. 设置发货数量 -6. 启用规则 - -### 3. 关键字配置建议 - -**商品分类关键字:** -- `手机` - 匹配手机类商品 -- `数码` - 匹配数码产品 -- `服装` - 匹配服装类商品 -- `鞋子` - 匹配鞋类商品 -- `家居` - 匹配家居用品 - -**品牌关键字:** -- `iPhone` - 匹配iPhone商品 -- `小米` - 匹配小米商品 -- `华为` - 匹配华为商品 - -**功能关键字:** -- `充值` - 匹配充值类商品 -- `会员` - 匹配会员服务 -- `游戏` - 匹配游戏相关商品 - -## 📊 统计功能 - -### 发货统计 -- 总发货次数 -- 各规则发货次数 -- 发货成功率 -- 卡券消耗情况 - -### 库存管理 -- 批量数据剩余数量 -- 卡券启用状态 -- 规则启用状态 - -## 🔧 高级配置 - -### 环境变量 -```bash -# 启用自动发货 -AUTO_DELIVERY_ENABLED=true - -# 自动发货超时时间 -AUTO_DELIVERY_TIMEOUT=30 - -# API卡券请求超时 -API_CARD_TIMEOUT=10 - -# 批量数据并发保护 -BATCH_DATA_LOCK_TIMEOUT=5 -``` - -### 日志配置 -系统会记录详细的发货日志: -- 商品信息获取日志 -- 规则匹配日志 -- 发货执行日志 -- 错误处理日志 - -## 🚨 注意事项 - -### 1. 商品ID提取 -- 系统会尝试从多个字段提取商品ID -- 如果提取失败,会使用默认ID -- 建议检查日志确认提取是否成功 - -### 2. API卡券配置 -- 确保API地址可访问 -- 检查请求头和参数格式 -- 设置合适的超时时间 -- 处理API异常情况 - -### 3. 批量数据管理 -- 定期检查数据库存 -- 及时补充批量数据 -- 监控消耗速度 -- 设置库存预警 - -### 4. 规则优先级 -- 关键字越长,优先级越高 -- 避免关键字冲突 -- 定期优化匹配规则 -- 测试匹配效果 - -## 🧪 测试方法 - -### 1. 功能测试 -```bash -python test-item-info-delivery.py -``` - -### 2. 手动测试 -1. 创建测试卡券和规则 -2. 模拟"等待卖家发货"消息 -3. 检查发货是否正常 -4. 验证统计数据更新 - -### 3. 日志检查 -查看日志文件确认: -- 商品信息获取是否成功 -- 规则匹配是否正确 -- 发货内容是否正确发送 - -## 🔍 故障排除 - -### 常见问题 - -**1. 未触发自动发货** -- 检查发货规则是否启用 -- 检查卡券是否启用 -- 检查关键字是否匹配 -- 查看错误日志 - -**2. 商品信息获取失败** -- 检查Cookie是否有效 -- 检查网络连接 -- 检查商品ID是否正确 -- 查看API调用日志 - -**3. 批量数据用完** -- 检查数据库存 -- 及时补充数据 -- 考虑使用其他类型卡券 - -**4. API卡券调用失败** -- 检查API地址和参数 -- 检查网络连接 -- 增加超时时间 -- 查看API响应日志 - -## 📈 性能优化 - -### 1. 数据库优化 -- 定期清理过期数据 -- 优化查询索引 -- 监控数据库性能 - -### 2. 网络优化 -- 设置合适的超时时间 -- 使用连接池 -- 实现重试机制 - -### 3. 并发控制 -- 批量数据消费使用锁机制 -- 避免重复发货 -- 控制并发数量 - -## 💡 最佳实践 - -1. **规则设计**:关键字要具体明确,避免过于宽泛 -2. **库存管理**:定期检查批量数据库存,及时补充 -3. **监控告警**:设置发货失败告警,及时处理异常 -4. **测试验证**:新规则上线前充分测试 -5. **日志分析**:定期分析发货日志,优化匹配规则 - ---- - -🎉 **自动发货功能让您的闲鱼店铺实现真正的自动化运营!** diff --git a/获取所有商品功能说明.md b/获取所有商品功能说明.md deleted file mode 100644 index ca70f87..0000000 --- a/获取所有商品功能说明.md +++ /dev/null @@ -1,203 +0,0 @@ -# 📦 获取所有商品功能说明 - -## 📋 功能概述 - -在商品管理界面新增了"获取所有商品"功能,支持选择指定账号,一键获取该账号下的所有商品信息,并将详细结果打印到控制台。 - -## ✨ 主要功能 - -### 1. 界面功能 -- 🎯 **账号选择**:使用现有的账号筛选下拉框选择目标账号 -- 🔄 **一键获取**:点击"获取所有商品"按钮开始获取 -- 📊 **状态显示**:按钮显示获取进度状态 -- 🔔 **结果通知**:获取完成后显示成功消息和商品数量 - -### 2. 后端功能 -- 🔐 **账号验证**:验证选中账号的有效性 -- 🔄 **自动重试**:支持token失效时自动刷新重试(最多3次) -- 📝 **详细日志**:完整的获取过程日志记录 -- 🖨️ **控制台输出**:格式化的商品信息打印到控制台 - -## 🎯 使用方法 - -### 1. 访问商品管理 -1. 登录系统后,点击左侧菜单的"商品管理" -2. 进入商品管理页面 - -### 2. 选择账号 -1. 在页面上方的"筛选账号"下拉框中选择目标账号 -2. 确保选择了有效的账号(不是"全部账号") - -### 3. 获取商品 -1. 点击"获取所有商品"按钮 -2. 按钮会显示"获取中..."状态 -3. 等待获取完成 - -### 4. 查看结果 -1. 获取完成后会显示成功消息 -2. 控制台会打印详细的商品信息 -3. 商品列表会自动刷新 - -## 🔧 技术实现 - -### 前端实现 -```javascript -// 获取所有商品信息 -async function getAllItemsFromAccount() { - const cookieSelect = document.getElementById('itemCookieFilter'); - const selectedCookieId = cookieSelect.value; - - // 调用后端API - const response = await fetch(`${apiBase}/items/get-all-from-account`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${authToken}` - }, - body: JSON.stringify({ - cookie_id: selectedCookieId - }) - }); -} -``` - -### 后端API -```python -@app.post("/items/get-all-from-account") -async def get_all_items_from_account(request: dict, _: None = Depends(require_auth)): - """从指定账号获取所有商品信息""" - # 1. 验证参数 - # 2. 获取账号信息 - # 3. 创建XianyuLive实例 - # 4. 调用get_item_list_info方法 - # 5. 返回结果 -``` - -### 核心方法 -```python -async def get_item_list_info(self, retry_count=0): - """获取商品信息,自动处理token失效的情况""" - # 1. 检查重试次数 - # 2. 刷新token(如果需要) - # 3. 构造请求参数 - # 4. 发送API请求 - # 5. 处理响应结果 - # 6. 打印商品信息到控制台 -``` - -## 📊 API参数说明 - -### 请求参数 -```json -{ - "cookie_id": "账号ID" -} -``` - -### 响应格式 -```json -{ - "success": true, - "message": "成功获取 5 个商品,详细信息已打印到控制台", - "total_count": 5 -} -``` - -### 错误响应 -```json -{ - "success": false, - "message": "错误信息" -} -``` - -## 🖨️ 控制台输出格式 - -``` -================================================================================ -📦 账号 12345678 的商品列表 (5 个商品) -================================================================================ - -🔸 商品 1: - 商品ID: 123456789 - 商品标题: iPhone 13 Pro Max 256G - 价格: 6999 - 状态: 在售 - 创建时间: 2025-07-23 10:30:00 - 更新时间: 2025-07-23 16:45:00 - 图片数量: 8 - 详细信息: { - "id": "123456789", - "title": "iPhone 13 Pro Max 256G", - "price": "6999", - "status": "在售", - ... - } - -🔸 商品 2: - ... - -================================================================================ -✅ 商品列表获取完成 -================================================================================ -``` - -## ⚠️ 注意事项 - -### 1. 使用限制 -- 需要选择有效的账号(不能是"全部账号") -- 需要账号的cookie信息有效 -- 需要网络连接正常 - -### 2. 错误处理 -- Token失效时会自动刷新重试 -- 最多重试3次,避免无限循环 -- 网络异常时会显示错误信息 - -### 3. 性能考虑 -- 获取过程可能需要几秒钟时间 -- 大量商品时控制台输出较多 -- 建议在网络良好时使用 - -## 🔮 功能特色 - -### 1. 智能重试机制 -- 自动检测token失效 -- 智能刷新token后重试 -- 避免因token问题导致的失败 - -### 2. 详细信息输出 -- 完整的商品信息展示 -- 格式化的控制台输出 -- 便于调试和分析 - -### 3. 用户友好界面 -- 直观的操作按钮 -- 实时状态反馈 -- 清晰的成功/失败提示 - -### 4. 完整的日志记录 -- 详细的操作日志 -- 错误信息记录 -- 便于问题排查 - -## 🚀 扩展可能 - -### 1. 批量操作 -- 支持多个账号批量获取 -- 导出商品信息到文件 -- 商品信息对比分析 - -### 2. 数据处理 -- 商品信息入库存储 -- 商品状态监控 -- 价格变化追踪 - -### 3. 界面优化 -- 商品信息表格显示 -- 商品图片预览 -- 筛选和搜索功能 - ---- - -🎉 **获取所有商品功能已完成,支持一键获取指定账号的所有商品信息!**