# 夸克网盘独立API接口文档

本文档说明两个新创建的独立PHP API接口的使用方法。

---

## API 1: Cookie验证与用户信息获取

**文件名：** `quark_api_verify.php`

### 功能描述
验证夸克网盘Cookie的有效性，并获取用户昵称和容量信息。

### 接口地址
```
POST /quark_api_verify.php
```

### 请求参数
```json
{
    "cookie": "夸克网盘Cookie字符串"
}
```

### 成功响应示例
```json
{
    "success": true,
    "message": "Cookie有效",
    "data": {
        "valid": true,
        "nickname": "张三",
        "used_size": 10737418240,
        "total_size": 107374182400,
        "used_size_formatted": "10.00 GB",
        "total_size_formatted": "100.00 GB",
        "free_size_formatted": "90.00 GB",
        "usage_percentage": 10.00
    }
}
```

### 失败响应示例
```json
{
    "success": false,
    "message": "Cookie已过期或无效",
    "data": {
        "valid": false
    }
}
```

### 响应字段说明
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 请求是否成功 |
| message | string | 响应消息 |
| data.valid | boolean | Cookie是否有效 |
| data.nickname | string | 用户昵称 |
| data.used_size | integer | 已使用容量(字节) |
| data.total_size | integer | 总容量(字节) |
| data.used_size_formatted | string | 已使用容量(格式化) |
| data.total_size_formatted | string | 总容量(格式化) |
| data.free_size_formatted | string | 剩余容量(格式化) |
| data.usage_percentage | float | 使用百分比 |

### 使用示例

#### curl 调用
```bash
curl -X POST http://localhost/quark_api_verify.php \
  -H "Content-Type: application/json" \
  -d '{
    "cookie": "your_cookie_here"
  }'
```

#### PHP 调用
```php
<?php
$url = 'http://localhost/quark_api_verify.php';
$data = [
    'cookie' => 'your_cookie_here'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
if ($result['success']) {
    echo "用户: " . $result['data']['nickname'] . "\n";
    echo "使用率: " . $result['data']['usage_percentage'] . "%\n";
} else {
    echo "错误: " . $result['message'] . "\n";
}
?>
```

#### JavaScript 调用
```javascript
fetch('http://localhost/quark_api_verify.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        cookie: 'your_cookie_here'
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('用户:', data.data.nickname);
        console.log('使用率:', data.data.usage_percentage + '%');
    } else {
        console.error('错误:', data.message);
    }
});
```

#### Python 调用
```python
import requests
import json

url = 'http://localhost/quark_api_verify.php'
data = {
    'cookie': 'your_cookie_here'
}

response = requests.post(url, json=data)
result = response.json()

if result['success']:
    print(f"用户: {result['data']['nickname']}")
    print(f"使用率: {result['data']['usage_percentage']}%")
else:
    print(f"错误: {result['message']}")
```

---

## API 2: 获取根目录文件列表

**文件名：** `quark_api_files.php`

### 功能描述
验证Cookie有效性，并获取指定目录（默认根目录）下的所有文件和文件夹列表。

### 接口地址
```
POST /quark_api_files.php
```

### 请求参数
```json
{
    "cookie": "夸克网盘Cookie字符串",
    "parent_fid": "0"  // 可选，父目录ID，默认为"0"（根目录）
}
```

### 成功响应示例
```json
{
    "success": true,
    "message": "获取成功",
    "data": {
        "valid": true,
        "parent_fid": "0",
        "total_count": 15,
        "file_count": 10,
        "folder_count": 5,
        "items": [
            {
                "fid": "1234567890",
                "name": "我的文档",
                "is_dir": true,
                "type": "folder",
                "size": 0,
                "size_formatted": "0 B",
                "updated_at": 1698765432,
                "updated_at_formatted": "2024-10-31 12:30:32"
            },
            {
                "fid": "9876543210",
                "name": "视频.mp4",
                "is_dir": false,
                "type": "file",
                "size": 104857600,
                "size_formatted": "100.00 MB",
                "updated_at": 1698765400,
                "updated_at_formatted": "2024-10-31 12:30:00"
            }
        ]
    }
}
```

### 失败响应示例
```json
{
    "success": false,
    "message": "Cookie无效：Cookie已过期或无效",
    "data": {
        "valid": false
    }
}
```

### 响应字段说明
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 请求是否成功 |
| message | string | 响应消息 |
| data.valid | boolean | Cookie是否有效 |
| data.parent_fid | string | 当前目录ID |
| data.total_count | integer | 文件+文件夹总数 |
| data.file_count | integer | 文件数量 |
| data.folder_count | integer | 文件夹数量 |
| data.items | array | 文件/文件夹列表 |
| data.items[].fid | string | 文件/文件夹唯一ID |
| data.items[].name | string | 文件/文件夹名称 |
| data.items[].is_dir | boolean | 是否为文件夹 |
| data.items[].type | string | 类型："folder" 或 "file" |
| data.items[].size | integer | 文件大小(字节)，文件夹为0 |
| data.items[].size_formatted | string | 格式化的文件大小 |
| data.items[].updated_at | integer | 更新时间戳 |
| data.items[].updated_at_formatted | string | 格式化的更新时间 |

