# AI 有声书 - 部署文档

## 目录

- [环境准备](#环境准备)
- [本地开发](#本地开发)
- [生产环境部署](#生产环境部署)
- [Docker 部署](#docker 部署)
- [常见问题](#常见问题)

---

## 环境准备

### 系统要求

- **操作系统**: Linux (推荐 Ubuntu 20.04+) / macOS / Windows
- **Node.js**: >= 18.x
- **MongoDB**: >= 6.0
- **FFmpeg**: 最新版本（用于音频处理）
- **Redis**: >= 6.0 (可选，用于缓存)

### 依赖安装

#### 1. 安装 Node.js

```bash
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# macOS
brew install node@18

# Windows
# 下载安装包：https://nodejs.org/
```

#### 2. 安装 MongoDB

```bash
# Ubuntu/Debian
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod

# macOS
brew tap mongodb/brew
brew install mongodb-community@6.0
brew services start mongodb-community@6.0

# Windows
# 下载安装包：https://www.mongodb.com/try/download/community
```

#### 3. 安装 FFmpeg

```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y ffmpeg

# macOS
brew install ffmpeg

# Windows
# 下载安装包：https://ffmpeg.org/download.html
# 添加到系统 PATH
```

#### 4. 安装 Redis (可选)

```bash
# Ubuntu/Debian
sudo apt-get install -y redis-server
sudo systemctl start redis
sudo systemctl enable redis

# macOS
brew install redis
brew services start redis

# Windows
# 使用 WSL 或下载 Windows 版本
```

---

## 本地开发

### 1. 克隆项目

```bash
git clone <repository-url>
cd audio_codebuddy
```

### 2. 安装后端依赖

```bash
cd server
npm install
```

### 3. 配置环境变量

```bash
# 复制环境配置模板
cp .env.example .env

# 编辑 .env 文件，配置必要参数
vi .env
```

**.env 配置说明**:

```bash
# 服务配置
PORT=3000
NODE_ENV=development

# MongoDB
MONGODB_URI=mongodb://localhost:27017/audio-book

# JWT
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRES_IN=7d

# 阿里云 TTS
ALIYUN_ACCESS_KEY=your-access-key
ALIYUN_ACCESS_SECRET=your-access-secret
ALIYUN_APP_KEY=your-app-key

# AI 服务（可选，用于智能摘要）
AI_API_KEY=your-ai-api-key
AI_API_ENDPOINT=https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

# 应用 URL
APP_URL=http://localhost:3000
```

### 4. 启动后端服务

```bash
# 开发模式（支持热重载）
npm run dev

# 生产模式
npm run build
npm start
```

### 5. 安装前端依赖

```bash
cd ../client
npm install
```

### 6. 启动前端开发服务器

```bash
# H5 开发
npm run dev:h5

# 微信小程序开发
npm run dev:mp-weixin
```

访问 `http://localhost:8080` 查看应用

---

## 生产环境部署

### 方案一：传统部署

#### 1. 服务器准备

- 阿里云 ECS / 腾讯云 CVM / 华为云 ECS
- 推荐配置：2 核 4G 以上
- 系统：Ubuntu 20.04 LTS

#### 2. 安装依赖

```bash
# 更新系统
sudo apt-get update
sudo apt-get upgrade -y

# 安装 Node.js、MongoDB、FFmpeg、Redis
# 参考"环境准备"章节
```

#### 3. 部署代码

```bash
# 克隆或上传代码
git clone <repository-url> /var/www/audio-book
cd /var/www/audio-book/server

# 安装依赖
npm install
npm run build

# 配置环境变量
cp .env.example .env
vi .env  # 修改为生产环境配置
```

#### 4. 使用 PM2 管理进程

```bash
# 全局安装 PM2
npm install -g pm2

# 创建 PM2 配置文件
cat > ecosystem.config.js << EOF
module.exports = {
  apps: [{
    name: 'audio-book-server',
    script: './dist/app.js',
    instances: 2,
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }]
};
EOF

# 启动服务
pm2 start ecosystem.config.js

# 设置开机自启
pm2 startup
pm2 save
```

#### 5. 配置 Nginx

```bash
# 安装 Nginx
sudo apt-get install -y nginx

# 创建站点配置
sudo vi /etc/nginx/sites-available/audio-book
```

**Nginx 配置示例**:

```nginx
server {
    listen 80;
    server_name your-domain.com;

    # 前端静态文件
    location / {
        root /var/www/audio-book/client/dist;
        try_files $uri $uri/ /index.html;
    }

    # 后端 API 代理
    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 音频文件
    location /uploads {
        alias /var/www/audio-book/server/uploads;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
```

```bash
# 启用站点
sudo ln -s /etc/nginx/sites-available/audio-book /etc/nginx/sites-enabled/

# 测试配置
sudo nginx -t

# 重启 Nginx
sudo systemctl restart nginx
```

#### 6. 配置 SSL 证书（推荐）

```bash
# 使用 Let's Encrypt 免费证书
sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
```

---

### 方案二：使用 Docker

#### 1. 安装 Docker

```bash
# Ubuntu/Debian
curl -fsSL https://get.docker.com | sh
sudo systemctl enable docker
sudo systemctl start docker

# 安装 Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
```

#### 2. 创建 Docker Compose 配置

```yaml
# docker-compose.yml
version: '3.8'

services:
  mongodb:
    image: mongo:6.0
    container_name: audio-mongodb
    restart: always
    volumes:
      - mongodb_data:/data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: your-password
    ports:
      - "27017:27017"

  redis:
    image: redis:7-alpine
    container_name: audio-redis
    restart: always
    volumes:
      - redis_data:/data
    ports:
      - "6379:6379"

  backend:
    build:
      context: ./server
      dockerfile: Dockerfile
    container_name: audio-backend
    restart: always
    depends_on:
      - mongodb
      - redis
    environment:
      NODE_ENV: production
      MONGODB_URI: mongodb://admin:your-password@mongodb:27017/audio-book
      REDIS_URL: redis://redis:6379
    volumes:
      - ./server/uploads:/app/uploads
    ports:
      - "3000:3000"

  frontend:
    build:
      context: ./client
      dockerfile: Dockerfile
    container_name: audio-frontend
    restart: always
    depends_on:
      - backend
    ports:
      - "80:80"

volumes:
  mongodb_data:
  redis_data:
```

#### 3. 创建 Dockerfile

**server/Dockerfile**:

```dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3000

CMD ["node", "dist/app.js"]
```

**client/Dockerfile**:

```dockerfile
FROM node:18-alpine as builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build:h5

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
```

#### 4. 启动服务

```bash
docker-compose up -d

# 查看日志
docker-compose logs -f

# 停止服务
docker-compose down

# 重启服务
docker-compose restart
```

---

## 常见问题

### 1. MongoDB 连接失败

**错误**: `MongoServerError: Authentication failed`

**解决**:
```bash
# 检查 MongoDB 是否运行
sudo systemctl status mongod

# 查看 MongoDB 日志
sudo tail -f /var/log/mongodb/mongod.log

# 重置密码
mongo
use admin
db.createUser({
  user: "admin",
  pwd: "new-password",
  roles: ["root"]
})
```

### 2. FFmpeg 找不到

**错误**: `Command failed: ffmpeg`

**解决**:
```bash
# 检查 FFmpeg 是否安装
which ffmpeg

# 重新安装
sudo apt-get install -y ffmpeg
```

### 3. 端口被占用

**错误**: `Error: listen EADDRINUSE: address already in use :::3000`

**解决**:
```bash
# 查找占用端口的进程
lsof -i :3000

# 杀死进程
kill -9 <PID>

# 或修改端口
vi .env
PORT=3001
```

### 4. 跨域问题

**解决**:
```javascript
// server/src/app.ts
app.use(cors({
  origin: 'https://your-domain.com', // 改为实际域名
  credentials: true,
}));
```

### 5. 文件上传大小限制

**解决**:
```javascript
// server/src/app.ts
app.use(bodyParser({
  formLimit: '10mb',
  jsonLimit: '10mb',
}));
```

### 6. 性能优化

**添加 Redis 缓存**:
```bash
# 安装 Redis
sudo apt-get install -y redis-server

# 配置服务端使用 Redis
vi .env
REDIS_URL=redis://localhost:6379
```

### 7. 日志管理

```bash
# 查看 PM2 日志
pm2 logs audio-book-server

# 清空日志
pm2 flush

# 查看系统日志
sudo journalctl -u nginx
sudo journalctl -u mongod
```

### 8. 备份数据

```bash
# MongoDB 备份
mongodump --out /backup/mongodb

# MongoDB 恢复
mongorestore /backup/mongodb

# 音频文件备份
tar -czf uploads-backup.tar.gz server/uploads
```

---

## 监控和维护

### 1. 系统监控

```bash
# 安装监控工具
sudo npm install -g pm2

# 查看应用状态
pm2 status

# 查看资源使用
pm2 monit
```

### 2. 数据库监控

```bash
# MongoDB 状态
mongostat

# MongoDB 慢查询
mongo
db.setProfilingLevel(2)
```

### 3. 日志轮转

```javascript
// ecosystem.config.js
{
  apps: [{
    name: 'audio-book-server',
    script: './dist/app.js',
    max_memory_restart: '500M',
    log_date_format: 'YYYY-MM-DD HH:mm:ss',
    error_file: './logs/error.log',
    out_file: './logs/out.log',
  }]
}
```

---

## 技术支持

如有问题，请联系：
- Email: support@example.com
- GitHub Issues: https://github.com/your-repo/issues
