File size: 14,822 Bytes
22087d0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
import uvicorn
import os
import subprocess
from pathlib import Path
from typing import Dict, List, Optional
# Import PDF router, PPTX router, DOCX router, and Visual HTML Editor router
from html_to_pdf_router import router as pdf_router
from visual_html_editor_router import router as editor_router
from html_to_pptx_router import router as pptx_router
from html_to_docx_router import router as docx_router
# Ensure we're serving from the /workspace directory
workspace_dir = "/workspace"
class WorkspaceDirMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Check if workspace directory exists and recreate if deleted
if not os.path.exists(workspace_dir):
print(f"Workspace directory {workspace_dir} not found, recreating...")
os.makedirs(workspace_dir, exist_ok=True)
return await call_next(request)
app = FastAPI()
app.add_middleware(WorkspaceDirMiddleware)
# Include routers
app.include_router(pdf_router)
app.include_router(editor_router)
app.include_router(pptx_router)
app.include_router(docx_router)
# Create downloads directory in workspace for all generated files
downloads_dir = Path(workspace_dir) / "downloads"
downloads_dir.mkdir(parents=True, exist_ok=True)
# Mount static files for downloads (PDFs, PPTX, etc.)
app.mount("/downloads", StaticFiles(directory=str(downloads_dir)), name="downloads")
# Create output directory for generated PDFs (legacy - for backward compatibility)
output_dir = Path("generated_pdfs")
output_dir.mkdir(exist_ok=True)
# Initial directory creation
os.makedirs(workspace_dir, exist_ok=True)
# Add visual HTML editor root endpoint
@app.get("/editor")
async def list_html_files():
"""List all HTML files in the workspace for easy access"""
from fastapi.responses import HTMLResponse
try:
html_files = [f for f in os.listdir(workspace_dir) if f.endswith('.html')]
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual HTML Editor</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, system-ui, sans-serif;
background: white;
color: black;
line-height: 1.5;
max-width: 900px;
margin: 0 auto;
padding: 40px 20px;
}
.header {
text-align: center;
margin-bottom: 32px;
border-bottom: 1px solid #e4e4e7;
padding-bottom: 24px;
}
.header h1 {
font-size: 24px;
font-weight: 600;
letter-spacing: -0.025em;
margin-bottom: 8px;
color: #09090b;
}
.header p {
font-size: 14px;
color: #71717a;
font-weight: 400;
}
.file-list {
border: 1px solid #e4e4e7;
border-radius: 8px;
overflow: hidden;
}
.file-item {
padding: 16px 20px;
border-bottom: 1px solid #e4e4e7;
display: flex;
justify-content: space-between;
align-items: center;
transition: background-color 0.15s ease;
}
.file-item:hover {
background: #f4f4f5;
}
.file-item:last-child {
border-bottom: none;
}
.file-name {
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
font-size: 14px;
font-weight: 500;
color: black;
}
.file-actions {
display: flex;
gap: 12px;
}
.btn {
padding: 8px 16px;
text-decoration: none;
font-size: 13px;
font-weight: 500;
border: 1px solid #e4e4e7;
color: #09090b;
background: white;
transition: all 0.15s ease;
text-align: center;
min-width: 60px;
border-radius: 6px;
}
.btn:hover {
background: #f4f4f5;
border-color: #d4d4d8;
}
.btn-edit {
background: #09090b;
color: white;
border-color: #09090b;
}
.btn-edit:hover {
background: #18181b;
border-color: #18181b;
}
.empty-state {
text-align: center;
padding: 64px 20px;
color: #71717a;
border: 1px solid #e4e4e7;
border-radius: 8px;
}
.empty-state h3 {
font-size: 16px;
font-weight: 500;
margin-bottom: 8px;
color: #09090b;
}
.info {
margin-top: 32px;
padding: 20px;
background: #fafafa;
border: 1px solid #e4e4e7;
border-radius: 8px;
}
.info h3 {
font-size: 16px;
font-weight: 500;
margin-bottom: 12px;
}
.info-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.info-item {
font-size: 14px;
line-height: 1.4;
}
.info-item strong {
font-weight: 500;
}
@media (max-width: 600px) {
.info-grid {
grid-template-columns: 1fr;
}
.file-item {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.file-actions {
width: 100%;
justify-content: flex-end;
}
}
</style>
</head>
<body>
<div class="header">
<h1>Visual HTML Editor</h1>
<p>Click-to-edit any HTML file with live preview</p>
</div>
<div class="file-list">
"""
if html_files:
for file in sorted(html_files):
html_content += f"""
<div class="file-item">
<div class="file-name">{file}</div>
<div class="file-actions">
<a href="/{file}" class="btn" target="_blank">View</a>
<a href="/api/html/{file}/editor" class="btn btn-edit" target="_blank">Edit</a>
</div>
</div>
"""
else:
html_content += """
<div class="empty-state">
<h3>No files found</h3>
<p>Add .html files to this directory to start editing</p>
</div>
"""
html_content += """
</div>
<div class="info">
<h3>How to use</h3>
<div class="info-grid">
<div class="info-item">
<strong>Edit text:</strong> Hover over any text and click the edit icon
</div>
<div class="info-item">
<strong>Delete elements:</strong> Click the trash icon to remove content
</div>
<div class="info-item">
<strong>Save changes:</strong> Press Ctrl+Enter or click Save
</div>
<div class="info-item">
<strong>Cancel editing:</strong> Press Escape or click Cancel
</div>
</div>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
except Exception as e:
print(f"❌ Error listing HTML files: {e}")
from fastapi import HTTPException
raise HTTPException(status_code=500, detail=str(e))
# Health check endpoint - must be defined before catch-all route
@app.get("/health")
async def health_check():
"""
Check health of all supervisord-managed services.
Returns aggregate status and per-service breakdown.
Returns:
- status: "healthy" | "starting" | "degraded" | "unhealthy"
- services: dict of service_name -> "running" | "stopped" | "starting" | "error"
- critical_services: list of services that must be running for healthy status
"""
services_status: Dict[str, str] = {}
# Critical services that must be running for sandbox to be usable
critical_services: List[str] = ['xvfb', 'x11vnc', 'novnc', 'http_server', 'browserApi']
try:
# Run supervisorctl status to get all service states
result = subprocess.run(
["supervisorctl", "status"],
capture_output=True,
text=True,
timeout=5
)
# Parse output format: "program_name STATE extra info"
# Example: "xvfb RUNNING pid 123, uptime 0:01:00"
for line in result.stdout.strip().split('\n'):
if not line.strip():
continue
parts = line.split()
if len(parts) >= 2:
service_name = parts[0]
state = parts[1].lower()
# Map supervisord states to our simplified states
if state == 'running':
services_status[service_name] = 'running'
elif state in ('stopped', 'exited', 'fatal'):
services_status[service_name] = 'stopped'
elif state in ('starting', 'backoff'):
services_status[service_name] = 'starting'
else:
services_status[service_name] = 'error'
except subprocess.TimeoutExpired:
return {
"status": "unhealthy",
"error": "supervisorctl timeout",
"services": {},
"critical_services": critical_services
}
except FileNotFoundError:
return {
"status": "unhealthy",
"error": "supervisorctl not found",
"services": {},
"critical_services": critical_services
}
except Exception as e:
return {
"status": "unhealthy",
"error": str(e),
"services": {},
"critical_services": critical_services
}
# Determine overall status based on critical services
critical_running = sum(
1 for svc in critical_services
if services_status.get(svc) == 'running'
)
critical_starting = sum(
1 for svc in critical_services
if services_status.get(svc) == 'starting'
)
critical_failed = sum(
1 for svc in critical_services
if services_status.get(svc) in ('stopped', 'error')
)
# All critical services running = healthy
if critical_running == len(critical_services):
overall = "healthy"
# Some starting, none failed = starting
elif critical_starting > 0 and critical_failed == 0:
overall = "starting"
# Some failed = degraded
elif critical_failed > 0 and critical_running > 0:
overall = "degraded"
# All failed or none running = unhealthy
else:
overall = "unhealthy"
return {
"status": overall,
"services": services_status,
"critical_services": critical_services
}
# Serve files at root level
# This route handles both HTML files and static assets (CSS, JS, images, etc.)
# Uses :path to handle nested paths like css/style.css or js/script.js
@app.get("/{file_path:path}")
async def serve_file(file_path: str):
"""Serve files from workspace - HTML files as HTML, others as static files"""
from fastapi import HTTPException
from fastapi.responses import HTMLResponse, FileResponse
# Security: prevent directory traversal attacks
if '..' in file_path or file_path.startswith('/'):
raise HTTPException(status_code=400, detail="Invalid file path")
full_file_path = os.path.join(workspace_dir, file_path)
# Normalize the path to prevent directory traversal
full_file_path = os.path.normpath(full_file_path)
workspace_dir_normalized = os.path.normpath(workspace_dir)
# Ensure the file is within the workspace directory
if not full_file_path.startswith(workspace_dir_normalized):
raise HTTPException(status_code=403, detail="Access denied")
if not os.path.exists(full_file_path) or not os.path.isfile(full_file_path):
raise HTTPException(status_code=404, detail="File not found")
# Serve HTML files with HTMLResponse
if file_path.endswith('.html'):
with open(full_file_path, 'r', encoding='utf-8') as f:
content = f.read()
return HTMLResponse(content=content)
# Serve all other files (CSS, JS, images, etc.) as static files
# FileResponse automatically sets the correct content-type based on file extension
return FileResponse(full_file_path)
# This is needed for the import string approach with uvicorn
if __name__ == '__main__':
print(f"Starting server with auto-reload, serving files from: {workspace_dir}")
# Don't use reload directly in the run call
uvicorn.run("server:app", host="0.0.0.0", port=8080, reload=True) |