# MyCloudVault Communication API

## Overview

The Communication API enables real-time messaging between Android devices, PC/cloud servers, and the MyCloudVault dashboard. It supports status updates, remote commands, notifications, and data transfer.

---

## Architecture

### Communication Flow

```
┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│   Android   │◄────►│  Dashboard  │◄────►│   Server    │
│   Device    │      │   (Web UI)  │      │  (PC/Cloud) │
└─────────────┘      └─────────────┘      └─────────────┘
       │                    │                    │
       └────────────────────┴────────────────────┘
                    REST API + Polling
```

### Message Types

- **status**: Device/server status updates
- **command**: Remote control commands
- **notification**: Push notifications
- **data**: Backup data transfer

---

## API Endpoints

### Base URL
```
https://vm6tgfyizy.preview.c24.airoapp.ai
```

---

## 1. Send Message

**Endpoint:** `POST /api/communication/send`

**Purpose:** Send a message from any entity to another.

**Request Body:**
```json
{
  "fromType": "device",
  "fromId": "android-123",
  "toType": "server",
  "toId": "home-pc-001",
  "messageType": "status",
  "subject": "Backup Progress",
  "body": "Backup 50% complete",
  "metadata": {
    "progress": 50,
    "filesProcessed": 1250
  }
}
```

**Response:**
```json
{
  "success": true,
  "message": {
    "id": 1,
    "messageId": "a1b2c3d4e5f6...",
    "fromType": "device",
    "fromId": "android-123",
    "toType": "server",
    "toId": "home-pc-001",
    "messageType": "status",
    "subject": "Backup Progress",
    "body": "Backup 50% complete",
    "metadata": "{\"progress\":50,\"filesProcessed\":1250}",
    "status": "sent",
    "createdAt": "2025-12-12T21:00:00.000Z"
  }
}
```

**Valid Types:**
- `fromType` / `toType`: "device", "server", "dashboard"
- `messageType`: "status", "command", "notification", "data"

---

## 2. Send Notification

**Endpoint:** `POST /api/communication/notify`

**Purpose:** Send a notification from server to device(s).

**Request Body:**
```json
{
  "serverId": "home-pc-001",
  "deviceId": "android-123",
  "notificationType": "backup_complete",
  "title": "Backup Complete",
  "message": "Your backup has finished successfully",
  "data": {
    "backupId": "backup-456",
    "size": "12.4 GB"
  }
}
```

**Response:**
```json
{
  "success": true,
  "notification": {
    "id": 2,
    "messageId": "b2c3d4e5f6g7...",
    "fromType": "server",
    "fromId": "home-pc-001",
    "toType": "device",
    "toId": "android-123",
    "messageType": "notification",
    "subject": "Backup Complete",
    "body": "Your backup has finished successfully",
    "status": "sent",
    "createdAt": "2025-12-12T21:05:00.000Z"
  }
}
```

**Note:** Omit `deviceId` to broadcast to all devices.

---

## 3. Get Messages

**Endpoint:** `GET /api/communication/messages`

**Purpose:** Fetch communication messages with filtering.

**Query Parameters:**
- `deviceId` (optional): Filter by device ID
- `serverId` (optional): Filter by server ID
- `messageType` (optional): Filter by message type
- `limit` (optional): Number of messages (default: 50, max: 200)
- `offset` (optional): Pagination offset (default: 0)

**Example Request:**
```
GET /api/communication/messages?deviceId=android-123&limit=10
```

**Response:**
```json
{
  "success": true,
  "messages": [
    {
      "id": 1,
      "messageId": "a1b2c3d4e5f6...",
      "fromType": "device",
      "fromId": "android-123",
      "toType": "server",
      "toId": "home-pc-001",
      "messageType": "status",
      "subject": "Backup Progress",
      "body": "Backup 50% complete",
      "status": "sent",
      "createdAt": "2025-12-12T21:00:00.000Z"
    }
  ],
  "total": 1,
  "limit": 10,
  "offset": 0
}
```

---

## 4. Send Remote Command

**Endpoint:** `POST /api/communication/command`

**Purpose:** Send a remote command to a device.

**Request Body:**
```json
{
  "deviceId": "android-123",
  "commandType": "backup_now",
  "parameters": {
    "backupType": "full",
    "priority": "high"
  }
}
```

**Response:**
```json
{
  "success": true,
  "command": {
    "id": 1,
    "commandId": "c3d4e5f6g7h8...",
    "deviceId": "android-123",
    "commandType": "backup_now",
    "parameters": "{\"backupType\":\"full\",\"priority\":\"high\"}",
    "status": "pending",
    "sentAt": "2025-12-12T21:10:00.000Z"
  }
}
```

**Valid Command Types:**
- `backup_now`: Start backup immediately
- `pause`: Pause ongoing backup
- `resume`: Resume paused backup
- `cancel`: Cancel backup
- `settings_update`: Update device settings

---

## 5. Get Pending Commands

**Endpoint:** `GET /api/communication/commands/:deviceId`

**Purpose:** Fetch pending commands for a device (for polling).

**Example Request:**
```
GET /api/communication/commands/android-123
```

**Response:**
```json
{
  "success": true,
  "commands": [
    {
      "id": 1,
      "commandId": "c3d4e5f6g7h8...",
      "deviceId": "android-123",
      "commandType": "backup_now",
      "parameters": "{\"backupType\":\"full\"}",
      "status": "pending",
      "sentAt": "2025-12-12T21:10:00.000Z"
    }
  ]
}
```

