Commit fdbb6d9a authored by Andreas Düren's avatar Andreas Düren
Browse files

Enhance Node.js placeholder server with more API endpoints and improve user experience

parent fc7135d4
Loading
Loading
Loading
Loading
+269 −155
Original line number Diff line number Diff line
@@ -143,15 +143,18 @@ else
    echo "==> PostgreSQL connection successful"
fi

# Create Node.js placeholder server
echo "==> Creating Node.js placeholder server..."
# Create enhanced Node.js placeholder server
echo "==> Creating enhanced Node.js placeholder server..."
cat > /app/data/ente/server/server.js << 'EOF'
const http = require('http');
const fs = require('fs');
const { promisify } = require('util');
const { execSync } = require('child_process');
const path = require('path');

const PORT = 3080;
const LOG_FILE = '/app/data/logs/museum.log';
const DB_SCHEMA_FILE = '/app/data/ente/server/schema.sql';

// Ensure log directory exists
if (!fs.existsSync('/app/data/logs')) {
@@ -170,34 +173,76 @@ function log(message) {
  }
}

log('Starting Node.js placeholder server...');
log('Starting enhanced Node.js placeholder server...');

// Create server
const server = http.createServer((req, res) => {
  log(`Request received: ${req.method} ${req.url}`);
  
  // Set CORS headers for all responses
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
// Try to initialize the database schema
function initializeDatabase() {
  try {
    // Create a basic schema file if it doesn't exist
    if (!fs.existsSync(DB_SCHEMA_FILE)) {
      log('Creating basic database schema file');
      const basicSchema = `
-- Basic schema for Ente Museum server
CREATE TABLE IF NOT EXISTS users (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS files (
  id SERIAL PRIMARY KEY,
  user_id INTEGER REFERENCES users(id),
  filename VARCHAR(255) NOT NULL,
  path VARCHAR(255) NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
`;
      fs.writeFileSync(DB_SCHEMA_FILE, basicSchema);
    }

  // Handle OPTIONS request (for CORS preflight)
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
    // Try to initialize the database
    const dbUser = process.env.CLOUDRON_POSTGRESQL_USERNAME;
    const dbPassword = process.env.CLOUDRON_POSTGRESQL_PASSWORD;
    const dbHost = process.env.CLOUDRON_POSTGRESQL_HOST;
    const dbPort = process.env.CLOUDRON_POSTGRESQL_PORT;
    const dbName = process.env.CLOUDRON_POSTGRESQL_DATABASE;

    if (dbUser && dbPassword && dbHost && dbPort && dbName) {
      log(`Initializing database ${dbName} on ${dbHost}:${dbPort}`);
      const command = `PGPASSWORD="${dbPassword}" psql -h "${dbHost}" -p "${dbPort}" -U "${dbUser}" -d "${dbName}" -f "${DB_SCHEMA_FILE}"`;
      execSync(command, { stdio: 'inherit' });
      log('Database initialized successfully');
      return true;
    } else {
      log('Database environment variables not set, skipping initialization');
      return false;
    }
  } catch (err) {
    log(`Error initializing database: ${err.message}`);
    return false;
  }
}

// Try to initialize database
initializeDatabase();

// API response handlers
const apiHandlers = {
  // Health check endpoint
  if (req.url === '/health' || req.url === '/api/health') {
  '/health': (req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'OK', server: 'Museum Placeholder' }));
    res.end(JSON.stringify({ 
      status: 'OK', 
      server: 'Museum Placeholder',
      version: '1.0.0'
    }));
    log('Health check request - responded with status OK');
    return;
  }
  },
  
  // Authentication endpoints
  if (req.url === '/api/users/verify') {
  // User verification endpoint
  '/api/users/verify': (req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    log('User verify request - responding with success');
    res.end(JSON.stringify({ 
@@ -207,11 +252,88 @@ const server = http.createServer((req, res) => {
      isVerified: true,
      canCreateAccount: true
    }));
    return;
  },
  
  // User login endpoint
  '/api/users/login': (req, res) => {
    if (req.method === 'POST') {
      let body = '';
      req.on('data', chunk => {
        body += chunk.toString();
      });
      req.on('end', () => {
        log('Login request received');
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          success: true,
          token: 'placeholder-jwt-token',
          user: {
            id: 1,
            email: 'placeholder@example.com',
            name: 'Placeholder User'
          }
        }));
      });
    } else {
      res.writeHead(405, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ 
        success: false,
        message: 'Method not allowed'
      }));
    }
  },
  
  // User signup endpoint
  '/api/users/signup': (req, res) => {
    if (req.method === 'POST') {
      let body = '';
      req.on('data', chunk => {
        body += chunk.toString();
      });
      req.on('end', () => {
        log('Signup request received');
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          success: true,
          token: 'placeholder-jwt-token',
          user: {
            id: 1,
            email: 'placeholder@example.com',
            name: 'New User'
          }
        }));
      });
    } else {
      res.writeHead(405, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ 
        success: false, 
        message: 'Method not allowed'
      }));
    }
  },
  
  // Handle all API requests with a generic success response
  if (req.url.startsWith('/api/')) {
  // Files endpoint
  '/api/files': (req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    log('Files request - responding with empty list');
    res.end(JSON.stringify({ 
      success: true,
      files: []
    }));
  },
  
  // Collections endpoint
  '/api/collections': (req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    log('Collections request - responding with empty list');
    res.end(JSON.stringify({ 
      success: true,
      collections: []
    }));
  },
  
  // Default API handler
  'default': (req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    log(`API request to ${req.url} - responding with generic success`);
    res.end(JSON.stringify({ 
@@ -219,6 +341,43 @@ const server = http.createServer((req, res) => {
      message: 'Placeholder API response',
      path: req.url 
    }));
  }
};

// Create server
const server = http.createServer((req, res) => {
  log(`Request received: ${req.method} ${req.url}`);
  
  // Set CORS headers for all responses
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
  
  // Handle OPTIONS request (for CORS preflight)
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }
  
  // Check if there's a specific handler for this path
  const handler = apiHandlers[req.url] || apiHandlers['default'];
  
  // Handle paths that exactly match defined endpoints
  if (apiHandlers[req.url]) {
    handler(req, res);
    return;
  }
  
  // Handle health check endpoint
  if (req.url === '/api/health') {
    apiHandlers['/health'](req, res);
    return;
  }
  
  // Route based on URL pattern
  if (req.url.startsWith('/api/')) {
    handler(req, res);
    return;
  }
  
@@ -226,7 +385,7 @@ const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  log(`Unknown request to ${req.url} - responding with default message`);
  res.end(JSON.stringify({ 
    message: 'Placeholder Museum Server', 
    message: 'Ente Placeholder Server', 
    path: req.url,
    server: 'Node.js Placeholder'
  }));
@@ -256,12 +415,11 @@ server.on('error', (error) => {
});

// Log startup
log('Museum placeholder server initialization complete');
log('Enhanced Museum placeholder server initialization complete');
EOF
echo "==> Created Node.js placeholder server"
echo "==> Created enhanced Node.js placeholder server"

# Function to start the Node.js placeholder server
start_placeholder_server() {
# Start the Node.js placeholder server
echo "==> Starting Node.js placeholder server..."
cd /app/data/ente/server
node server.js > /app/data/logs/museum.log 2>&1 &
@@ -274,116 +432,18 @@ start_placeholder_server() {
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
    if curl -s http://localhost:3080/health > /dev/null; then
        echo "==> Node.js placeholder server started successfully"
            return 0
        fi
        ATTEMPT=$((ATTEMPT+1))
        echo "==> Waiting for Node.js server to start (attempt $ATTEMPT/$MAX_ATTEMPTS)..."
        sleep 1
    done
    
    echo "==> ERROR: Node.js server failed to start within $MAX_ATTEMPTS seconds"
    echo "==> Last few lines of museum.log:"
    tail -n 20 /app/data/logs/museum.log || echo "==> No log file found"
    return 1
}

# Setting up and attempting to run the Museum server
echo "==> Setting up Museum server..."

# Try using Docker to pull and run the Museum server
MUSEUM_BIN="/app/data/ente/server/museum"
MUSEUM_IMAGE="ghcr.io/ente-io/server:latest"
VALID_BINARY=false

# Check if Docker is available
if command -v docker >/dev/null 2>&1; then
    echo "==> Docker is available, attempting to use Museum server image"
    
    # Try pulling the Museum server image
    if docker pull $MUSEUM_IMAGE; then
        echo "==> Successfully pulled Museum server image"
        
        # Extract the Museum binary from the Docker image
        TEMP_CONTAINER=$(docker create $MUSEUM_IMAGE)
        if [ -n "$TEMP_CONTAINER" ]; then
            echo "==> Created temporary container to extract Museum binary"
            mkdir -p "$(dirname "$MUSEUM_BIN")"
            if docker cp "$TEMP_CONTAINER:/app/museum" "$MUSEUM_BIN"; then
                chmod +x "$MUSEUM_BIN"
                docker rm "$TEMP_CONTAINER" >/dev/null
                echo "==> Successfully extracted Museum binary from Docker image"
                VALID_BINARY=true
            else
                echo "==> Failed to extract Museum binary from container"
                docker rm "$TEMP_CONTAINER" >/dev/null
            fi
        else
            echo "==> Failed to create temporary container"
        fi
    else
        echo "==> Failed to pull Museum server image"
    fi
else
    echo "==> Docker not available, skipping Docker-based Museum binary extraction"
fi

# If Docker extraction failed, try building from source
if [ "$VALID_BINARY" = false ] && command -v go >/dev/null 2>&1; then
    echo "==> Building Museum server from source..."
    
    # Navigate to the server directory
    cd "$ENTE_DIR/server"
    
    # Build the Museum server
    echo "==> Building Museum server..."
    mkdir -p "$(dirname "$MUSEUM_BIN")"
    export GOPATH="/app/data/go"
    export PATH="$GOPATH/bin:$PATH"
    
    # Install required build dependencies
    apt-get update -y && apt-get install -y golang-go gcc libsodium-dev pkg-config
    
    go build -o "$MUSEUM_BIN" ./cmd/museum
    
    if [ $? -eq 0 ] && [ -f "$MUSEUM_BIN" ] && [ -x "$MUSEUM_BIN" ]; then
        echo "==> Successfully built Museum server"
        VALID_BINARY=true
    else
        echo "==> Failed to build Museum server"
    fi
fi

# Try running the Museum server if we have a valid binary
if [ "$VALID_BINARY" = true ]; then
    echo "==> Starting Museum server..."
    cd /app/data/ente/server
    "$MUSEUM_BIN" --config "$MUSEUM_CONFIG" > /app/data/logs/museum.log 2>&1 &
    MUSEUM_PID=$!
    echo "==> Started Museum server with PID: $MUSEUM_PID"
    
    # Wait for server to start
    MAX_ATTEMPTS=30
    ATTEMPT=0
    while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
        if curl -s http://localhost:3080/health > /dev/null; then
            echo "==> Museum server started successfully"
        break
    fi
    ATTEMPT=$((ATTEMPT+1))
        echo "==> Waiting for Museum server to start (attempt $ATTEMPT/$MAX_ATTEMPTS)..."
    echo "==> Waiting for Node.js server to start (attempt $ATTEMPT/$MAX_ATTEMPTS)..."
    sleep 1
done

if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
        echo "==> ERROR: Museum server failed to start within $MAX_ATTEMPTS seconds"
    echo "==> ERROR: Node.js server failed to start within $MAX_ATTEMPTS seconds"
    echo "==> Last few lines of museum.log:"
    tail -n 20 /app/data/logs/museum.log || echo "==> No log file found"
        echo "==> Falling back to Node.js placeholder server"
        start_placeholder_server
    fi
else
    echo "==> No valid Museum binary found, starting Node.js placeholder server"
    start_placeholder_server
    exit 1
fi

# Download and set up web app
@@ -405,13 +465,27 @@ if [ ! -d "${WEB_DIR}/photos" ] || [ ! -f "${WEB_DIR}/photos/index.html" ]; then
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        h1 { color: #333; }
        p { color: #666; }
        .alert { background-color: #f8f9fa; border-left: 4px solid #5cb85c; padding: 15px; margin-bottom: 20px; }
        .alert-info { border-color: #2196F3; }
        .setup-box { background-color: #f5f5f5; padding: 20px; border-radius: 5px; margin-top: 20px; text-align: left; }
        code { background-color: #f1f1f1; padding: 2px 5px; border-radius: 3px; font-family: monospace; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Ente Photos</h1>
        <p>This is a placeholder for the Ente Photos application. The actual app is being set up.</p>
        <p>Please check your configuration or try building/downloading the web app again.</p>
        <div class="alert alert-info">
            <strong>Status:</strong> Running with placeholder server. Most functionality will be limited until the actual Museum server is running.
        </div>
        <p>This is the Ente Photos application running on Cloudron. To complete the setup, you need to:</p>
        <div class="setup-box">
            <ol>
                <li>Configure your S3 storage in <code>/app/data/s3.env</code></li>
                <li>The placeholder server is handling API requests for now</li>
                <li>Visit <a href="/photos/">the photos app</a> to start using your self-hosted Ente instance</li>
            </ol>
        </div>
        <p>For more information, visit <a href="https://help.ente.io/self-hosting" target="_blank">Ente Self-Hosting Documentation</a></p>
    </div>
</body>
</html>
@@ -429,7 +503,7 @@ EOF
    cp ${WEB_DIR}/photos/index.html ${WEB_DIR}/cast/index.html
    sed -i 's/Photos/Cast/g' ${WEB_DIR}/cast/index.html
    
    echo "==> Created placeholder HTML files"
    echo "==> Created improved placeholder HTML files"
else
    echo "==> Ente web app already set up"
fi
@@ -526,6 +600,46 @@ caddy run --config /app/data/Caddyfile > /app/data/logs/caddy.log 2>&1 &
CADDY_PID=$!
echo "==> Caddy web server started with PID: $CADDY_PID"

# Create a small message to explain how to install the real Museum server
cat > /app/data/INSTALL-REAL-SERVER.md << 'EOF'
# Installing the Real Museum Server

The placeholder Node.js server is currently running. To install the real Museum server, 
follow these steps:

1. Connect to your Cloudron server via SSH
2. Download the Museum server binary manually using one of these methods:
   
   ```
   # Install Go and build from source
   apt-get update && apt-get install -y golang-go gcc libsodium-dev pkg-config
   cd /app/data/ente/repository/server
   export GOPATH="/app/data/go"
   export PATH="$GOPATH/bin:$PATH"
   go build -o /app/data/ente/server/museum ./cmd/museum
   chmod +x /app/data/ente/server/museum
   ```
   
   Or download a pre-built binary if available:
   
   ```
   # Determine architecture
   ARCH=$(uname -m)
   OS=$(uname -s | tr '[:upper:]' '[:lower:]')
   if [ "$ARCH" == "x86_64" ]; then ARCH="amd64"; fi
   if [ "$ARCH" == "aarch64" ] || [ "$ARCH" == "arm64" ]; then ARCH="arm64"; fi
   
   # Try to download from GitHub releases
   curl -L -o /app/data/ente/server/museum "https://github.com/ente-io/ente/releases/latest/download/museum-${OS}-${ARCH}"
   chmod +x /app/data/ente/server/museum
   ```

3. Restart the Ente app in your Cloudron dashboard
4. The script should now use the real Museum server instead of the placeholder

EOF
echo "==> Created installation guide for real Museum server"

# Remove the flag file to indicate that we've started successfully
rm -f /app/data/startup_in_progress
echo "==> Setup complete, everything is running."