Convert web service from FastAPI to Django 6.1

Replace the FastAPI/SQLAlchemy/Alembic web service with a Django project
laid out like cumorah-build: manage.py at the root, settings in the
privatestudio.settings package (base/dev/production), and a
privatestudio.studio app.

- Studio model owns a unique bucket_name; access is granted through
  membership in the studio's auth Group. Assets, profiles and jobs are
  scoped to a studio; API keys and S3 credentials stay per user.
- JSON API via Django Ninja under /api/ (profiles and transcode jobs now
  live under /api/studios/{bucket}/).
- S3-compatible interface as plain class-based views under /s3/,
  supporting bearer tokens and AWS v4 signatures.
- create_studio and create_key management commands replace ps-serve.
- Fresh Django initial migration; tests ported to Django TestCase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shaun Kruger
2026-11-29 21:54:16 -07:00
co-authored by Claude Opus 5.5
parent 46adddd50a
commit b3b51f6cc5
60 changed files with 1776 additions and 3002 deletions
+87 -299
View File
@@ -1,24 +1,17 @@
# Private Studio - Video Transcoding Web Service
A FastAPI-based video transcoding management service with S3-compatible file uploads, API key authentication, and per-user resource isolation.
A Django video transcoding management service. It provides S3-compatible file storage, API key authentication, and studio-based access control.
## Features
- **S3-Compatible Interface**: Upload, download, delete, and list files using S3-compatible HTTP endpoints
- **API Key Authentication**: Secure bearer token authentication with per-user isolation
- **YAML-Based Transcode API**: Request transcode jobs and manage encoding profiles via YAML
- **SQLite Database**: Lightweight file-based database with SQLAlchemy ORM
- **User Management**: Create users and API keys via CLI
- **Studios**: each studio owns one S3 bucket. Members of the studio's Django group can access it.
- **S3-compatible interface**: upload, download, delete and list objects with bearer tokens or AWS v4 signatures (works with boto3).
- **JSON API** ([Django Ninja](https://django-ninja.dev/)): manage API keys, temporary S3 credentials, transcode profiles and transcode jobs. Interactive docs are at `/api/docs`.
- **Django admin** for managing users, groups, studios and jobs.
## Installation
Install the package with all dependencies:
```bash
pip install -e .
```
Or install development dependencies:
Requires Python 3.12+.
```bash
pip install -e ".[dev]"
@@ -26,329 +19,124 @@ pip install -e ".[dev]"
## Quick Start
### 1. Initialize Database
```bash
ps-serve init
python manage.py migrate
python manage.py createsuperuser
python manage.py create_studio demo --name "Demo Studio" --group demo-team --add-user <username>
python manage.py create_key <username>
python manage.py runserver
```
This creates a `transcoding.db` file in the current directory.
`create_key` prints the API key once. Keep it secret.
### 2. Create a User
To grant someone access to a studio, add them to the studio's group, either in the admin (`/admin/`) or with `create_studio --add-user` when the studio is created.
```bash
ps-serve create-user myuser
```
See [README_SERVE.md](README_SERVE.md) for the full command guide.
### 3. Create an API Key
```bash
ps-serve create-key 1
```
This outputs an API key that should be kept secret:
## Project Layout
```
API key created for user 1
Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
Keep this key safe - you won't be able to see it again!
manage.py
privatestudio/
settings/base.py # shared settings
settings/dev.py # default (DJANGO_SETTINGS_MODULE=privatestudio.settings.dev)
settings/production.py # env-driven production settings
urls.py, wsgi.py, asgi.py
studio/ # Django app: models, API routers, S3 views, management commands
transcode.py # ps-transcode CLI (ffmpeg wrapper)
```
### 4. Start the Server
```bash
ps-serve serve
```
The server will start at `http://localhost:8000`
## Configuration
Environment variables:
Settings live in the `privatestudio.settings` package. Choose one with `DJANGO_SETTINGS_MODULE`:
- `privatestudio.settings.dev` is the default. You can add overrides in an optional, git-ignored `privatestudio/settings/local.py`.
- `privatestudio.settings.production` is configured from the environment variables below.
- `DATABASE_URL`: SQLite database path (default: `./transcoding.db`)
- `STORAGE_PATH`: File storage directory (default: `./storage`)
- `SERVER_HOST`: Server host address (default: `0.0.0.0`)
- `SERVER_PORT`: Server port (default: `8000`)
- `SQL_ECHO`: Enable SQL query logging (default: `false`)
Example:
```bash
export DATABASE_URL="sqlite:///./my_transcoding.db"
export STORAGE_PATH="./media"
ps-serve serve --host 127.0.0.1 --port 8080
```
| Variable | Used by | Description |
|---|---|---|
| `STORAGE_PATH` | all | File storage root (default `<repo>/storage`) |
| `S3_CREDENTIAL_TTL_HOURS` | all | Lifetime of `/api/s3keys` credentials (default `1`) |
| `DJANGO_TIME_ZONE` | all | Time zone (default `UTC`) |
| `SECRET_KEY` | production | Django secret key |
| `ALLOWED_HOSTS` | production | Comma-separated host names |
| `DATABASE_URL` | production | Database URL parsed by `dj-database-url` (default SQLite `db.sqlite3`) |
| `CORS_ALLOWED_ORIGINS` | production | Comma-separated allowed CORS origins |
| `SECURE_PROXY_SSL_HEADER` | production | Set to trust `X-Forwarded-Proto` from a proxy |
## API Usage
### Authentication
All endpoints except `/health` need `Authorization: Bearer <API_KEY>`. The S3 endpoints also accept AWS v4 signatures made with credentials from `/api/s3keys`.
All endpoints require an API key via Bearer token:
### Account
| Method | Path | Description |
|---|---|---|
| GET | `/api/userinfo` | User id, username, and the studios (buckets) the user can access |
| POST | `/api/keys` | Create an API key |
| GET | `/api/keys` | List your API keys |
| DELETE | `/api/keys/{id}` | Revoke an API key |
| POST | `/api/s3keys` | Create temporary S3 access/secret keys |
### S3-compatible storage
| Method | Path | Description |
|---|---|---|
| PUT | `/s3/{bucket}/{key}` | Upload: either a raw body, or multipart with a `file` field |
| GET | `/s3/{bucket}/{key}` | Download |
| HEAD | `/s3/{bucket}/{key}` | Object size |
| DELETE | `/s3/{bucket}/{key}` | Delete |
| GET | `/s3/{bucket}?prefix=&delimiter=` | List objects |
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:8000/api/keys
curl -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 \
http://localhost:8000/s3/demo/videos/video.mp4
```
### S3-Compatible File Operations
With boto3 (AWS v4 signatures):
Upload a file:
```python
import boto3, requests
from botocore.config import Config
```bash
curl -X PUT \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "file=@video.mp4" \
http://localhost:8000/s3/1/videos/video.mp4
creds = requests.post("http://localhost:8000/api/s3keys",
headers={"Authorization": f"Bearer {KEY}"}).json()
s3 = boto3.client("s3", endpoint_url="http://localhost:8000/s3",
aws_access_key_id=creds["access_key"],
aws_secret_access_key=creds["secret_key"],
region_name="us-east-1",
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}))
s3.upload_file("video.mp4", "demo", "videos/video.mp4")
```
Download a file:
### Transcode profiles and jobs (per studio)
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/s3/1/videos/video.mp4 \
-o video.mp4
```
| Method | Path | Body |
|---|---|---|
| POST | `/api/studios/{bucket}/profiles?name=<name>` | YAML profile definition (must contain `profiles:`) |
| GET | `/api/studios/{bucket}/profiles` | |
| GET | `/api/studios/{bucket}/profiles/{id}` | |
| POST | `/api/studios/{bucket}/transcode` | YAML job request |
| GET | `/api/studios/{bucket}/transcode?status=pending` | |
| GET | `/api/studios/{bucket}/transcode/{id}` | |
List files:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/s3/1
```
Delete a file:
```bash
curl -X DELETE \
-H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/s3/1/videos/video.mp4
```
### Transcode Profile Management
Create a profile:
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/yaml" \
-d @profile.yaml \
http://localhost:8000/api/profiles?name=my-profile
```
Where `profile.yaml`:
The asset in a job request can be given as its key, its filename or its ID. The profile can be a profile name or an inline definition:
```yaml
profiles:
hd:
resolution: "1280x720"
bitrate: "2500k"
fps: 30
sd:
resolution: "854x480"
bitrate: "1000k"
fps: 30
asset: videos/video.mp4
profile: hd-profile
```
List profiles:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/profiles
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/yaml" \
--data-binary @job.yaml http://localhost:8000/api/studios/demo/transcode
```
### Transcode Job Requests
## Storage
Request a transcode job with a stored profile:
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/yaml" \
-d 'asset: video.mp4
profile: my-profile' \
http://localhost:8000/api/transcode
```
Or with an inline profile:
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/yaml" \
-d 'asset: video.mp4
profile:
profiles:
hd:
resolution: "1280x720"
bitrate: "2500k"' \
http://localhost:8000/api/transcode
```
Get job status:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/transcode/1
```
List jobs:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/transcode
```
List jobs by status:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/transcode?status=pending
```
### API Key Management
Create an API key:
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/keys
```
List keys:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/keys
```
Revoke a key:
```bash
curl -X DELETE \
-H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/api/keys/KEY_ID
```
Files are stored under `STORAGE_PATH/<bucket_name>/<key>`. Keys that resolve outside the bucket directory are rejected.
## Testing
Run the test suite:
```bash
pytest tests/test_web.py -v
```
## Database Schema
### Users
- `id`: Primary key
- `username`: Unique username
- `created_at`: Creation timestamp
### API Keys
- `id`: Primary key
- `key_hash`: SHA256 hash of the API key
- `user_id`: Foreign key to users
- `created_at`: Creation timestamp
- `is_active`: Whether the key is active
### Uploaded Assets
- `id`: Primary key
- `user_id`: Foreign key to users
- `filename`: Original filename
- `size`: File size in bytes
- `s3_path`: Path relative to storage root
- `upload_timestamp`: Upload time
### Transcode Profiles
- `id`: Primary key
- `user_id`: Foreign key to users
- `name`: Profile name
- `profile_definition`: YAML definition as string
- `created_at`: Creation timestamp
### Transcode Jobs
- `id`: Primary key
- `user_id`: Foreign key to users
- `asset_id`: Foreign key to uploaded_assets
- `profile_id`: Foreign key to transcode_profiles (nullable for inline profiles)
- `status`: Job status (pending, in_progress, completed, failed)
- `requested_at`: Request timestamp
- `completed_at`: Completion timestamp (nullable)
### Packaging Jobs
- `id`: Primary key
- `user_id`: Foreign key to users
- `transcode_job_id`: Foreign key to transcode_jobs
- `status`: Job status (pending, in_progress, completed, failed)
- `requested_at`: Request timestamp
- `completed_at`: Completion timestamp (nullable)
### Transcoded Assets
- `id`: Primary key
- `user_id`: Foreign key to users
- `transcode_job_id`: Foreign key to transcode_jobs
- `filename`: Output filename
- `s3_path`: Path relative to storage root
- `format`: Output format (e.g., "mp4", "audio")
- `created_at`: Creation timestamp
## Architecture
### Authentication
API keys are stored as SHA256 hashes in the database and validated via FastAPI's HTTPBearer security scheme. Each authenticated endpoint receives the user context automatically.
### Per-User Isolation
All resources (assets, profiles, jobs) are scoped to the authenticated user. Users can only access their own resources, enforced at the database query level.
### File Storage
Files are stored on disk in user-specific directories under `STORAGE_PATH`:
```
storage/
├── 1/ (user 1)
│ ├── video1.mp4
│ └── video2.mp4
└── 2/ (user 2)
└── presentation.mp4
```
Symlink traversal attacks are prevented by validating file paths.
## Development
### Enable Auto-Reload
```bash
ps-serve serve --reload
```
### View SQL Queries
```bash
export SQL_ECHO=true
ps-serve serve
```
### Run Tests
```bash
pytest tests/test_web.py -v
```
With coverage:
```bash
pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
pytest
```