Files
privatestudio/README.md
T
Shaun KrugerandClaude Opus 5.5 1327f929e1 Add resumable multipart uploads for large files
Stream uploads and downloads in 1 MB blocks so memory use does not grow
with file size, under both WSGI and ASGI.

- S3 multipart upload API (create, upload part, list parts, complete,
  abort), so boto3 upload_file works for files over 8 MB.
- Browser uploader on the studio page: sends 16 MB parts three at a
  time with retries, and resumes when the same file is picked again.
  Uses session-authenticated, CSRF-protected JSON endpoints under
  /studio/<bucket>/uploads/.
- Request bodies are checked against the signed X-Amz-Content-Sha256
  instead of being read into memory; signed requests must include it.
  boto3's aws-chunked bodies with CRC32 trailers are decoded.
- Objects are written to a temporary file and renamed into place, so a
  failed upload leaves the existing file intact.
- Downloads stream with FileResponse, or an async iterator under ASGI.
- SigV4 verification uses the encoded path, fixing keys with spaces.
- cleanup_uploads command removes abandoned uploads and temp files.
- DATA_UPLOAD_MAX_MEMORY_SIZE is capped at 10 MB again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:24:52 -07:00

167 lines
7.4 KiB
Markdown

# Private Studio - Video Transcoding Web Service
A Django video transcoding management service. It provides S3-compatible file storage, API key authentication, and studio-based access control.
## Features
- **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
Requires Python 3.12+.
```bash
pip install -e ".[dev]"
```
## Quick Start
```bash
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
```
`create_key` prints the API key once. Keep it secret.
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.
See [README_SERVE.md](README_SERVE.md) for the full command guide.
## Project Layout
```
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)
```
## Configuration
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.
| 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`) |
| `UPLOAD_PART_SIZE_MB` | all | Part size for browser uploads (default `16`). Files that would need over 10,000 parts use larger parts |
| `UPLOAD_MAX_SIZE` | all | Largest multipart upload in bytes (default `0`, no limit) |
| `UPLOAD_EXPIRY_DAYS` | all | `cleanup_uploads` removes unfinished uploads idle for this many days (default `7`) |
| `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
All endpoints except `/health` need `Authorization: Bearer <API_KEY>`. The S3 endpoints also accept AWS v4 signatures made with credentials from `/api/s3keys`.
### 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 |
| POST | `/s3/{bucket}/{key}?uploads` | Start a multipart upload |
| PUT | `/s3/{bucket}/{key}?partNumber=N&uploadId=ID` | Upload a part |
| GET | `/s3/{bucket}/{key}?uploadId=ID` | List received parts |
| POST | `/s3/{bucket}/{key}?uploadId=ID` | Complete a multipart upload |
| DELETE | `/s3/{bucket}/{key}?uploadId=ID` | Abort a multipart upload |
| 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 -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 \
http://localhost:8000/s3/demo/videos/video.mp4
```
With boto3 (AWS v4 signatures):
```python
import boto3, requests
from botocore.config import Config
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")
```
`upload_file` sends files over 8 MB as a multipart upload. Uploads and downloads are streamed in 1 MB blocks, so memory use does not grow with file size. Signed requests must include `X-Amz-Content-Sha256` in their signed headers (boto3 and other S3 SDKs do), and the body is checked against it. boto3's `aws-chunked` uploads with CRC32 trailers are supported; the `STREAMING-AWS4-HMAC-SHA256-PAYLOAD` signing mode is not.
### Browser uploads
The studio page (`/studio/{bucket}/`) has an uploader for signed-in users. It sends files in parts, three at a time, and retries failed parts. If an upload is interrupted, picking the same file again (same name, size and modification time) sends only the missing parts. It uses these session-authenticated JSON endpoints, which need the `X-CSRFToken` header:
| Method | Path | Description |
|---|---|---|
| POST | `/studio/{bucket}/uploads/` | Start: `{"filename", "folder", "size", "last_modified", "overwrite"}` |
| GET | `/studio/{bucket}/uploads/{id}/` | Status and received part numbers |
| PUT | `/studio/{bucket}/uploads/{id}/parts/{n}/` | A part as the raw request body |
| POST | `/studio/{bucket}/uploads/{id}/complete/` | Join the parts (`{"overwrite": true}` to replace a file created meanwhile) |
| DELETE | `/studio/{bucket}/uploads/{id}/` | Cancel |
Parts are kept in `STORAGE_PATH/.multipart/` until the upload completes, so a file temporarily needs twice its size in free space. Run `python manage.py cleanup_uploads` daily to remove abandoned uploads (see [README_SERVE.md](README_SERVE.md)).
### Transcode profiles and jobs (per studio)
| 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}` | |
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
asset: videos/video.mp4
profile: hd-profile
```
```bash
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/yaml" \
--data-binary @job.yaml http://localhost:8000/api/studios/demo/transcode
```
## Storage
Files are stored under `STORAGE_PATH/<bucket_name>/<key>`. Keys that resolve outside the bucket directory are rejected.
## Testing
```bash
pytest
```