Implement Bellhop: Matrix-authenticated *arr request portal
- FastAPI backend with async SQLite session storage - Matrix homeserver authentication (login/logout/session validation via whoami) - Server-side proxy for Radarr, Sonarr, and Lidarr search & add APIs - Fire-and-forget Matrix audit log bot for request tracking - Rate-limited login endpoint (5 req/min per IP via slowapi) - Single-page Alpine.js frontend with dark theme, media type tabs, search grid - Dockerfile for single-container deployment - Secure session cookies (httponly, samesite=strict, secure) https://claude.ai/code/session_018iMt5qm4j9bk8wzytLC3E6
This commit is contained in:
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
||||
.git
|
||||
__pycache__
|
||||
*.pyc
|
||||
.env
|
||||
bellhop.db
|
||||
29
.env.example
Normal file
29
.env.example
Normal file
@@ -0,0 +1,29 @@
|
||||
# Matrix homeserver
|
||||
MATRIX_HOMESERVER_URL=https://matrix.example.com
|
||||
|
||||
# Matrix audit bot (pre-authenticated)
|
||||
MATRIX_AUDIT_ROOM_ID=!roomid:example.com
|
||||
MATRIX_BOT_USER_ID=@bot:example.com
|
||||
MATRIX_BOT_ACCESS_TOKEN=syt_bot_token_here
|
||||
|
||||
# Radarr
|
||||
RADARR_URL=https://radarr.example.com
|
||||
RADARR_API_KEY=your_radarr_api_key
|
||||
RADARR_QUALITY_PROFILE_ID=1
|
||||
RADARR_ROOT_FOLDER=/movies
|
||||
|
||||
# Sonarr
|
||||
SONARR_URL=https://sonarr.example.com
|
||||
SONARR_API_KEY=your_sonarr_api_key
|
||||
SONARR_QUALITY_PROFILE_ID=1
|
||||
SONARR_ROOT_FOLDER=/tv
|
||||
|
||||
# Lidarr
|
||||
LIDARR_URL=https://lidarr.example.com
|
||||
LIDARR_API_KEY=your_lidarr_api_key
|
||||
LIDARR_QUALITY_PROFILE_ID=1
|
||||
LIDARR_ROOT_FOLDER=/music
|
||||
|
||||
# App
|
||||
SESSION_SECRET_KEY=change-me-to-a-random-secret
|
||||
DATABASE_PATH=bellhop.db
|
||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.env
|
||||
bellhop.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
12
Dockerfile
Normal file
12
Dockerfile
Normal file
@@ -0,0 +1,12 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
234
app/arr.py
Normal file
234
app/arr.py
Normal file
@@ -0,0 +1,234 @@
|
||||
"""Proxy layer for Radarr, Sonarr, and Lidarr APIs."""
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.auth import require_session
|
||||
from app.audit import send_audit_message
|
||||
from app.config import (
|
||||
LIDARR_API_KEY,
|
||||
LIDARR_QUALITY_PROFILE_ID,
|
||||
LIDARR_ROOT_FOLDER,
|
||||
LIDARR_URL,
|
||||
RADARR_API_KEY,
|
||||
RADARR_QUALITY_PROFILE_ID,
|
||||
RADARR_ROOT_FOLDER,
|
||||
RADARR_URL,
|
||||
SONARR_API_KEY,
|
||||
SONARR_QUALITY_PROFILE_ID,
|
||||
SONARR_ROOT_FOLDER,
|
||||
SONARR_URL,
|
||||
)
|
||||
|
||||
router = APIRouter(tags=["arr"])
|
||||
|
||||
SERVICE_CONFIG = {
|
||||
"movie": {
|
||||
"url": RADARR_URL,
|
||||
"api_key": RADARR_API_KEY,
|
||||
"quality_profile_id": RADARR_QUALITY_PROFILE_ID,
|
||||
"root_folder": RADARR_ROOT_FOLDER,
|
||||
"lookup_path": "/api/v3/movie/lookup",
|
||||
"add_path": "/api/v3/movie",
|
||||
"label": "Movie",
|
||||
},
|
||||
"tv": {
|
||||
"url": SONARR_URL,
|
||||
"api_key": SONARR_API_KEY,
|
||||
"quality_profile_id": SONARR_QUALITY_PROFILE_ID,
|
||||
"root_folder": SONARR_ROOT_FOLDER,
|
||||
"lookup_path": "/api/v3/series/lookup",
|
||||
"add_path": "/api/v3/series",
|
||||
"label": "Show",
|
||||
},
|
||||
"music": {
|
||||
"url": LIDARR_URL,
|
||||
"api_key": LIDARR_API_KEY,
|
||||
"quality_profile_id": LIDARR_QUALITY_PROFILE_ID,
|
||||
"root_folder": LIDARR_ROOT_FOLDER,
|
||||
"lookup_path": "/api/v1/artist/lookup",
|
||||
"add_path": "/api/v1/artist",
|
||||
"label": "Artist",
|
||||
},
|
||||
}
|
||||
|
||||
VALID_TYPES = set(SERVICE_CONFIG.keys())
|
||||
|
||||
|
||||
def _headers(api_key: str) -> dict[str, str]:
|
||||
return {"X-Api-Key": api_key}
|
||||
|
||||
|
||||
def _safe_result_movie(item: dict) -> dict:
|
||||
return {
|
||||
"title": item.get("title", ""),
|
||||
"year": item.get("year"),
|
||||
"tmdbId": item.get("tmdbId"),
|
||||
"overview": item.get("overview", ""),
|
||||
"remotePoster": item.get("remotePoster", ""),
|
||||
"hasFile": item.get("hasFile", False),
|
||||
}
|
||||
|
||||
|
||||
def _safe_result_tv(item: dict) -> dict:
|
||||
return {
|
||||
"title": item.get("title", ""),
|
||||
"year": item.get("year"),
|
||||
"tvdbId": item.get("tvdbId"),
|
||||
"overview": item.get("overview", ""),
|
||||
"remotePoster": item.get("remotePoster", ""),
|
||||
"statistics": item.get("statistics", {}),
|
||||
}
|
||||
|
||||
|
||||
def _safe_result_music(item: dict) -> dict:
|
||||
return {
|
||||
"artistName": item.get("artistName", ""),
|
||||
"foreignArtistId": item.get("foreignArtistId", ""),
|
||||
"overview": item.get("overview", ""),
|
||||
"remotePoster": (item.get("images") or [{}])[0].get("remoteUrl", "") if item.get("images") else "",
|
||||
}
|
||||
|
||||
|
||||
SAFE_MAPPERS = {
|
||||
"movie": _safe_result_movie,
|
||||
"tv": _safe_result_tv,
|
||||
"music": _safe_result_music,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/search/{media_type}")
|
||||
async def search(media_type: str, term: str, request: Request) -> JSONResponse:
|
||||
session = await require_session(request)
|
||||
if not session:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
if media_type not in VALID_TYPES:
|
||||
return JSONResponse({"error": f"Invalid type. Must be one of: {', '.join(VALID_TYPES)}"}, status_code=400)
|
||||
|
||||
if not term or not term.strip():
|
||||
return JSONResponse({"error": "Search term is required"}, status_code=400)
|
||||
|
||||
cfg = SERVICE_CONFIG[media_type]
|
||||
if not cfg["url"] or not cfg["api_key"]:
|
||||
return JSONResponse({"error": f"{cfg['label']} service is not configured"}, status_code=503)
|
||||
|
||||
lookup_url = f"{cfg['url'].rstrip('/')}{cfg['lookup_path']}"
|
||||
params = {"term": term.strip()}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
lookup_url,
|
||||
params=params,
|
||||
headers=_headers(cfg["api_key"]),
|
||||
timeout=15.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
return JSONResponse({"error": f"Could not reach {cfg['label']} service"}, status_code=502)
|
||||
|
||||
if resp.status_code != 200:
|
||||
return JSONResponse({"error": f"{cfg['label']} lookup failed"}, status_code=resp.status_code)
|
||||
|
||||
results = resp.json()
|
||||
mapper = SAFE_MAPPERS[media_type]
|
||||
safe_results = [mapper(item) for item in results[:25]]
|
||||
|
||||
return JSONResponse(safe_results)
|
||||
|
||||
|
||||
@router.post("/request/{media_type}")
|
||||
async def add_request(media_type: str, request: Request) -> JSONResponse:
|
||||
session = await require_session(request)
|
||||
if not session:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
if media_type not in VALID_TYPES:
|
||||
return JSONResponse({"error": f"Invalid type. Must be one of: {', '.join(VALID_TYPES)}"}, status_code=400)
|
||||
|
||||
body = await request.json()
|
||||
cfg = SERVICE_CONFIG[media_type]
|
||||
|
||||
if not cfg["url"] or not cfg["api_key"]:
|
||||
return JSONResponse({"error": f"{cfg['label']} service is not configured"}, status_code=503)
|
||||
|
||||
add_url = f"{cfg['url'].rstrip('/')}{cfg['add_path']}"
|
||||
|
||||
if media_type == "movie":
|
||||
payload = _build_movie_payload(body, cfg)
|
||||
title_display = f"\"{body.get('title', 'Unknown')}\" ({body.get('year', '?')})"
|
||||
elif media_type == "tv":
|
||||
payload = _build_tv_payload(body, cfg)
|
||||
title_display = f"\"{body.get('title', 'Unknown')}\" ({body.get('year', '?')})"
|
||||
else:
|
||||
payload = _build_music_payload(body, cfg)
|
||||
title_display = f"\"{body.get('artistName', 'Unknown')}\" ({body.get('foreignArtistId', '?')})"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.post(
|
||||
add_url,
|
||||
json=payload,
|
||||
headers=_headers(cfg["api_key"]),
|
||||
timeout=15.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
return JSONResponse({"error": f"Could not reach {cfg['label']} service"}, status_code=502)
|
||||
|
||||
if resp.status_code not in (200, 201):
|
||||
error_detail = ""
|
||||
try:
|
||||
error_body = resp.json()
|
||||
if isinstance(error_body, list):
|
||||
error_detail = "; ".join(e.get("errorMessage", "") for e in error_body if e.get("errorMessage"))
|
||||
elif isinstance(error_body, dict):
|
||||
error_detail = error_body.get("message", "") or error_body.get("errorMessage", "")
|
||||
except Exception:
|
||||
pass
|
||||
msg = f"Failed to add to {cfg['label']}"
|
||||
if error_detail:
|
||||
msg += f": {error_detail}"
|
||||
return JSONResponse({"error": msg}, status_code=resp.status_code)
|
||||
|
||||
# Fire-and-forget audit message
|
||||
user_id = session["matrix_user_id"]
|
||||
audit_msg = f"[REQUEST] {user_id} → [{cfg['label']}] {title_display}"
|
||||
send_audit_message(audit_msg)
|
||||
|
||||
return JSONResponse({"ok": True, "message": f"{cfg['label']} added successfully"})
|
||||
|
||||
|
||||
def _build_movie_payload(body: dict, cfg: dict) -> dict:
|
||||
return {
|
||||
"title": body.get("title", ""),
|
||||
"tmdbId": body.get("tmdbId"),
|
||||
"year": body.get("year"),
|
||||
"qualityProfileId": cfg["quality_profile_id"],
|
||||
"rootFolderPath": cfg["root_folder"],
|
||||
"monitored": True,
|
||||
"addOptions": {"searchForMovie": True},
|
||||
}
|
||||
|
||||
|
||||
def _build_tv_payload(body: dict, cfg: dict) -> dict:
|
||||
return {
|
||||
"title": body.get("title", ""),
|
||||
"tvdbId": body.get("tvdbId"),
|
||||
"year": body.get("year"),
|
||||
"qualityProfileId": cfg["quality_profile_id"],
|
||||
"rootFolderPath": cfg["root_folder"],
|
||||
"monitored": True,
|
||||
"addOptions": {"searchForMissingEpisodes": True},
|
||||
}
|
||||
|
||||
|
||||
def _build_music_payload(body: dict, cfg: dict) -> dict:
|
||||
return {
|
||||
"artistName": body.get("artistName", ""),
|
||||
"foreignArtistId": body.get("foreignArtistId", ""),
|
||||
"qualityProfileId": cfg["quality_profile_id"],
|
||||
"rootFolderPath": cfg["root_folder"],
|
||||
"monitored": True,
|
||||
"addOptions": {"searchForMissingAlbums": True},
|
||||
}
|
||||
51
app/audit.py
Normal file
51
app/audit.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""Matrix audit log — fire-and-forget messages to an unencrypted room."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import (
|
||||
MATRIX_AUDIT_ROOM_ID,
|
||||
MATRIX_BOT_ACCESS_TOKEN,
|
||||
MATRIX_HOMESERVER_URL,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def send_audit_message(message: str) -> None:
|
||||
"""Schedule an audit message to be sent without blocking the caller."""
|
||||
if not MATRIX_AUDIT_ROOM_ID or not MATRIX_BOT_ACCESS_TOKEN:
|
||||
logger.debug("Audit log not configured, skipping")
|
||||
return
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
return
|
||||
|
||||
loop.create_task(_send(message))
|
||||
|
||||
|
||||
async def _send(message: str) -> None:
|
||||
import time
|
||||
|
||||
room_id = MATRIX_AUDIT_ROOM_ID
|
||||
txn_id = str(int(time.time() * 1000))
|
||||
|
||||
url = (
|
||||
f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/rooms/"
|
||||
f"{room_id}/send/m.room.message/{txn_id}"
|
||||
)
|
||||
body = {
|
||||
"msgtype": "m.text",
|
||||
"body": message,
|
||||
}
|
||||
headers = {"Authorization": f"Bearer {MATRIX_BOT_ACCESS_TOKEN}"}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
await client.put(url, json=body, headers=headers, timeout=10.0)
|
||||
except Exception:
|
||||
logger.warning("Failed to send audit message: %s", message, exc_info=True)
|
||||
131
app/auth.py
Normal file
131
app/auth.py
Normal file
@@ -0,0 +1,131 @@
|
||||
import httpx
|
||||
from fastapi import APIRouter, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.config import MATRIX_HOMESERVER_URL
|
||||
from app.database import create_session, delete_session, get_session
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
SESSION_COOKIE = "bellhop_session"
|
||||
MAX_SESSION_AGE = 60 * 60 * 24 * 7 # 7 days
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(request: Request) -> Response:
|
||||
body = await request.json()
|
||||
username: str = body.get("username", "").strip()
|
||||
password: str = body.get("password", "")
|
||||
|
||||
if not username or not password:
|
||||
return JSONResponse({"error": "Username and password are required"}, status_code=400)
|
||||
|
||||
# Build the Matrix user identifier
|
||||
if username.startswith("@"):
|
||||
user_identifier = username
|
||||
else:
|
||||
user_identifier = username # let the homeserver resolve it
|
||||
|
||||
login_url = f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/login"
|
||||
payload = {
|
||||
"type": "m.login.password",
|
||||
"identifier": {"type": "m.id.user", "user": user_identifier},
|
||||
"password": password,
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.post(login_url, json=payload, timeout=15.0)
|
||||
except httpx.RequestError:
|
||||
return JSONResponse({"error": "Could not reach Matrix homeserver"}, status_code=502)
|
||||
|
||||
if resp.status_code != 200:
|
||||
error_msg = resp.json().get("error", "Authentication failed")
|
||||
return JSONResponse({"error": error_msg}, status_code=401)
|
||||
|
||||
data = resp.json()
|
||||
matrix_user_id: str = data["user_id"]
|
||||
matrix_access_token: str = data["access_token"]
|
||||
|
||||
session_id = await create_session(matrix_user_id, matrix_access_token)
|
||||
|
||||
response = JSONResponse({"user_id": matrix_user_id})
|
||||
response.set_cookie(
|
||||
key=SESSION_COOKIE,
|
||||
value=session_id,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=True,
|
||||
max_age=MAX_SESSION_AGE,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(request: Request) -> Response:
|
||||
session_id = request.cookies.get(SESSION_COOKIE)
|
||||
if session_id:
|
||||
await delete_session(session_id)
|
||||
response = JSONResponse({"ok": True})
|
||||
response.delete_cookie(key=SESSION_COOKIE)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(request: Request) -> Response:
|
||||
session_id = request.cookies.get(SESSION_COOKIE)
|
||||
if not session_id:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
session = await get_session(session_id)
|
||||
if not session:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
# Verify token is still valid with the homeserver
|
||||
whoami_url = f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/account/whoami"
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
whoami_url,
|
||||
headers={"Authorization": f"Bearer {session['matrix_access_token']}"},
|
||||
timeout=10.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
# If homeserver is unreachable, trust the local session
|
||||
return JSONResponse({"user_id": session["matrix_user_id"]})
|
||||
|
||||
if resp.status_code != 200:
|
||||
await delete_session(session_id)
|
||||
response = JSONResponse({"error": "Session expired"}, status_code=401)
|
||||
response.delete_cookie(key=SESSION_COOKIE)
|
||||
return response
|
||||
|
||||
return JSONResponse({"user_id": session["matrix_user_id"]})
|
||||
|
||||
|
||||
async def require_session(request: Request) -> dict | None:
|
||||
"""Utility: extract and validate session from a request. Returns session dict or None."""
|
||||
session_id = request.cookies.get(SESSION_COOKIE)
|
||||
if not session_id:
|
||||
return None
|
||||
session = await get_session(session_id)
|
||||
if not session:
|
||||
return None
|
||||
|
||||
# Verify token is still valid
|
||||
whoami_url = f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/account/whoami"
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
whoami_url,
|
||||
headers={"Authorization": f"Bearer {session['matrix_access_token']}"},
|
||||
timeout=10.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
return session # trust local session if homeserver unreachable
|
||||
|
||||
if resp.status_code != 200:
|
||||
await delete_session(session_id)
|
||||
return None
|
||||
|
||||
return session
|
||||
42
app/config.py
Normal file
42
app/config.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def _require(name: str) -> str:
|
||||
val = os.getenv(name)
|
||||
if not val:
|
||||
raise RuntimeError(f"Missing required environment variable: {name}")
|
||||
return val
|
||||
|
||||
|
||||
# Matrix
|
||||
MATRIX_HOMESERVER_URL: str = _require("MATRIX_HOMESERVER_URL")
|
||||
MATRIX_AUDIT_ROOM_ID: str = os.getenv("MATRIX_AUDIT_ROOM_ID", "")
|
||||
MATRIX_BOT_USER_ID: str = os.getenv("MATRIX_BOT_USER_ID", "")
|
||||
MATRIX_BOT_ACCESS_TOKEN: str = os.getenv("MATRIX_BOT_ACCESS_TOKEN", "")
|
||||
|
||||
# Radarr
|
||||
RADARR_URL: str = os.getenv("RADARR_URL", "")
|
||||
RADARR_API_KEY: str = os.getenv("RADARR_API_KEY", "")
|
||||
RADARR_QUALITY_PROFILE_ID: int = int(os.getenv("RADARR_QUALITY_PROFILE_ID", "1"))
|
||||
RADARR_ROOT_FOLDER: str = os.getenv("RADARR_ROOT_FOLDER", "/movies")
|
||||
|
||||
# Sonarr
|
||||
SONARR_URL: str = os.getenv("SONARR_URL", "")
|
||||
SONARR_API_KEY: str = os.getenv("SONARR_API_KEY", "")
|
||||
SONARR_QUALITY_PROFILE_ID: int = int(os.getenv("SONARR_QUALITY_PROFILE_ID", "1"))
|
||||
SONARR_ROOT_FOLDER: str = os.getenv("SONARR_ROOT_FOLDER", "/tv")
|
||||
|
||||
# Lidarr
|
||||
LIDARR_URL: str = os.getenv("LIDARR_URL", "")
|
||||
LIDARR_API_KEY: str = os.getenv("LIDARR_API_KEY", "")
|
||||
LIDARR_QUALITY_PROFILE_ID: int = int(os.getenv("LIDARR_QUALITY_PROFILE_ID", "1"))
|
||||
LIDARR_ROOT_FOLDER: str = os.getenv("LIDARR_ROOT_FOLDER", "/music")
|
||||
|
||||
# App
|
||||
SESSION_SECRET_KEY: str = _require("SESSION_SECRET_KEY")
|
||||
DATABASE_PATH: str = os.getenv("DATABASE_PATH", "bellhop.db")
|
||||
73
app/database.py
Normal file
73
app/database.py
Normal file
@@ -0,0 +1,73 @@
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import aiosqlite
|
||||
|
||||
from app.config import DATABASE_PATH
|
||||
|
||||
_db: aiosqlite.Connection | None = None
|
||||
|
||||
|
||||
async def get_db() -> aiosqlite.Connection:
|
||||
global _db
|
||||
if _db is None:
|
||||
_db = await aiosqlite.connect(DATABASE_PATH)
|
||||
_db.row_factory = aiosqlite.Row
|
||||
await _db.execute("PRAGMA journal_mode=WAL")
|
||||
await _db.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
matrix_user_id TEXT NOT NULL,
|
||||
matrix_access_token TEXT NOT NULL,
|
||||
created_at REAL NOT NULL,
|
||||
last_seen REAL NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
await _db.commit()
|
||||
return _db
|
||||
|
||||
|
||||
async def close_db() -> None:
|
||||
global _db
|
||||
if _db is not None:
|
||||
await _db.close()
|
||||
_db = None
|
||||
|
||||
|
||||
async def create_session(matrix_user_id: str, matrix_access_token: str) -> str:
|
||||
db = await get_db()
|
||||
session_id = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
await db.execute(
|
||||
"INSERT INTO sessions (session_id, matrix_user_id, matrix_access_token, created_at, last_seen) "
|
||||
"VALUES (?, ?, ?, ?, ?)",
|
||||
(session_id, matrix_user_id, matrix_access_token, now, now),
|
||||
)
|
||||
await db.commit()
|
||||
return session_id
|
||||
|
||||
|
||||
async def get_session(session_id: str) -> dict | None:
|
||||
db = await get_db()
|
||||
cursor = await db.execute(
|
||||
"SELECT session_id, matrix_user_id, matrix_access_token, created_at, last_seen "
|
||||
"FROM sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
await db.execute(
|
||||
"UPDATE sessions SET last_seen = ? WHERE session_id = ?",
|
||||
(time.time(), session_id),
|
||||
)
|
||||
await db.commit()
|
||||
return dict(row)
|
||||
|
||||
|
||||
async def delete_session(session_id: str) -> None:
|
||||
db = await get_db()
|
||||
await db.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
|
||||
await db.commit()
|
||||
48
app/main.py
Normal file
48
app/main.py
Normal file
@@ -0,0 +1,48 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from slowapi import Limiter, _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
from slowapi.util import get_remote_address
|
||||
|
||||
from app.auth import router as auth_router
|
||||
from app.arr import router as arr_router
|
||||
from app.database import close_db, get_db
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await get_db()
|
||||
yield
|
||||
await close_db()
|
||||
|
||||
|
||||
app = FastAPI(title="Bellhop", lifespan=lifespan)
|
||||
app.state.limiter = limiter
|
||||
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
||||
|
||||
# Mount static files
|
||||
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
|
||||
|
||||
# Apply rate limit to login specifically
|
||||
original_login = auth_router.routes
|
||||
for route in auth_router.routes:
|
||||
if hasattr(route, "path") and route.path == "/login" and hasattr(route, "endpoint"):
|
||||
route.endpoint = limiter.limit("5/minute")(route.endpoint)
|
||||
break
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(arr_router)
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index():
|
||||
html_path = BASE_DIR / "templates" / "index.html"
|
||||
return HTMLResponse(html_path.read_text())
|
||||
0
app/static/.gitkeep
Normal file
0
app/static/.gitkeep
Normal file
355
app/templates/index.html
Normal file
355
app/templates/index.html
Normal file
@@ -0,0 +1,355 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Bellhop</title>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f0f0f;
|
||||
--surface: #1a1a2e;
|
||||
--surface2: #16213e;
|
||||
--primary: #e94560;
|
||||
--primary-hover: #c73650;
|
||||
--text: #eee;
|
||||
--text-muted: #999;
|
||||
--border: #333;
|
||||
--success: #2ecc71;
|
||||
--error: #e74c3c;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
.container { max-width: 960px; margin: 0 auto; padding: 1.5rem; }
|
||||
header {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
padding: 1rem 0; border-bottom: 1px solid var(--border); margin-bottom: 1.5rem;
|
||||
}
|
||||
header h1 { font-size: 1.5rem; letter-spacing: 0.05em; }
|
||||
header h1 span { color: var(--primary); }
|
||||
.btn {
|
||||
padding: 0.5rem 1rem; border: none; border-radius: 6px;
|
||||
cursor: pointer; font-size: 0.9rem; font-weight: 500;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
.btn-primary:hover { background: var(--primary-hover); }
|
||||
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.btn-ghost {
|
||||
background: transparent; color: var(--text-muted); border: 1px solid var(--border);
|
||||
}
|
||||
.btn-ghost:hover { color: var(--text); border-color: var(--text-muted); }
|
||||
.btn-sm { padding: 0.35rem 0.75rem; font-size: 0.8rem; }
|
||||
|
||||
/* Login */
|
||||
.login-card {
|
||||
max-width: 380px; margin: 4rem auto; background: var(--surface);
|
||||
border-radius: 12px; padding: 2rem;
|
||||
}
|
||||
.login-card h2 { margin-bottom: 0.25rem; }
|
||||
.login-card p { color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.5rem; }
|
||||
.form-group { margin-bottom: 1rem; }
|
||||
.form-group label { display: block; font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.3rem; }
|
||||
.form-group input {
|
||||
width: 100%; padding: 0.6rem 0.75rem; background: var(--bg);
|
||||
border: 1px solid var(--border); border-radius: 6px; color: var(--text);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.form-group input:focus { outline: none; border-color: var(--primary); }
|
||||
.error-msg { color: var(--error); font-size: 0.85rem; margin-bottom: 0.75rem; }
|
||||
|
||||
/* Search bar */
|
||||
.search-bar {
|
||||
display: flex; gap: 0.5rem; margin-bottom: 1.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.media-tabs { display: flex; gap: 0.25rem; margin-bottom: 1rem; }
|
||||
.media-tab {
|
||||
padding: 0.4rem 1rem; background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 6px; cursor: pointer; color: var(--text-muted); font-size: 0.85rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.media-tab.active { background: var(--primary); color: #fff; border-color: var(--primary); }
|
||||
.search-input {
|
||||
flex: 1; min-width: 200px; padding: 0.6rem 0.75rem; background: var(--surface);
|
||||
border: 1px solid var(--border); border-radius: 6px; color: var(--text); font-size: 0.95rem;
|
||||
}
|
||||
.search-input:focus { outline: none; border-color: var(--primary); }
|
||||
|
||||
/* Results grid */
|
||||
.results-grid {
|
||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
.result-card {
|
||||
background: var(--surface); border-radius: 10px; overflow: hidden;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.result-card:hover { transform: translateY(-2px); }
|
||||
.result-card img {
|
||||
width: 100%; aspect-ratio: 2/3; object-fit: cover; background: var(--surface2);
|
||||
}
|
||||
.result-card .info { padding: 0.75rem; }
|
||||
.result-card .title { font-size: 0.9rem; font-weight: 600; margin-bottom: 0.15rem; }
|
||||
.result-card .year { font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.5rem; }
|
||||
.result-card .btn { width: 100%; }
|
||||
|
||||
/* Feedback */
|
||||
.toast {
|
||||
position: fixed; bottom: 1.5rem; right: 1.5rem;
|
||||
padding: 0.75rem 1.25rem; border-radius: 8px;
|
||||
font-size: 0.9rem; color: #fff; z-index: 100;
|
||||
animation: slideIn 0.3s ease;
|
||||
}
|
||||
.toast.success { background: var(--success); }
|
||||
.toast.error { background: var(--error); }
|
||||
@keyframes slideIn {
|
||||
from { transform: translateY(1rem); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.spinner { display: inline-block; width: 1em; height: 1em; border: 2px solid #fff3;
|
||||
border-top-color: #fff; border-radius: 50%; animation: spin 0.6s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.placeholder {
|
||||
text-align: center; padding: 3rem 1rem; color: var(--text-muted);
|
||||
}
|
||||
.no-poster {
|
||||
width: 100%; aspect-ratio: 2/3; background: var(--surface2);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: var(--text-muted); font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" x-data="bellhop()">
|
||||
|
||||
<!-- Toast -->
|
||||
<template x-if="toast.show">
|
||||
<div class="toast" :class="toast.type" x-text="toast.message"
|
||||
x-init="setTimeout(() => toast.show = false, 3000)"></div>
|
||||
</template>
|
||||
|
||||
<!-- Logged-out view -->
|
||||
<template x-if="!user">
|
||||
<div class="login-card">
|
||||
<h2>Bellhop</h2>
|
||||
<p>Sign in with your Matrix account to request media.</p>
|
||||
<div x-show="loginError" class="error-msg" x-text="loginError"></div>
|
||||
<form @submit.prevent="login">
|
||||
<div class="form-group">
|
||||
<label for="username">Matrix username</label>
|
||||
<input id="username" type="text" x-model="loginForm.username"
|
||||
placeholder="@user:example.com" required autocomplete="username">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" x-model="loginForm.password"
|
||||
required autocomplete="current-password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" style="width:100%;margin-top:0.5rem"
|
||||
:disabled="loggingIn">
|
||||
<span x-show="!loggingIn">Sign in</span>
|
||||
<span x-show="loggingIn"><span class="spinner"></span></span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Logged-in view -->
|
||||
<template x-if="user">
|
||||
<div>
|
||||
<header>
|
||||
<h1><span>Bellhop</span></h1>
|
||||
<div style="display:flex;align-items:center;gap:0.75rem">
|
||||
<span style="font-size:0.85rem;color:var(--text-muted)" x-text="user"></span>
|
||||
<button class="btn btn-ghost btn-sm" @click="logout">Sign out</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Media type tabs -->
|
||||
<div class="media-tabs">
|
||||
<template x-for="t in mediaTypes" :key="t.value">
|
||||
<button class="media-tab" :class="mediaType === t.value && 'active'"
|
||||
@click="mediaType = t.value" x-text="t.label"></button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Search -->
|
||||
<div class="search-bar">
|
||||
<input class="search-input" type="text" x-model="searchTerm"
|
||||
@keydown.enter="search" placeholder="Search for a title...">
|
||||
<button class="btn btn-primary" @click="search" :disabled="searching">
|
||||
<span x-show="!searching">Search</span>
|
||||
<span x-show="searching"><span class="spinner"></span></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Results -->
|
||||
<div x-show="results.length > 0" class="results-grid">
|
||||
<template x-for="(item, idx) in results" :key="idx">
|
||||
<div class="result-card">
|
||||
<template x-if="posterUrl(item)">
|
||||
<img :src="posterUrl(item)" :alt="itemTitle(item)" loading="lazy">
|
||||
</template>
|
||||
<template x-if="!posterUrl(item)">
|
||||
<div class="no-poster">No image</div>
|
||||
</template>
|
||||
<div class="info">
|
||||
<div class="title" x-text="itemTitle(item)"></div>
|
||||
<div class="year" x-text="itemSubtitle(item)"></div>
|
||||
<button class="btn btn-primary btn-sm"
|
||||
@click="requestItem(item)" :disabled="item._requesting">
|
||||
<span x-show="!item._requesting">Request</span>
|
||||
<span x-show="item._requesting"><span class="spinner"></span></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div x-show="searched && results.length === 0" class="placeholder">
|
||||
No results found. Try a different search.
|
||||
</div>
|
||||
<div x-show="!searched && results.length === 0" class="placeholder">
|
||||
Select a media type and search for something to request.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function bellhop() {
|
||||
return {
|
||||
user: null,
|
||||
loginForm: { username: '', password: '' },
|
||||
loginError: '',
|
||||
loggingIn: false,
|
||||
mediaType: 'movie',
|
||||
mediaTypes: [
|
||||
{ value: 'movie', label: 'Movie' },
|
||||
{ value: 'tv', label: 'TV Show' },
|
||||
{ value: 'music', label: 'Music' },
|
||||
],
|
||||
searchTerm: '',
|
||||
results: [],
|
||||
searched: false,
|
||||
searching: false,
|
||||
toast: { show: false, type: 'success', message: '' },
|
||||
|
||||
async init() {
|
||||
try {
|
||||
const res = await fetch('/auth/me');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
this.user = data.user_id;
|
||||
}
|
||||
} catch {}
|
||||
},
|
||||
|
||||
async login() {
|
||||
this.loginError = '';
|
||||
this.loggingIn = true;
|
||||
try {
|
||||
const res = await fetch('/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: this.loginForm.username,
|
||||
password: this.loginForm.password,
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
this.user = data.user_id;
|
||||
this.loginForm = { username: '', password: '' };
|
||||
} else {
|
||||
this.loginError = data.error || 'Login failed';
|
||||
}
|
||||
} catch {
|
||||
this.loginError = 'Network error';
|
||||
} finally {
|
||||
this.loggingIn = false;
|
||||
}
|
||||
},
|
||||
|
||||
async logout() {
|
||||
try { await fetch('/auth/logout', { method: 'POST' }); } catch {}
|
||||
this.user = null;
|
||||
this.results = [];
|
||||
this.searched = false;
|
||||
},
|
||||
|
||||
async search() {
|
||||
if (!this.searchTerm.trim()) return;
|
||||
this.searching = true;
|
||||
this.results = [];
|
||||
this.searched = false;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/search/${this.mediaType}?term=${encodeURIComponent(this.searchTerm)}`
|
||||
);
|
||||
if (res.ok) {
|
||||
this.results = (await res.json()).map(r => ({ ...r, _requesting: false }));
|
||||
} else {
|
||||
const d = await res.json();
|
||||
this.showToast('error', d.error || 'Search failed');
|
||||
}
|
||||
} catch {
|
||||
this.showToast('error', 'Network error');
|
||||
} finally {
|
||||
this.searching = true; // keep spinner briefly
|
||||
this.searched = true;
|
||||
this.searching = false;
|
||||
}
|
||||
},
|
||||
|
||||
async requestItem(item) {
|
||||
item._requesting = true;
|
||||
try {
|
||||
const res = await fetch(`/request/${this.mediaType}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(item),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
this.showToast('success', data.message || 'Requested!');
|
||||
} else {
|
||||
this.showToast('error', data.error || 'Request failed');
|
||||
}
|
||||
} catch {
|
||||
this.showToast('error', 'Network error');
|
||||
} finally {
|
||||
item._requesting = false;
|
||||
}
|
||||
},
|
||||
|
||||
posterUrl(item) {
|
||||
return item.remotePoster || '';
|
||||
},
|
||||
|
||||
itemTitle(item) {
|
||||
return item.title || item.artistName || '—';
|
||||
},
|
||||
|
||||
itemSubtitle(item) {
|
||||
if (item.year) return String(item.year);
|
||||
if (item.foreignArtistId) return item.foreignArtistId;
|
||||
return '';
|
||||
},
|
||||
|
||||
showToast(type, message) {
|
||||
this.toast = { show: true, type, message };
|
||||
setTimeout(() => { this.toast.show = false; }, 3000);
|
||||
},
|
||||
};
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
9
requirements.txt
Normal file
9
requirements.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
httpx==0.28.1
|
||||
aiosqlite==0.20.0
|
||||
python-dotenv==1.0.1
|
||||
matrix-nio==0.24.0
|
||||
slowapi==0.1.9
|
||||
jinja2==3.1.5
|
||||
itsdangerous==2.2.0
|
||||
Reference in New Issue
Block a user