# download-service **Repository Path**: surpass/download-service ## Basic Information - **Project Name**: download-service - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-09-29 - **Last Updated**: 2025-09-29 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Download Service API 一个基于Node.js和Express.js的文件下载队列服务,支持URL队列管理、批量下载、进度跟踪等功能。 ## 🚀 功能特性 - **队列管理**: 自动管理下载任务队列,FIFO顺序处理 - **进度跟踪**: 实时监控下载进度和状态 - **持久化存储**: 任务状态自动保存,服务重启后自动恢复 - **重试机制**: 失败任务自动重试,可配置重试次数 - **智能文件名**: 支持中文文件名,自动处理编码问题 - **RESTful API**: 完整的REST API接口 - **安全防护**: 包含限流、参数验证、错误处理等安全措施 ## 📦 安装与启动 ### 安装依赖 ```bash npm install ``` ### 启动服务 ```bash # 基础启动 npm start # 开发模式 npm run dev # 生产模式 npm run prod # 命令行参数启动 node app.js -p 9990 # 指定端口9990 node app.js -p 8080 -h 0.0.0.0 # 指定端口8080,监听所有接口 node app.js -d /custom/downloads # 指定下载目录 node app.js -c "remix_userkey=xxx; remix_userid=123" # 指定Cookie node app.js -p 9990 -d /tmp -c "cookie_value" # 完整参数组合 # 快捷启动脚本 npm run start:9990 # 在端口9990启动 npm run start:8080 # 在端口8080启动(监听所有接口) npm run start:custom # 自定义配置启动示例 npm run help # 显示帮助信息 # 组合使用(命令行参数优先级最高) node app.js -p 9990 -d /custom/path -c "your_cookie" # 或者设置环境变量后启动 export DOWNLOAD_DIR=/custom/downloads export ZLIB_COOKIE="prefers_color_scheme=light; remix_userkey=xxx; remix_userid=xxx" node app.js -p 8080 ``` 服务默认运行在 `http://localhost:8870` ## 📚 API 接口文档 ### 基础信息 - 基础URL: `http://localhost:8870/api/download` - 内容类型: `application/json` - 响应格式: JSON ### 接口列表 #### 1. 添加下载任务 ```http POST /api/download/add Content-Type: application/json { "url": "https://example.com/file.pdf", "customFileName": "我的文件.pdf" // 可选 } ``` **响应:** ```json { "success": true, "task": { "id": "task-uuid", "url": "https://example.com/file.pdf", "status": "pending", "addedAt": "2023-12-01T10:00:00.000Z" }, "message": "任务已添加到队列" } ``` #### 2. 查看队列状态 ```http GET /api/download/queue ``` **响应:** ```json { "success": true, "queue": { "stats": { "total": 5, "pending": 2, "downloading": 1, "completed": 2, "failed": 0 }, "processing": true, "currentTask": { "id": "current-task-id", "fileName": "downloading-file.pdf", "progress": 45.5 }, "tasks": [...] } } ``` #### 3. 查看任务状态 ```http GET /api/download/status/{taskId} ``` **响应:** ```json { "success": true, "task": { "id": "task-uuid", "url": "https://example.com/file.pdf", "status": "completed", "fileName": "file.pdf", "filePath": "/path/to/downloads/file.pdf", "fileSize": 1024000, "progress": 100, "addedAt": "2023-12-01T10:00:00.000Z", "completedAt": "2023-12-01T10:05:00.000Z" } } ``` #### 4. 删除任务 ```http DELETE /api/download/{taskId} ``` #### 5. 取消任务 ```http POST /api/download/{taskId}/cancel ``` #### 6. 重试失败任务 ```http POST /api/download/{taskId}/retry ``` #### 7. 获取下载历史 ```http GET /api/download/history?limit=50&status=completed ``` #### 8. 清理历史任务 ```http POST /api/download/cleanup Content-Type: application/json { "maxAge": 7 // 清理7天前的任务 } ``` #### 9. 服务统计信息 ```http GET /api/download/stats ``` #### 10. 健康检查 ```http GET /api/download/health GET /health ``` ## 🔧 配置选项 ### 环境变量 - `PORT`: 服务端口 (默认: 8870) - `HOST`: 服务主机 (默认: 127.0.0.1) - `NODE_ENV`: 环境模式 (development/production) - `DOWNLOAD_DIR`: 下载目录路径 (默认: ./storage/downloads) - `ZLIB_COOKIE`: Z-Library登录Cookie ### 任务配置 - 最大重试次数: 3次 - 下载超时: 60秒 - 队列检查间隔: 5秒 - 历史清理周期: 7天 ## 📁 项目结构 ``` download-service/ ├── app.js # 应用入口 ├── routes/ │ └── download.js # 下载路由 ├── services/ │ ├── downloadService.js # 下载服务 │ ├── queueManager.js # 队列管理 │ └── fileDownloader.js # 文件下载器 ├── models/ │ └── task.js # 任务模型 ├── middleware/ │ └── validation.js # 验证中间件 ├── utils/ │ └── logger.js # 日志工具 └── storage/ ├── downloads/ # 下载文件存储 ├── queue.json # 队列持久化 └── *.log # 日志文件 ``` ## 🛡️ 安全措施 - **限流控制**: 每IP每15分钟最多100次请求 - **参数验证**: 严格的输入参数验证 - **错误处理**: 完善的错误捕获和处理 - **安全头**: 使用Helmet.js添加安全响应头 - **CORS支持**: 跨域资源共享配置 ## 📝 使用示例 ### JavaScript/Node.js ```javascript const axios = require('axios'); // 添加下载任务 async function addDownload(url, fileName) { try { const response = await axios.post('http://localhost:3000/api/download/add', { url: url, customFileName: fileName }); console.log('任务已添加:', response.data.task.id); return response.data.task; } catch (error) { console.error('添加失败:', error.response?.data?.error); } } // 查看队列状态 async function checkQueue() { try { const response = await axios.get('http://localhost:3000/api/download/queue'); console.log('队列状态:', response.data.queue.stats); return response.data.queue; } catch (error) { console.error('查询失败:', error.message); } } // 使用示例 (async () => { // 添加下载任务 const task = await addDownload('https://example.com/file.pdf', '示例文件.pdf'); // 检查队列状态 const queue = await checkQueue(); // 等待任务完成 if (task) { const checkStatus = async () => { const response = await axios.get(`http://localhost:3000/api/download/status/${task.id}`); const status = response.data.task.status; if (status === 'completed') { console.log('下载完成:', response.data.task.filePath); } else if (status === 'failed') { console.log('下载失败:', response.data.task.error); } else { console.log(`下载中... ${response.data.task.progress}%`); setTimeout(checkStatus, 2000); // 2秒后再次检查 } }; setTimeout(checkStatus, 1000); } })(); ``` ### curl命令示例 ```bash # 添加下载任务 curl -X POST http://localhost:3000/api/download/add \ -H "Content-Type: application/json" \ -d '{"url":"https://example.com/file.pdf","customFileName":"我的文件.pdf"}' # 查看队列状态 curl http://localhost:3000/api/download/queue # 查看任务状态 curl http://localhost:3000/api/download/status/{task-id} # 健康检查 curl http://localhost:3000/health ``` ## 🔍 故障排除 ### 常见问题 1. **下载失败** - 检查URL是否有效 - 确认网络连接正常 - 查看错误日志获取详细信息 2. **队列不处理** - 检查服务是否正常运行 - 查看当前任务状态 - 重启服务恢复队列处理 3. **文件名乱码** - 使用customFileName参数指定文件名 - 确保文件名不包含特殊字符 ### 日志文件 - `storage/app.log`: 应用日志 - `storage/error.log`: 错误日志 - `storage/download.log`: 下载日志 - `storage/debug.log`: 调试日志(开发模式) ## 📄 许可证 ISC License ## 🤝 贡献 欢迎提交Issue和Pull Request! ## 📞 支持 如有问题,请通过以下方式联系: - 创建GitHub Issue - 邮箱: your-email@example.com