# MyCloudVault Server Setup Guide

## Overview

This guide explains how to set up PC or cloud servers to work with MyCloudVault's Android backup system. Servers store backup data from Android devices and communicate with the MyCloudVault dashboard via REST APIs.

## Server Types

### 1. PC Server
- **Use Case:** Home/office PC with large storage capacity
- **Requirements:** Always-on computer, stable network connection
- **Advantages:** Full control, no cloud costs, local data storage

### 2. Cloud Server
- **Use Case:** AWS S3, Google Cloud Storage, Azure Blob Storage
- **Requirements:** Cloud account, API credentials
- **Advantages:** High availability, scalable storage, remote access

---

## API Endpoints

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

### 1. Register Server

**Endpoint:** `POST /api/servers/register`

**Purpose:** Register a new backup server with the system.

**Request Body:**
```json
{
  "serverId": "home-pc-001",
  "name": "Home PC",
  "type": "pc",
  "ipAddress": "192.168.1.100",
  "port": 8080,
  "storageTotal": 1000
}
```

**Response:**
```json
{
  "success": true,
  "server": {
    "id": 1,
    "serverId": "home-pc-001",
    "name": "Home PC",
    "apiKey": "a1b2c3d4e5f6...",
    "status": "online",
    "...": "..."
  }
}
```

**Important:** Save the `apiKey` securely. You'll need it for all subsequent API calls.

---

### 2. Health Check (Ping)

**Endpoint:** `POST /api/servers/:serverId/ping`

**Purpose:** Update server status and maintain "online" state.

**Request Body:**
```json
{
  "apiKey": "a1b2c3d4e5f6...",
  "storageUsed": 450
}
```

**Response:**
```json
{
  "success": true,
  "server": {
    "id": 1,
    "status": "online",
    "lastPing": "2025-12-12T21:00:00.000Z",
    "...": "..."
  }
}
```

**Recommendation:** Call this endpoint every 30-60 seconds to maintain online status.

---

### 3. Allocate Storage

**Endpoint:** `POST /api/servers/:serverId/allocate`

**Purpose:** Reserve storage space for backup operations.

**Request Body:**
```json
{
  "apiKey": "a1b2c3d4e5f6...",
  "allocateGB": 50
}
```

**Response:**
```json
{
  "success": true,
  "server": {
    "id": 1,
    "storageAllocated": 50,
    "...": "..."
  },
  "storageAvailable": 950
}
```

---

### 4. Get Server Status

**Endpoint:** `GET /api/servers/:serverId`

**Purpose:** Fetch current server information.

**Response:**
```json
{
  "success": true,
  "server": {
    "id": 1,
    "serverId": "home-pc-001",
    "name": "Home PC",
    "type": "pc",
    "status": "online",
    "storageTotal": 1000,
    "storageUsed": 450,
    "storageAllocated": 50,
    "lastPing": "2025-12-12T21:00:00.000Z"
  }
}
```

---

## PC Server Implementation

### Requirements
- Node.js 18+ or Python 3.8+
- Network connectivity
- Storage space for backups

### Example: Node.js Server

```javascript
const express = require('express');
const axios = require('axios');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 8080;
const CLOUDVAULT_API = 'https://vm6tgfyizy.preview.c24.airoapp.ai';

// Configuration (set these after registration)
const SERVER_ID = 'home-pc-001';
const API_KEY = 'your-api-key-here';
const BACKUP_DIR = '/path/to/backup/storage';

// Health check ping (every 30 seconds)
setInterval(async () => {
  try {
    const storageUsed = getStorageUsed(BACKUP_DIR);
    await axios.post(`${CLOUDVAULT_API}/api/servers/${SERVER_ID}/ping`, {
      apiKey: API_KEY,
      storageUsed: Math.floor(storageUsed / (1024 * 1024 * 1024)) // Convert to GB
    });
    console.log('Ping successful');
  } catch (error) {
    console.error('Ping failed:', error.message);
  }
}, 30000);

// Endpoint to receive backup data
app.post('/backup/upload', express.json(), async (req, res) => {
  try {
    const { deviceId, backupId, data } = req.body;
    
    // Save backup data
    const backupPath = path.join(BACKUP_DIR, deviceId, `${backupId}.backup`);
    fs.mkdirSync(path.dirname(backupPath), { recursive: true });
    fs.writeFileSync(backupPath, JSON.stringify(data));
    
    res.json({ success: true, path: backupPath });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Helper function to calculate storage usage
function getStorageUsed(dir) {
  let totalSize = 0;
  const files = fs.readdirSync(dir, { recursive: true });
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    if (fs.statSync(filePath).isFile()) {
      totalSize += fs.statSync(filePath).size;
    }
  });
  
  return totalSize;
}

app.listen(PORT, () => {
  console.log(`Backup server running on port ${PORT}`);
});
```