**Polling Recommendation:** Check every 10-30 seconds.

---

## Implementation Examples

### Android Device (Kotlin)

```kotlin
import okhttp3.*
import org.json.JSONObject

class CommunicationClient(private val deviceId: String) {
    private val client = OkHttpClient()
    private val baseUrl = "https://vm6tgfyizy.preview.c24.airoapp.ai"

    // Send status update
    fun sendStatus(message: String, metadata: Map<String, Any>) {
        val json = JSONObject().apply {
            put("fromType", "device")
            put("fromId", deviceId)
            put("toType", "dashboard")
            put("messageType", "status")
            put("subject", "Status Update")
            put("body", message)
            put("metadata", JSONObject(metadata))
        }

        val request = Request.Builder()
            .url("$baseUrl/api/communication/send")
            .post(RequestBody.create(
                MediaType.parse("application/json"),
                json.toString()
            ))
            .build()

        client.newCall(request).execute()
    }

    // Poll for commands
    fun checkCommands(): List<Command> {
        val request = Request.Builder()
            .url("$baseUrl/api/communication/commands/$deviceId")
            .get()
            .build()

        val response = client.newCall(request).execute()
        val json = JSONObject(response.body()?.string())
        
        // Parse and return commands
        return parseCommands(json.getJSONArray("commands"))
    }
}

// Start polling service
class CommandPollingService : Service() {
    private val handler = Handler()
    private val pollInterval = 10000L // 10 seconds

    private val pollRunnable = object : Runnable {
        override fun run() {
            val commands = communicationClient.checkCommands()
            commands.forEach { executeCommand(it) }
            handler.postDelayed(this, pollInterval)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        handler.post(pollRunnable)
        return START_STICKY
    }
}
```

### Server (Node.js)

```javascript
const axios = require('axios');

const CLOUDVAULT_API = 'https://vm6tgfyizy.preview.c24.airoapp.ai';
const SERVER_ID = 'home-pc-001';

// Send notification to device
async function notifyDevice(deviceId, title, message, data = {}) {
  try {
    const response = await axios.post(`${CLOUDVAULT_API}/api/communication/notify`, {
      serverId: SERVER_ID,
      deviceId,
      notificationType: 'backup_complete',
      title,
      message,
      data
    });
    
    console.log('Notification sent:', response.data);
  } catch (error) {
    console.error('Failed to send notification:', error.message);
  }
}

// Send status update
async function sendStatus(message, metadata = {}) {
  try {
    await axios.post(`${CLOUDVAULT_API}/api/communication/send`, {
      fromType: 'server',
      fromId: SERVER_ID,
      toType: 'dashboard',
      messageType: 'status',
      subject: 'Server Status',
      body: message,
      metadata
    });
  } catch (error) {
    console.error('Failed to send status:', error.message);
  }
}

// Example: Notify device when backup completes
backupStream.on('complete', async (backupId, size) => {
  await notifyDevice('android-123', 'Backup Complete', 
    'Your backup has finished successfully', 
    { backupId, size }
  );
});
```

### Dashboard (React)

```typescript
import { useState, useEffect } from 'react';

function CommunicationPanel() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    fetchMessages();
    const interval = setInterval(fetchMessages, 10000);
    return () => clearInterval(interval);
  }, []);

  const fetchMessages = async () => {
    const response = await fetch('/api/communication/messages?limit=20');
    const result = await response.json();
    if (result.success) {
      setMessages(result.messages);
    }
  };

  const sendCommand = async (deviceId: string, commandType: string) => {
    await fetch('/api/communication/command', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ deviceId, commandType })
    });
  };

  return (
    <div>
      <button onClick={() => sendCommand('android-123', 'backup_now')}>
        Start Backup
      </button>
      <div>
        {messages.map(msg => (
          <div key={msg.id}>
            <strong>{msg.subject}</strong>
            <p>{msg.body}</p>
          </div>
        ))}
      </div>
    </div>
  );
}
```

---

## Best Practices

### 1. Polling Intervals
- **Commands**: Poll every 10-30 seconds
- **Messages**: Poll every 30-60 seconds
- **Status Updates**: Send as needed, not more than once per minute

### 2. Message Size
- Keep message bodies under 10KB
- Use metadata for structured data
- Store large data separately, send references

### 3. Error Handling
- Implement retry logic with exponential backoff
- Handle network failures gracefully
- Log all communication errors

### 4. Security
- Always use HTTPS
- Validate message sources
- Sanitize message content
- Implement rate limiting

---

## Monitoring

### Dashboard View
- Real-time message feed
- Command status tracking
- Communication statistics
- Error logs

### Metrics to Track
- Message delivery rate
- Average response time
- Failed message count
- Command execution success rate

---

## Troubleshooting

### Messages Not Appearing
- Check network connectivity
- Verify API endpoint URLs
- Confirm message format is correct
- Check server logs for errors

### Commands Not Executing
- Ensure device is polling regularly
- Verify command type is valid
- Check device logs for errors
- Confirm command status in database

### High Latency
- Reduce polling intervals
- Optimize message size
- Check network bandwidth
- Consider implementing WebSocket (future enhancement)

---

## Future Enhancements

1. **WebSocket Support**: Real-time bidirectional communication
2. **Message Encryption**: End-to-end encryption for sensitive data
3. **Message Queuing**: Reliable message delivery with queues
4. **Push Notifications**: Native push for Android devices
5. **Message Acknowledgment**: Delivery confirmation system

---

## Support

For issues or questions, refer to the main MyCloudVault documentation.
