# MyCloudVault Mobile API Reference

Complete API documentation for Android and iOS developers building MyCloudVault mobile clients.

## Base URL

```
http://your-server-address:port/api
```

Replace `your-server-address` and `port` with your MyCloudVault server details.

## Authentication

All API requests (except health check) require authentication using an API key obtained during device pairing.

### Headers

```
X-Device-ID: your-device-id
X-API-Key: your-api-key
Content-Type: application/json
```

## Error Responses

All endpoints return consistent error responses:

```json
{
  "success": false,
  "error": "Error message describing what went wrong"
}
```

Common HTTP status codes:
- `200` - Success
- `201` - Created
- `400` - Bad Request (validation error)
- `401` - Unauthorized (missing or invalid API key)
- `404` - Not Found
- `500` - Internal Server Error

---

## Endpoints

### Health Check

**GET** `/health`

Check if the server is running.

**Authentication:** None required

**Response:**
```json
{
  "success": true,
  "message": "MyCloudVault API is running",
  "timestamp": "2025-12-12T22:30:00.000Z"
}
```

---

## Device Management

### Pair Device

**POST** `/devices/pair`

Initiate device pairing and receive an API key.

**Authentication:** None required (initial pairing)

**Request Body:**
```json
{
  "deviceId": "android-abc123",
  "deviceName": "Samsung Galaxy S23",
  "deviceModel": "SM-S911B",
  "osVersion": "14",
  "pairingCode": "123456"
}
```

**Response:**
```json
{
  "success": true,
  "device": {
    "id": 1,
    "deviceId": "android-abc123",
    "deviceName": "Samsung Galaxy S23",
    "deviceModel": "SM-S911B",
    "osVersion": "14",
    "status": "active",
    "lastSeen": "2025-12-12T22:30:00.000Z"
  },
  "apiKey": "cvault_abc123def456..."
}
```

**Important:** Store the `apiKey` securely. It's required for all subsequent API calls.

### Get Device Info

**GET** `/devices/:deviceId`

**Authentication:** Required

**Response:**
```json
{
  "success": true,
  "device": {
    "id": 1,
    "deviceId": "android-abc123",
    "deviceName": "Samsung Galaxy S23",
    "deviceModel": "SM-S911B",
    "osVersion": "14",
    "status": "active",
    "lastSeen": "2025-12-12T22:30:00.000Z"
  }
}
```

### Update Device

**PUT** `/devices/:deviceId`

**Authentication:** Required

**Request Body:**
```json
{
  "deviceName": "My Phone",
  "deviceModel": "SM-S911B",
  "osVersion": "14"
}
```

**Response:**
```json
{
  "success": true,
  "device": { /* updated device object */ }
}
```

### Delete Device

**DELETE** `/devices/:deviceId`

**Authentication:** Required

**Response:**
```json
{
  "success": true,
  "message": "Device deleted successfully"
}
```

---

## Backup Operations

### Start Backup

**POST** `/backup/start`

Initiate a new backup session.

**Authentication:** Required

**Request Body:**
```json
{
  "deviceId": "android-abc123",
  "backupType": "full",
  "totalSize": 1048576000,
  "fileCount": 150,
  "metadata": {
    "appVersion": "1.0.0",
    "osVersion": "14",
    "backupCategories": ["photos", "videos", "documents"]
  }
}
```

**Response:**
```json
{
  "success": true,
  "backup": {
    "id": 1,
    "backupId": "backup-xyz789",
    "deviceId": "android-abc123",
    "backupType": "full",
    "status": "in_progress",
    "totalSize": 1048576000,
    "uploadedSize": 0,
    "fileCount": 150,
    "startedAt": "2025-12-12T22:30:00.000Z"
  }
}
```

### Upload Backup (Chunked)

**POST** `/backup/upload-chunk`

Upload backup data in chunks (recommended for large files).

**Authentication:** Required

**Content-Type:** `multipart/form-data`

**Form Data:**
- `deviceId` (string): Device identifier
- `backupId` (string): Backup session ID from `/backup/start`
- `chunkIndex` (number): Current chunk index (0-based)
- `totalChunks` (number): Total number of chunks
- `chunk` (file): Binary chunk data

