Files
blackroad-operating-system/backend/app/main.py
Claude 138d79a6e3 Integrate BlackRoad OS front-end with FastAPI backend
This commit transforms the BlackRoad OS from a static mockup into a fully
functional web-based operating system with real backend integration.

## Major Changes

### Backend (New Features)

1. **Device Management System** (IoT/Raspberry Pi)
   - New models: Device, DeviceMetric, DeviceLog
   - Router: /api/devices with full CRUD operations
   - Device heartbeat system for status monitoring
   - Metrics tracking (CPU, RAM, temperature)

2. **Mining Stats & Control** (RoadCoin Miner)
   - Router: /api/miner with status, stats, control endpoints
   - Simulated mining with hashrate, shares, temperature
   - Start/stop mining controls
   - Lifetime statistics and recent blocks listing

3. **Static File Serving**
   - Backend now serves front-end from /backend/static/
   - index.html served at root URL
   - API routes under /api/* namespace

4. **Updated User Model**
   - Added devices relationship

### Frontend (New Features)

1. **API Client Module** (api-client.js)
   - Centralized API communication layer
   - Automatic base URL detection (dev vs prod)
   - JWT token management with auto-refresh
   - Error handling and 401 redirects

2. **Authentication System** (auth.js)
   - Login/Register modal UI
   - Session persistence via localStorage
   - Auto-logout on token expiration
   - Keyboard shortcuts (Enter to submit)

3. **Application Modules** (apps.js)
   - Dynamic data loading for all desktop windows
   - Auto-refresh for real-time data (miner, blockchain)
   - Event-driven architecture
   - Lazy loading (data fetched only when window opens)

4. **Enhanced UI**
   - Added 380+ lines of CSS for new components
   - Auth modal styling
   - Miner dashboard layout
   - Blockchain explorer tables
   - Wallet balance display
   - Device management cards

5. **Live Window Integration**
   - RoadCoin Miner: Real mining stats, start/stop controls
   - RoadChain Explorer: Live blockchain data, mine block button
   - Wallet: Real-time balance, transaction history
   - Raspberry Pi: Device status dashboard
   - RoadMail: Live inbox from API
   - Social Feed: Real posts from database
   - BlackStream: Video grid from API
   - AI Assistant: Conversation UI

### Configuration

- Updated .env.example with:
  - ROADCHAIN_RPC_URL, ROADCOIN_POOL_URL
  - MQTT broker settings for device management
  - Production CORS origins (www.blackroad.systems)
  - PORT configuration for Railway deployment

### Documentation

- Added INTEGRATION_GUIDE.md (400+ lines)
  - Complete architecture overview
  - API endpoint documentation
  - Environment configuration guide
  - Development workflow
  - Troubleshooting section

## Technical Details

- All windows now connect to real backend APIs
- Authentication required before OS access
- User-specific data isolation
- Proper error handling and loading states
- Retro Windows 95 aesthetic preserved

## What's Working

 Full authentication flow (login/register)
 Mining stats and control
 Blockchain explorer with live data
 Wallet with real balance
 Device management dashboard
 Email inbox integration
 Social feed integration
 Video platform integration
 Static file serving
 CORS configuration

## Future Enhancements

- Real XMRig integration
- WebSocket for real-time updates
- MQTT broker for device heartbeats
- OpenAI/Anthropic API integration
- File uploads to S3
- Email sending via SMTP

## Files Added

- backend/app/models/device.py
- backend/app/routers/devices.py
- backend/app/routers/miner.py
- backend/static/index.html
- backend/static/js/api-client.js
- backend/static/js/auth.js
- backend/static/js/apps.js
- INTEGRATION_GUIDE.md

## Files Modified

- backend/app/main.py (added routers, static file serving)
- backend/app/models/user.py (added devices relationship)
- backend/.env.example (added device & mining variables)

Tested locally with Docker Compose (PostgreSQL + Redis).
Ready for Railway deployment.
2025-11-16 07:19:45 +00:00

171 lines
4.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
@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")
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)
# 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"
},
"documentation": {
"swagger": "/api/docs",
"redoc": "/api/redoc",
"openapi": "/api/openapi.json"
}
}