Files
blackroad-operating-system/backend/app/main.py
Claude b22c95b639 Add comprehensive service integrations and games to BlackRoad OS
This massive update transforms BlackRoad OS into a complete virtual operating
system with modern cloud integrations and retro-styled games.

New API Integrations:
- DigitalOcean: Droplet management, spaces, regions, and account info
- GitHub: Repo browsing, commits, PRs, issues, code search, notifications
- Hugging Face: Model browser, inference API, datasets, spaces, trending
- VS Code: Monaco editor integration with file tree and syntax highlighting

Games (SimCity/Sims style):
- Road City: City builder with zones, utilities, services, and resources
- Road Life: Life simulator with characters, needs, skills, and jobs
- RoadCraft: Voxel world builder with block placement

Enhanced Features:
- RoadView Browser: Web proxy with bookmarks, history, tabs, and search
- Device Manager: SSH connections, remote command execution, deployments
- Unified Dashboard: Comprehensive overview of all services and stats

Backend Enhancements:
- 7 new API routers with 100+ endpoints
- Enhanced device management with SSH and deployment capabilities
- Service health monitoring and activity tracking
- Support for DigitalOcean, GitHub, and Hugging Face tokens

Configuration:
- Added environment variables for new API tokens
- All integrations properly registered in main.py
- Comprehensive error handling and validation

This brings the total to 15+ integrated services creating a complete
retro-styled virtual operating system with AI, cloud, games, and dev tools.
2025-11-16 08:33:00 +00:00

196 lines
5.7 KiB
Python

"""Main FastAPI application"""
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import time
import os
from app.config import settings
from app.database import async_engine, Base
from app.redis_client import close_redis
from app.routers import (
auth, email, social, video, files, blockchain, ai_chat, devices, miner,
digitalocean, github, huggingface, vscode, games, browser, dashboard
)
from app.services.crypto import rotate_plaintext_wallet_keys
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan events"""
# Startup
print("Starting BlackRoad Operating System Backend...")
# Create database tables
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
print("Database tables created successfully")
print(f"Server running on {settings.ENVIRONMENT} mode")
# Re-encrypt any legacy plaintext wallet keys before serving requests
updated_users, updated_wallets = await rotate_plaintext_wallet_keys()
if updated_users or updated_wallets:
print(
f"Re-encrypted {updated_users} user keys and {updated_wallets} wallet keys"
)
yield
# Shutdown
print("Shutting down...")
await close_redis()
await async_engine.dispose()
print("Shutdown complete")
# Create FastAPI app
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
description="Backend API for BlackRoad Operating System - A Windows 95-inspired web OS",
lifespan=lifespan,
docs_url="/api/docs",
redoc_url="/api/redoc",
openapi_url="/api/openapi.json"
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins_list,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Request timing middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""Add processing time header to responses"""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
# Error handlers
@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
"""Handle 404 errors"""
return JSONResponse(
status_code=404,
content={"detail": "Resource not found"}
)
@app.exception_handler(500)
async def internal_error_handler(request: Request, exc):
"""Handle 500 errors"""
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"}
)
# Include routers
app.include_router(auth.router)
app.include_router(email.router)
app.include_router(social.router)
app.include_router(video.router)
app.include_router(files.router)
app.include_router(blockchain.router)
app.include_router(ai_chat.router)
app.include_router(devices.router)
app.include_router(miner.router)
app.include_router(digitalocean.router)
app.include_router(github.router)
app.include_router(huggingface.router)
app.include_router(vscode.router)
app.include_router(games.router)
app.include_router(browser.router)
app.include_router(dashboard.router)
# Static file serving for the BlackRoad OS front-end
static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static")
if os.path.exists(static_dir):
# Mount static files (JS, CSS, images)
app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
# Serve index.html at root
@app.get("/")
async def serve_frontend():
"""Serve the BlackRoad OS desktop interface"""
index_path = os.path.join(static_dir, "index.html")
if os.path.exists(index_path):
return FileResponse(index_path)
return {
"name": settings.APP_NAME,
"version": settings.APP_VERSION,
"environment": settings.ENVIRONMENT,
"docs": "/api/docs",
"status": "operational",
"note": "Front-end not found. API is operational."
}
else:
# Fallback if static directory doesn't exist
@app.get("/")
async def root():
"""Root endpoint"""
return {
"name": settings.APP_NAME,
"version": settings.APP_VERSION,
"environment": settings.ENVIRONMENT,
"docs": "/api/docs",
"status": "operational",
"note": "API-only mode. Front-end not deployed."
}
# Health check
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"timestamp": time.time()
}
# API info
@app.get("/api")
async def api_info():
"""API information"""
return {
"name": settings.APP_NAME,
"version": settings.APP_VERSION,
"endpoints": {
"auth": "/api/auth",
"email": "/api/email",
"social": "/api/social",
"videos": "/api/videos",
"files": "/api/files",
"blockchain": "/api/blockchain",
"ai_chat": "/api/ai-chat",
"devices": "/api/devices",
"miner": "/api/miner",
"digitalocean": "/api/digitalocean",
"github": "/api/github",
"huggingface": "/api/huggingface",
"vscode": "/api/vscode",
"games": "/api/games",
"browser": "/api/browser",
"dashboard": "/api/dashboard"
},
"documentation": {
"swagger": "/api/docs",
"redoc": "/api/redoc",
"openapi": "/api/openapi.json"
}
}