**Response:**
```json
{
  "success": true,
  "chunkIndex": 0,
  "uploadedSize": 5242880,
  "progress": 5.0
}
```

### Upload Encrypted Backup

**POST** `/backup/upload-encrypted`

Upload encrypted backup with metadata.

**Authentication:** Required

**Content-Type:** `multipart/form-data`

**Form Data:**
- `deviceId` (string)
- `backupId` (string)
- `encryptedData` (file): Encrypted backup file
- `encryptionMetadata` (JSON string):
  ```json
  {
    "algorithm": "aes-256-gcm",
    "iv": "base64-encoded-iv",
    "authTag": "base64-encoded-auth-tag",
    "salt": "base64-encoded-salt"
  }
  ```

**Response:**
```json
{
  "success": true,
  "backup": {
    "backupId": "backup-xyz789",
    "status": "completed",
    "encryptionEnabled": true,
    "size": 1048576000
  }
}
```

### Verify Backup

**POST** `/backup/verify`

Verify backup integrity using checksums.

**Authentication:** Required

**Request Body:**
```json
{
  "deviceId": "android-abc123",
  "backupId": "backup-xyz789"
}
```

**Response:**
```json
{
  "success": true,
  "verification": {
    "backupId": "backup-xyz789",
    "isValid": true,
    "sha256Match": true,
    "crc32Match": true,
    "verifiedAt": "2025-12-12T22:35:00.000Z"
  }
}
```

### List Backups

**GET** `/backup/list?deviceId=android-abc123&limit=20&offset=0`

**Authentication:** Required

**Query Parameters:**
- `deviceId` (required): Device identifier
- `limit` (optional): Number of results (default: 50)
- `offset` (optional): Pagination offset (default: 0)
- `status` (optional): Filter by status (in_progress, completed, failed)

**Response:**
```json
{
  "success": true,
  "backups": [
    {
      "id": 1,
      "backupId": "backup-xyz789",
      "deviceId": "android-abc123",
      "backupType": "full",
      "status": "completed",
      "size": 1048576000,
      "fileCount": 150,
      "encryptionEnabled": true,
      "verificationStatus": "verified",
      "startedAt": "2025-12-12T22:30:00.000Z",
      "completedAt": "2025-12-12T22:35:00.000Z"
    }
  ],
  "total": 1,
  "limit": 20,
  "offset": 0
}
```

### Download Backup

**GET** `/backup/download/:backupId?deviceId=android-abc123`

**Authentication:** Required

**Response:** Binary file stream (encrypted backup data)

**Headers:**
- `Content-Type`: `application/octet-stream`
- `Content-Disposition`: `attachment; filename="backup-xyz789.enc"`
- `Content-Length`: File size in bytes

### Download Decrypted Backup

**GET** `/backup/download-decrypted/:backupId?deviceId=android-abc123`

**Authentication:** Required

**Response:** Binary file stream (decrypted backup data)

**Note:** Only works if backup was encrypted server-side. For client-side encryption, use `/backup/download` and decrypt locally.

### Delete Backup

**DELETE** `/backup/delete/:backupId?deviceId=android-abc123`

**Authentication:** Required

**Response:**
```json
{
  "success": true,
  "message": "Backup deleted successfully"
}
```

### Get Backup Progress

**GET** `/backup/progress/:backupId?deviceId=android-abc123`

**Authentication:** Required

**Response:**
```json
{
  "success": true,
  "progress": {
    "backupId": "backup-xyz789",
    "status": "in_progress",
    "uploadedSize": 524288000,
    "totalSize": 1048576000,
    "percentage": 50.0,
    "uploadedFiles": 75,
    "totalFiles": 150
  }
}
```

---

## Encryption

### Generate Encryption Key

**POST** `/encryption/generate-key`

Generate a secure encryption key for client-side encryption.

**Authentication:** Required

**Request Body:**
```json
{
  "deviceId": "android-abc123",
  "passphrase": "user-provided-passphrase"
}
```