### Setup Steps

1. **Register the server:**
   - Use the MyCloudVault dashboard "Add Server" button
   - Enter server details (ID, name, IP, port, storage)
   - Save the generated API key

2. **Configure the server script:**
   - Set `SERVER_ID` and `API_KEY` from registration
   - Set `BACKUP_DIR` to your storage location
   - Install dependencies: `npm install express axios`

3. **Run the server:**
   ```bash
   node server.js
   ```

4. **Verify connection:**
   - Check MyCloudVault dashboard for "online" status
   - Monitor server logs for successful pings

---

## Cloud Server Implementation

### AWS S3 Example

```javascript
const AWS = require('aws-sdk');
const axios = require('axios');

const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY,
  secretAccessKey: process.env.AWS_SECRET_KEY,
  region: 'us-east-1'
});

const BUCKET_NAME = 'mycloudvault-backups';
const SERVER_ID = 'aws-s3-001';
const API_KEY = 'your-api-key-here';
const CLOUDVAULT_API = 'https://vm6tgfyizy.preview.c24.airoapp.ai';

// Health check ping
setInterval(async () => {
  try {
    // Get bucket size
    const objects = await s3.listObjectsV2({ Bucket: BUCKET_NAME }).promise();
    const totalSize = objects.Contents.reduce((sum, obj) => sum + obj.Size, 0);
    const sizeGB = Math.floor(totalSize / (1024 * 1024 * 1024));
    
    await axios.post(`${CLOUDVAULT_API}/api/servers/${SERVER_ID}/ping`, {
      apiKey: API_KEY,
      storageUsed: sizeGB
    });
    
    console.log('Ping successful, storage:', sizeGB, 'GB');
  } catch (error) {
    console.error('Ping failed:', error.message);
  }
}, 30000);

// Upload backup to S3
async function uploadBackup(deviceId, backupId, data) {
  const key = `${deviceId}/${backupId}.backup`;
  
  await s3.putObject({
    Bucket: BUCKET_NAME,
    Key: key,
    Body: JSON.stringify(data),
    ContentType: 'application/json'
  }).promise();
  
  return { success: true, key };
}
```

---

## Security Best Practices

1. **API Key Protection:**
   - Store API keys in environment variables
   - Never commit keys to version control
   - Rotate keys periodically

2. **Network Security:**
   - Use HTTPS for all API calls
   - Configure firewall rules for PC servers
   - Use VPN for remote access

3. **Data Encryption:**
   - Encrypt backup data before transmission
   - Use encrypted storage (LUKS, BitLocker, etc.)
   - Implement end-to-end encryption

4. **Access Control:**
   - Limit server access to authorized devices
   - Use strong authentication
   - Monitor access logs

---

## Monitoring & Maintenance

### Dashboard Monitoring
- Check server status in MyCloudVault dashboard
- Monitor storage usage and allocation
- Review last ping timestamps

### Server Health Checks
- Verify ping intervals (should be < 60 seconds)
- Monitor storage capacity
- Check network connectivity
- Review error logs

### Troubleshooting

**Server shows "offline":**
- Check network connection
- Verify API key is correct
- Ensure ping endpoint is being called
- Check server logs for errors

**Storage allocation fails:**
- Verify available storage capacity
- Check storage usage calculations
- Ensure API key has proper permissions

**Backup uploads fail:**
- Check server disk space
- Verify file permissions
- Monitor network bandwidth
- Review server error logs

---

## Support

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