14 KiB
AGENTS.md
Project Overview
MediaLore is a self-hosted media library browser for images and videos. It provides a web UI for browsing, searching, tagging, and viewing media with thumbnail previews and doom-scroll/TikTok-style consumption. All access requires authentication — users must log in before accessing any media or UI pages.
Monorepo with two independent apps:
backend/— Python FastAPI serverfrontend/— React SPA (TypeScript, Vite)
Tech Stack
| Layer | Technology |
|---|---|
| Backend | Python 3.12+, FastAPI, Uvicorn |
| Database | SQLite via SQLAlchemy (async aiosqlite), WAL mode |
| Migrations | Alembic |
| Auth | JWT (python-jose) + bcrypt password hashing |
| Thumbnails | Pillow (images), ffmpeg (videos) — generated on-demand |
| File Watch | watchdog — live filesystem monitoring |
| Frontend | React 19, TypeScript 6, Vite 8, React Router 7, TanStack Query v5 |
| Infra | Docker Compose (backend: Python 3.12-slim, frontend: Nginx Alpine) |
Directory Structure
medialore-web-app/
├── docker-compose.yml # Orchestration (backend, frontend, volumes)
├── .env.example # Environment variable template
├── .gitea/
│ └── workflows/
│ └── container-publish.yml # CI: build & push Docker images
├── backend/
│ ├── Dockerfile
│ ├── pyproject.toml # Python package config (hatchling build)
│ ├── alembic.ini
│ ├── alembic/ # DB migrations
│ │ ├── env.py
│ │ └── versions/
│ └── app/
│ ├── main.py # FastAPI app, CORS, lifespan, router registration
│ ├── config.py # Pydantic Settings (DATABASE_URL, MEDIA_ROOT, etc.)
│ ├── database.py # SQLAlchemy async engine, session, WAL pragma
│ ├── models.py # ORM models: Library, MediaItem, Tag, User, media_item_tags
│ ├── schemas.py # Pydantic request/response schemas (incl. auth)
│ ├── auth.py # bcrypt hashing, JWT create/decode, auth dependencies
│ ├── routers/
│ │ ├── auth.py # Login, token validation, user CRUD (admin)
│ │ ├── libraries.py # Library CRUD, browse, doom-scroll, scan-status, rescan
│ │ ├── media.py # Media item get, file serve, thumbnail, tag assignment
│ │ ├── tags.py # Tag CRUD, grouped by category
│ │ └── search.py # Fuzzy filename + tag search
│ └── services/
│ ├── scanner.py # Dir walk, SHA-256 hashing, moved file detection
│ ├── watcher.py # watchdog event handler (create/move/delete)
│ └── thumbnails.py # Pillow + ffmpeg thumbnail generation
└── frontend/
├── Dockerfile # Multi-stage: Node build + Nginx serve
├── nginx.conf # SPA fallback, /api proxy to backend
├── package.json
├── tsconfig.json # Root references
├── tsconfig.app.json # App TS config
├── tsconfig.node.json # Vite config TS config
├── vite.config.ts # Vite + React plugin, dev proxy /api -> localhost:8000
├── eslint.config.js # Flat config: JS + TS + React hooks + refresh
├── index.html
├── public/
│ ├── favicon.svg
│ └── icons.svg
└── src/
├── main.tsx # React entry point
├── App.tsx # Router, QueryClient, sidebar, theme, responsive layout
├── index.css # CSS custom properties for light/dark themes
├── api/
│ └── client.ts # Typed fetch wrapper; all endpoint functions
├── auth/
│ ├── AuthTypes.ts # AuthUser, AuthState interfaces, AuthContext
│ ├── AuthContext.tsx # AuthProvider component (login/logout/token mgmt)
│ └── useAuth.ts # useAuth hook
├── pages/
│ ├── LoginPage.tsx
│ ├── SearchPage.tsx
│ ├── BrowserPage.tsx
│ ├── SettingsPage.tsx
├── components/
│ ├── FileBrowser/FileBrowser.tsx
│ ├── MediaViewer/MediaViewer.tsx
│ ├── DoomScrollViewer/DoomScrollViewer.tsx
│ └── TagPanel/TagPanel.tsx
└── assets/
├── hero.png
└── vite.svg
Common Commands
Backend
# Install (from backend/)
pip install -e .
# Run dev server
cd backend && uvicorn app.main:app --reload --port 8000
# Generate a new Alembic migration
cd backend && alembic revision --autogenerate -m "description"
# Apply migrations
cd backend && alembic upgrade head
Frontend
# Install dependencies (from frontend/)
npm install
# Dev server (proxies /api to localhost:8000)
npm run dev
# Production build
npm run build
# Lint
npm run lint
# Preview production build
npm run preview
Docker
docker compose up -d
Environment Variables
| Variable | Default | Purpose |
|---|---|---|
DATABASE_URL |
sqlite+aiosqlite:////data/medialore.db |
SQLite connection string |
MEDIA_ROOT |
/media |
Root path for media libraries |
THUMBNAIL_DIR |
/data/thumbnails |
Cached thumbnail storage |
SECRET_KEY |
auto-generated | JWT signing key |
ADMIN_USERNAME |
admin |
Initial admin user |
ADMIN_PASSWORD |
(required) | Initial admin password |
ACCESS_TOKEN_EXPIRE_DAYS |
30 |
JWT token lifetime in days |
Pydantic Settings reads from .env at startup (via model_config = {"env_file": ".env"}). For Docker, these are set in docker-compose.yml.
Database
SQLite with WAL mode and a 10-second busy timeout (see app/database.py:14-18). Tables are auto-created at startup via Base.metadata.create_all in the FastAPI lifespan.
Schema
- libraries:
id,name,path(unique) - media_items:
id,library_id(FK),rel_path,filename,file_hash(SHA-256),media_type("image" or "video"),size_bytes,missing,created_at,updated_at— unique on(library_id, rel_path) - tags:
id,name,category— unique on(name, category) - media_item_tags:
media_item_id(FK),tag_id(FK), composite PK - users:
id,username(unique),password_hash,is_admin,created_at
Migrations: Use Alembic. The initial migration is at backend/alembic/versions/0001_initial_schema.py and the users table migration at 0002_add_users_table.py.
API Conventions
All endpoints are prefixed with /api. All responses are JSON except /api/media/:id/file (binary stream) and /api/media/:id/thumbnail (JPEG).
All endpoints require authentication except POST /api/auth/login. The Authorization: Bearer <token> header must be included. File and thumbnail endpoints also accept ?token= as a query parameter (for <img>/<video> tags that can't send headers).
Auth Endpoints
| Method | Path | Auth | Purpose |
|---|---|---|---|
POST |
/auth/login |
Public | Returns JWT access_token |
GET |
/auth/me |
User | Current user info |
GET |
/auth/users |
Admin | List all users |
POST |
/auth/users |
Admin | Create a new user |
DELETE |
/auth/users/{id} |
Admin | Delete a user (not self) |
Async Database Access
Routers use FastAPI's Depends injection with the get_db async generator from database.py:
from app.database import get_db
@router.get("/...")
async def endpoint(db: AsyncSession = Depends(get_db)):
...
Authentication Dependency
All protected endpoints use get_current_user (from app/auth.py) as a FastAPI dependency:
from app.auth import get_current_user
from app.models import User
@router.get("/...")
async def endpoint(
db: AsyncSession = Depends(get_db),
_user: User = Depends(get_current_user),
):
...
Admin-only endpoints chain get_current_admin_user:
from app.auth import get_current_admin_user
@router.delete("/users/{user_id}")
async def delete_user(
user_id: int,
current_user: User = Depends(get_current_admin_user),
...
):
File and thumbnail endpoints use get_current_user_from_query_or_header which accepts the token via Authorization header or ?token= query parameter.
Frontend API Client
All API calls go through the typed api object in frontend/src/api/client.ts. Use useQuery / useMutation from TanStack Query. Never call fetch directly from components.
import { api } from "../api/client";
import { useQuery } from "@tanstack/react-query";
const { data } = useQuery({
queryKey: ["libraries", id, "browse", path],
queryFn: () => api.libraries.browse(id, path),
});
Code Patterns & Conventions
Backend (Python)
- No linter configured — follow the existing style (4-space indent, snake_case)
- Models use SQLAlchemy 2.0-style
mapped_column(notColumn()) - Schemas use Pydantic
BaseModel - Service modules handle business logic; routers handle HTTP concerns
- Background scanning runs via
asyncio.create_task; watchers run in separate threads viawatchdog.Observer - Logging: use
logging.getLogger(__name__)— theappnamespace has a StreamHandler configured inmain.py - Auth: use
bcryptdirectly (not passlib) for password hashing;python-josefor JWT tokens - All protected endpoints must include
_user: User = Depends(get_current_user)as a parameter
Frontend (TypeScript/React)
- ESLint flat config with strict TypeScript-ESLint rules
- Inline
style={{ ... }}objects for CSS (no CSS modules, no Tailwind) - TypeScript interfaces for all API types live in
client.ts - Components use
useState/useEffect/useQueryhooks, not class components - Theme state persisted in
localStoragekey"theme", applied asdata-themeattribute - Auth token persisted in
localStoragekey"token", managed viaAuthProvidercontext - Responsive via
window.matchMedia("(max-width: 767px)")listener - File/thumbnail URLs constructed with
api.media.fileUrl(id)andapi.media.thumbnailUrl(id)(not fetched) - API client automatically injects
Authorization: Bearer <token>header; handles 401 by clearing token
TypeScript Configuration
tsconfig.app.json: strict mode,noUnusedLocals,noUnusedParameters,erasableSyntaxOnlytsconfig.node.json: forvite.config.tsonly- Build command:
tsc -b && vite build(type-check via project references)
Testing
There are no test files in this project. No test framework is configured. When adding tests:
- Frontend: consider Vitest (pairs with Vite) + React Testing Library
- Backend: consider pytest + pytest-asyncio + httpx (for FastAPI TestClient)
- No existing test commands in CI, so add them and consider a GitHub Action or similar
Docker / Deployment
docker compose up -dstarts both services- Images are pulled from the Gitea container registry (
git.gpatti.com/<owner>/medialore-backendand...frontend) - Backend runs on port 8000 (internal), frontend Nginx on port 80 (mapped to 8080 on host)
- Nginx proxies
/api/tohttp://backend:8000 - Media paths from the host are volume-mounted into the container at
/media - Persistent data (DB, thumbnails) stored in Docker volume
medialore-data - Set
OWNERin.envto control which registry namespace images are pulled from
CI/CD (Gitea Actions)
The workflow at .gitea/workflows/container-publish.yml automatically builds and pushes Docker images to the Gitea container registry on push to main or version tags (v*).
Required secrets (set in repo Settings → Actions → Secrets):
| Secret | Purpose |
|---|---|
REGISTRY_USER |
Gitea username for docker login |
REGISTRY_TOKEN |
Gitea PAT with read:packages and write:packages scopes |
To pull images from the private registry on a host, run docker login git.gpatti.com first with the same credentials.
Local Development (without registry)
For local development without pulling from the registry, switch docker-compose.yml back to local builds:
services:
backend:
build: ./backend # instead of image: ...
frontend:
build: ./frontend # instead of image: ...
Important Notes
- Authentication is required for all endpoints and UI pages except
/api/auth/login. JWT tokens are signed withSECRET_KEY(auto-generated if unset, so set it for persistent sessions). File/thumbnail endpoints also accept?token=as a query parameter since<img>/<video>tags can't send headers. - Thumbnails are generated on first request and cached to disk (
THUMBNAIL_DIR) - The scanner computes SHA-256 hashes to detect moved/renamed files and avoid re-processing
- File watcher uses watchdog with per-library
PollingObserver(necessary for Docker volumes) media_items.missingflag is set when a scanned file no longer exists on disk- The frontend
buildcommand runstsc -bfirst, which checks types across project references — type errors will block the build - Admin user is created automatically on first startup from
ADMIN_USERNAME/ADMIN_PASSWORDenv vars; additional users can be created via the Settings page by an admin