**Response:**
```json
{
  "success": true,
  "key": "base64-encoded-encryption-key",
  "salt": "base64-encoded-salt",
  "algorithm": "aes-256-gcm"
}
```

**Important:** Store the encryption key securely. The server does not store it.

---

## Communication

### Send Message

**POST** `/communication/send`

Send a message between device and server.

**Authentication:** Required

**Request Body:**
```json
{
  "fromType": "device",
  "fromId": "android-abc123",
  "toType": "server",
  "toId": "server-main",
  "messageType": "status_update",
  "subject": "Backup Progress",
  "body": "Backup 50% complete",
  "metadata": {
    "backupId": "backup-xyz789",
    "progress": 50
  }
}
```

**Response:**
```json
{
  "success": true,
  "message": {
    "id": 1,
    "messageId": "msg-abc123",
    "status": "sent",
    "createdAt": "2025-12-12T22:30:00.000Z"
  }
}
```

### Get Messages

**GET** `/communication/messages?deviceId=android-abc123&limit=50`

**Authentication:** Required

**Query Parameters:**
- `deviceId` (optional): Filter by device
- `messageType` (optional): Filter by type
- `limit` (optional): Number of results (default: 50)

**Response:**
```json
{
  "success": true,
  "messages": [
    {
      "id": 1,
      "messageId": "msg-abc123",
      "fromType": "server",
      "toType": "device",
      "messageType": "command",
      "subject": "Start Backup",
      "body": "Please start backup now",
      "status": "delivered",
      "createdAt": "2025-12-12T22:30:00.000Z"
    }
  ]
}
```

### Send Command

**POST** `/communication/command`

Send a command from server to device.

**Authentication:** Required

**Request Body:**
```json
{
  "deviceId": "android-abc123",
  "command": "start_backup",
  "parameters": {
    "backupType": "incremental",
    "categories": ["photos", "videos"]
  }
}
```

**Response:**
```json
{
  "success": true,
  "command": {
    "commandId": "cmd-xyz789",
    "status": "pending",
    "createdAt": "2025-12-12T22:30:00.000Z"
  }
}
```

---

## Rate Limits

To prevent abuse, the API implements rate limiting:

- **Device Pairing:** 5 attempts per hour per IP
- **Backup Operations:** 100 requests per hour per device
- **File Uploads:** No limit (but consider bandwidth)
- **General API:** 1000 requests per hour per device

Rate limit headers:
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1702425600
```

---

## Best Practices

### Security

1. **Always use HTTPS** in production
2. **Store API keys securely** using Android Keystore or iOS Keychain
3. **Encrypt backups client-side** before uploading
4. **Verify checksums** after upload and before restore
5. **Use certificate pinning** to prevent MITM attacks

### Performance

1. **Use chunked uploads** for files larger than 10MB
2. **Implement retry logic** with exponential backoff
3. **Compress data** before encryption to reduce size
4. **Use background tasks** for long-running operations
5. **Cache device info** to reduce API calls

### Error Handling

1. **Check HTTP status codes** before parsing response
2. **Handle network errors** gracefully
3. **Implement offline queue** for failed operations
4. **Show user-friendly error messages**
5. **Log errors** for debugging

---

## Testing

Use these curl commands to test the API:

### Health Check
```bash
curl http://localhost:8080/api/health
```

### Pair Device
```bash
curl -X POST http://localhost:8080/api/devices/pair \
  -H "Content-Type: application/json" \
  -d '{
    "deviceId": "test-device-001",
    "deviceName": "Test Phone",
    "deviceModel": "Test Model",
    "osVersion": "14",
    "pairingCode": "123456"
  }'
```

### Start Backup
```bash
curl -X POST http://localhost:8080/api/backup/start \
  -H "Content-Type: application/json" \
  -H "X-Device-ID: test-device-001" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "deviceId": "test-device-001",
    "backupType": "full",
    "totalSize": 1048576,
    "fileCount": 10
  }'
```

### List Backups
```bash
curl http://localhost:8080/api/backup/list?deviceId=test-device-001 \
  -H "X-Device-ID: test-device-001" \
  -H "X-API-Key: your-api-key"
```