### 使用示例

#### curl 调用（获取根目录）
```bash
curl -X POST http://localhost/quark_api_files.php \
  -H "Content-Type: application/json" \
  -d '{
    "cookie": "your_cookie_here"
  }'
```

#### curl 调用（获取指定目录）
```bash
curl -X POST http://localhost/quark_api_files.php \
  -H "Content-Type: application/json" \
  -d '{
    "cookie": "your_cookie_here",
    "parent_fid": "1234567890"
  }'
```

#### PHP 调用
```php
<?php
$url = 'http://localhost/quark_api_files.php';
$data = [
    'cookie' => 'your_cookie_here',
    'parent_fid' => '0'  // 可选
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
if ($result['success']) {
    echo "总数: " . $result['data']['total_count'] . "\n";
    echo "文件夹: " . $result['data']['folder_count'] . "\n";
    echo "文件: " . $result['data']['file_count'] . "\n\n";
    
    foreach ($result['data']['items'] as $item) {
        $icon = $item['is_dir'] ? '📁' : '📄';
        echo "{$icon} {$item['name']} (ID: {$item['fid']})\n";
    }
} else {
    echo "错误: " . $result['message'] . "\n";
}
?>
```

#### JavaScript 调用
```javascript
fetch('http://localhost/quark_api_files.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        cookie: 'your_cookie_here',
        parent_fid: '0'  // 可选
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log(`总数: ${data.data.total_count}`);
        console.log(`文件夹: ${data.data.folder_count}`);
        console.log(`文件: ${data.data.file_count}`);
        
        data.data.items.forEach(item => {
            const icon = item.is_dir ? '📁' : '📄';
            console.log(`${icon} ${item.name} (ID: ${item.fid})`);
        });
    } else {
        console.error('错误:', data.message);
    }
});
```

#### Python 调用
```python
import requests
import json

url = 'http://localhost/quark_api_files.php'
data = {
    'cookie': 'your_cookie_here',
    'parent_fid': '0'  # 可选
}

response = requests.post(url, json=data)
result = response.json()

if result['success']:
    print(f"总数: {result['data']['total_count']}")
    print(f"文件夹: {result['data']['folder_count']}")
    print(f"文件: {result['data']['file_count']}\n")
    
    for item in result['data']['items']:
        icon = '📁' if item['is_dir'] else '📄'
        print(f"{icon} {item['name']} (ID: {item['fid']})")
else:
    print(f"错误: {result['message']}")
```

---

## 部署说明

### 方式一：使用Apache/Nginx
将两个PHP文件放置在Web服务器的文档根目录下即可访问。

### 方式二：使用PHP内置服务器（开发测试用）
```bash
# 在项目目录下运行
php -S localhost:8000

# 然后可以通过以下地址访问
# http://localhost:8000/quark_api_verify.php
# http://localhost:8000/quark_api_files.php
```

---

## 错误码说明

| HTTP状态码 | 说明 |
|-----------|------|
| 200 | 请求成功 |
| 400 | 请求参数错误（Cookie为空、JSON格式错误等） |
| 401 | Cookie无效或已过期 |
| 405 | 请求方法错误（仅支持POST） |
| 500 | 服务器内部错误 |

---

## 注意事项

1. **Cookie安全**：Cookie包含敏感信息，请勿在不安全的环境中传输
2. **HTTPS推荐**：生产环境建议使用HTTPS协议
3. **跨域支持**：API已启用CORS，支持跨域调用
4. **并发限制**：建议控制API调用频率，避免被夸克限制
5. **日志记录**：两个API都会记录详细日志到PHP错误日志中

---

## 常见问题

### Q1: Cookie从哪里获取？
A: 使用浏览器登录夸克网盘后，在开发者工具中的Network标签页查看请求头中的Cookie值。

### Q2: Cookie多久过期？
A: 夸克网盘Cookie的有效期由夸克服务器决定，通常为一段时间后自动失效。

### Q3: 如何获取子目录的文件列表？
A: 先调用文件列表API获取根目录，找到文件夹的fid，然后将该fid作为parent_fid参数再次调用。

### Q4: 为什么返回的items中文件夹在前面？
A: API设计上将文件夹排在前面，文件排在后面，方便用户浏览。

---

## 版本信息

- **版本**: 1.0.0
- **创建日期**: 2024-10-26
- **作者**: AI Assistant
- **依赖**: PHP 7.0+, cURL扩展

---

## 更新日志

### v1.0.0 (2024-10-26)
- ✨ 初始版本发布
- ✨ 支持Cookie验证和用户信息获取
- ✨ 支持文件列表获取
- ✨ 完整的错误处理和日志记录
