File size: 9,134 Bytes
3533fb9
 
 
 
 
 
d8cd523
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8cd523
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2893cc2
3533fb9
 
2893cc2
 
 
 
 
 
 
d8cd523
2893cc2
 
 
 
 
 
 
 
 
 
 
 
3533fb9
2893cc2
 
3533fb9
 
 
2893cc2
3533fb9
 
 
 
d8cd523
2893cc2
 
3533fb9
2893cc2
3533fb9
 
2893cc2
3533fb9
 
 
 
 
d8cd523
 
3533fb9
2893cc2
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0eeeed2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3533fb9
0eeeed2
 
 
 
 
 
 
 
 
 
 
 
 
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Depends, Request, WebSocket, WebSocketDisconnect, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.api.v1.api import api_router
from app.api.v1.endpoints import seo
from app.core import dependencies
from app.core.config import CORS_ALLOW_ORIGIN_REGEX, CORS_ALLOWED_ORIGINS
from app.core.error_handlers import register_exception_handlers
from fastapi.middleware.gzip import GZipMiddleware
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from redis import asyncio as aioredis


# Database initialized via Supabase schema
import app.worker

from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
import uuid
import logging
import os

logger = logging.getLogger("monteeq")
ALLOWED_ORIGINS = set(CORS_ALLOWED_ORIGINS)

app = FastAPI(
    title="Monteeq Video Platform",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
)

app.add_middleware(GZipMiddleware, minimum_size=1000)


# ── Request-ID Middleware ──────────────────────────────────────────────────────
class RequestIDMiddleware(BaseHTTPMiddleware):
    """Attach a unique X-Request-ID to every request/response for tracing."""
    async def dispatch(self, request: Request, call_next):
        request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
        request.state.request_id = request_id
        response = await call_next(request)
        response.headers["X-Request-ID"] = request_id
        return response

app.add_middleware(RequestIDMiddleware)

# ── Anti-Bot Middleware ───────────────────────────────────────────────────────
class AntiBotMiddleware(BaseHTTPMiddleware):
    """Identify and block malicious bots globally with CORS support."""

    async def dispatch(self, request: Request, call_next):
        from app.core import security

        # Short-circuit CORS preflight β€” return 200 with CORS headers immediately.
        # This prevents BaseHTTPMiddleware body-buffering from interfering with
        # CORSMiddleware and stops the form-body parser from running on OPTIONS.
        if request.method == "OPTIONS":
            origin = request.headers.get("Origin", "")
            response = JSONResponse(status_code=200, content={})
            if origin in ALLOWED_ORIGINS:
                response.headers["Access-Control-Allow-Origin"] = origin
                response.headers["Access-Control-Allow-Credentials"] = "true"
                response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, PATCH, OPTIONS"
                response.headers["Access-Control-Allow-Headers"] = "*"
                response.headers["Access-Control-Max-Age"] = "600"
            return response

        # Skip bot check for static files, health, and SEO endpoints
        if (request.url.path.startswith("/static") or
                request.url.path == "/health" or
                "/seo/" in request.url.path or
                "sitemap" in request.url.path):
            return await call_next(request)

        # Heuristic bot check
        if security.is_bot(request):
            ua = request.headers.get("User-Agent", "Unknown")
            logger.warning(f"Bot detected and blocked: {ua} from {request.client.host if request.client else 'unknown'}")
            origin = request.headers.get("Origin", "")
            response = JSONResponse(
                status_code=403,
                content={"detail": "Access denied. Automated traffic detected.", "ua": ua}
            )
            if origin in ALLOWED_ORIGINS:
                response.headers["Access-Control-Allow-Origin"] = origin
                response.headers["Access-Control-Allow-Credentials"] = "true"
            return response

        return await call_next(request)


app.add_middleware(AntiBotMiddleware)

# CORS middleware - MUST be added before other middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=CORS_ALLOWED_ORIGINS,
    allow_origin_regex=CORS_ALLOW_ORIGIN_REGEX,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
    allow_headers=["*"],
)

# Mount static files
static_path = os.path.join(os.path.dirname(__file__), "static")
os.makedirs(static_path, exist_ok=True)
app.mount("/static", StaticFiles(directory=static_path), name="static")

# ── Global Exception Handlers ────────────────────────────────────────────────
register_exception_handlers(app)

# ── Routers ───────────────────────────────────────────────────────────────────
app.include_router(api_router, prefix="/api/v1")
app.include_router(seo.router)


# ── WebSocket Chat Endpoint ───────────────────────────────────────────────────
from app.core.ws_manager import manager as ws_manager

@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket, token: str = Query(...)):
    """Authenticated WebSocket for real-time chat message push."""
    from jose import jwt, JWTError
    from app.core.config import SECRET_KEY, ALGORITHM
    from app.db.session import SessionLocal
    from app.models.models import User

    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username:
            await websocket.close(code=4001)
            return
    except JWTError:
        await websocket.close(code=4001)
        return

    db = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username).first()
        if not user:
            await websocket.close(code=4001)
            return
    finally:
        db.close()

    await ws_manager.connect(user.id, websocket)
    try:
        while True:
            # Keep-alive: client sends periodic pings, we just read and discard
            await websocket.receive_text()
    except WebSocketDisconnect:
        ws_manager.disconnect(user.id, websocket)
    except Exception:
        ws_manager.disconnect(user.id, websocket)


# ── Initialization ────────────────────────────────────────────────────────────
@app.on_event("startup")
async def startup():
    # Ensure database tables exist
    try:
        from app.db.session import engine
        from app.models.models import Base
        Base.metadata.create_all(bind=engine)
    except Exception as db_err:
        logger.warning(f"DB table creation warning: {db_err}")

    # Guarantee critical columns exist before any ORM query runs.
    try:
        from app.db.session import SessionLocal
        from sqlalchemy import text
        db = SessionLocal()
        try:
            db.execute(text("ALTER TABLE videos ADD COLUMN IF NOT EXISTS cover_url VARCHAR"))
            db.execute(text("ALTER TABLE videos ADD COLUMN IF NOT EXISTS cover_source VARCHAR"))
            db.execute(text("ALTER TABLE upload_jobs ADD COLUMN IF NOT EXISTS video_type VARCHAR"))
            db.execute(text("ALTER TABLE upload_jobs ADD COLUMN IF NOT EXISTS cover_source VARCHAR"))
            db.execute(text("ALTER TABLE upload_jobs ADD COLUMN IF NOT EXISTS cover_s3_key VARCHAR"))
            db.commit()
            logger.info("Critical columns verified in DB")
        except Exception as e:
            db.rollback()
            logger.warning(f"Column guard skipped: {e}")
        finally:
            db.close()
    except Exception as e:
        logger.warning(f"DB column guard skipped: {e}")

    from app.core.config import REDIS_URL
    if REDIS_URL:
        try:
            redis = aioredis.from_url(
                REDIS_URL,
                encoding="utf8",
                decode_responses=True,
                max_connections=5,
            )
            FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
        except Exception as cache_err:
            logger.warning(f"Redis cache initialization skipped: {cache_err}")
    else:
        logger.info("REDIS_URL not set; skipping Redis cache initialization")

@app.get("/", tags=["System"])
async def root_health():
    """Default root endpoint for simple load balancer health checks."""
    return {"status": "ok", "message": "Monteeq Backend API is running"}

@app.get("/health", tags=["System"])
async def health_check():
    """Simple liveness probe used by load balancers and uptime monitors."""
    return JSONResponse(
        status_code=200,
        content={"status": "ok", "service": "monteeq-backend"},
    )