Compare commits
16
Commits
26ca77594a
...
v0.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d7d03a0a6 | ||
|
|
38f3a0da2f | ||
|
|
ba76671795 | ||
|
|
7231f69014 | ||
|
|
e582cb9234 | ||
|
|
5bb9a70c11 | ||
|
|
3fe49b47ea | ||
|
|
d73dddc3d9 | ||
|
|
3bbb57760e | ||
|
|
af18031a14 | ||
|
|
b3b51f6cc5 | ||
|
|
46adddd50a | ||
|
|
9522762de5 | ||
|
|
97e6f8f873 | ||
|
|
97d2d99dae | ||
|
|
057d6bed5c |
@@ -0,0 +1,21 @@
|
||||
.git/
|
||||
.gitea/
|
||||
.github/
|
||||
.idea/
|
||||
.vscode/
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
node_modules/
|
||||
storage/
|
||||
static/
|
||||
dist/
|
||||
build/
|
||||
*.egg-info/
|
||||
**/__pycache__
|
||||
*.pyc
|
||||
*.sqlite3
|
||||
*.db
|
||||
privatestudio/_version.py
|
||||
privatestudio/settings/local.py
|
||||
privatestudio/static/bundle/
|
||||
@@ -0,0 +1,215 @@
|
||||
name: Build and publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, closed]
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
env:
|
||||
REGISTRY: git.krugerprojects.com
|
||||
IMAGE_NAME: skruger/privatestudio
|
||||
|
||||
jobs:
|
||||
test:
|
||||
if: github.event.action != 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Python
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
python-version: "3.13"
|
||||
activate-environment: true
|
||||
|
||||
- name: Install package
|
||||
run: uv pip install -e ".[dev]"
|
||||
|
||||
- name: Run tests
|
||||
run: pytest
|
||||
|
||||
build:
|
||||
if: github.event.action != 'closed'
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.tag.outputs.tag }}
|
||||
version: ${{ steps.tag.outputs.version }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Determine image tags
|
||||
id: tag
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --tags
|
||||
current_tag=$(git tag --points-at HEAD | head -n1)
|
||||
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
|
||||
PR_NUMBER=$(echo "$GITHUB_REF" | cut -d'/' -f3)
|
||||
TAG="pr-${PR_NUMBER}"
|
||||
VERSION="0.0.0.dev${PR_NUMBER}"
|
||||
tags="${TAG} ${GITHUB_SHA::7}"
|
||||
elif [ -n "$current_tag" ]; then
|
||||
echo "Head already tagged: $current_tag"
|
||||
TAG="$current_tag"
|
||||
VERSION=${TAG#v}
|
||||
tags="latest ${VERSION} ${GITHUB_SHA::7}"
|
||||
else
|
||||
latest_tag=$(git tag --sort=-v:refname | head -n1 || true)
|
||||
if [ -z "$latest_tag" ]; then
|
||||
latest_tag="v0.0.0"
|
||||
fi
|
||||
sem=${latest_tag#v}
|
||||
IFS='.' read -r major minor patch <<< "${sem}"
|
||||
major=${major:-0}
|
||||
minor=${minor:-0}
|
||||
patch=${patch:-0}
|
||||
patch=$((patch+1))
|
||||
TAG="v${major}.${minor}.${patch}"
|
||||
git config user.name "gitea-actions"
|
||||
git config user.email "gitea-actions@git.krugerprojects.com"
|
||||
git tag -a "$TAG" -m "Release $TAG"
|
||||
git push origin "$TAG"
|
||||
VERSION=${TAG#v}
|
||||
tags="latest ${VERSION} ${GITHUB_SHA::7}"
|
||||
fi
|
||||
echo "Determined tag: $TAG, version: $VERSION, image tags: $tags"
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "tags=$tags" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Install dependencies
|
||||
run: apt-get update && apt-get install -y podman
|
||||
|
||||
- name: Login to registry
|
||||
run: |
|
||||
echo -e "${{ secrets.PACKAGE_ACCESS_TOKEN }}" | \
|
||||
podman login ${REGISTRY} -u "${{ vars.PACKAGE_USERNAME }}" --password-stdin
|
||||
|
||||
- name: Build image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
IMAGE="${REGISTRY}/${IMAGE_NAME}"
|
||||
buildah bud --userns=host -f Dockerfile \
|
||||
--build-arg VERSION="${{ steps.tag.outputs.version }}" \
|
||||
-t "${IMAGE}:build" .
|
||||
for t in ${{ steps.tag.outputs.tags }}; do
|
||||
echo "Tag: ${IMAGE}:${t}"
|
||||
buildah tag "${IMAGE}:build" "${IMAGE}:${t}"
|
||||
done
|
||||
|
||||
- name: Push image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
IMAGE="${REGISTRY}/${IMAGE_NAME}"
|
||||
for t in ${{ steps.tag.outputs.tags }}; do
|
||||
echo "Push: ${IMAGE}:${t}"
|
||||
buildah push "${IMAGE}:${t}"
|
||||
done
|
||||
|
||||
pypi:
|
||||
# Only publish releases from main, and only when a PyPI token is configured.
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
|
||||
steps:
|
||||
- name: Check for PyPI token
|
||||
run: |
|
||||
if [ -z "$PYPI_TOKEN" ]; then
|
||||
echo "PYPI_TOKEN secret is not set; skipping PyPI publish."
|
||||
fi
|
||||
|
||||
- name: Checkout repository
|
||||
if: env.PYPI_TOKEN != ''
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Node
|
||||
if: env.PYPI_TOKEN != ''
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Build static bundle
|
||||
if: env.PYPI_TOKEN != ''
|
||||
run: |
|
||||
mkdir -p privatestudio/static/bundle
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
- name: Set up Python
|
||||
if: env.PYPI_TOKEN != ''
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
python-version: "3.13"
|
||||
activate-environment: true
|
||||
|
||||
- name: Build distributions
|
||||
if: env.PYPI_TOKEN != ''
|
||||
env:
|
||||
SETUPTOOLS_SCM_PRETEND_VERSION: ${{ needs.build.outputs.version }}
|
||||
run: |
|
||||
uv pip install build twine
|
||||
python -m build
|
||||
twine check dist/*
|
||||
|
||||
- name: Publish to PyPI
|
||||
if: env.PYPI_TOKEN != ''
|
||||
env:
|
||||
TWINE_USERNAME: __token__
|
||||
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
|
||||
run: twine upload --non-interactive dist/*
|
||||
|
||||
cleanup:
|
||||
# Only run when a pull request is closed and merged
|
||||
if: github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged == true
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Install jq
|
||||
run: |
|
||||
apt-get update && apt-get install -y jq
|
||||
|
||||
- name: Delete PR images from Gitea package registry
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SERVER: ${{ gitea.server_url }}
|
||||
OWNER: skruger
|
||||
PACKAGE: privatestudio
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "Cleaning up Gitea registry images for PR #$PR_NUMBER"
|
||||
AUTH_HEADER="Authorization: token ${GITEA_TOKEN}"
|
||||
LIST_URL="${SERVER}/api/v1/packages/${OWNER}?type=container&q=${PACKAGE}&limit=50"
|
||||
VERSIONS_JSON=$(curl -s -H "$AUTH_HEADER" "$LIST_URL")
|
||||
MATCHES=$(echo "$VERSIONS_JSON" | jq -r --arg pr "pr-$PR_NUMBER" \
|
||||
'.[] | select(.version == $pr) | .version')
|
||||
if [ -z "$(echo "$MATCHES" | tr -d '\n')" ]; then
|
||||
echo "No image versions found for PR #$PR_NUMBER"
|
||||
exit 0
|
||||
fi
|
||||
for VERSION in $MATCHES; do
|
||||
echo "Deleting package version $VERSION"
|
||||
curl -s -X DELETE -H "$AUTH_HEADER" \
|
||||
"${SERVER}/api/v1/packages/${OWNER}/container/${PACKAGE}/${VERSION}" \
|
||||
|| echo "Failed to delete package version $VERSION"
|
||||
done
|
||||
echo "Cleanup complete."
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
.idea/
|
||||
.venv/
|
||||
dist/
|
||||
privatestudio/_version.py
|
||||
*.egg-info/
|
||||
|
||||
storage/
|
||||
|
||||
**.pyc
|
||||
__pycache__/
|
||||
|
||||
*.db
|
||||
|
||||
db.sqlite3
|
||||
privatestudio/settings/local.py
|
||||
privatestudio/static/bundle/
|
||||
node_modules/
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
FROM node:24 AS nodebuild
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY webpack.config.js ./
|
||||
COPY src ./src
|
||||
COPY privatestudio ./privatestudio
|
||||
RUN mkdir -p privatestudio/static/bundle && npm run build
|
||||
|
||||
|
||||
FROM python:3.13-slim-trixie
|
||||
|
||||
# Version used by setuptools_scm, since .git is not copied into the image.
|
||||
ARG VERSION=0.0.0
|
||||
|
||||
RUN useradd --create-home privatestudio
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PORT=8000 \
|
||||
DJANGO_SETTINGS_MODULE=privatestudio.settings.production \
|
||||
STORAGE_PATH=/data/storage
|
||||
|
||||
RUN pip install --no-cache-dir "gunicorn~=23.0" "psycopg2-binary~=2.9.11"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --chown=privatestudio:privatestudio . .
|
||||
COPY --from=nodebuild --chown=privatestudio:privatestudio /build/privatestudio/static/bundle ./privatestudio/static/bundle
|
||||
|
||||
RUN SETUPTOOLS_SCM_PRETEND_VERSION="${VERSION}" pip install --no-cache-dir . \
|
||||
&& mkdir -p /data/storage && chown -R privatestudio:privatestudio /data /app
|
||||
|
||||
USER privatestudio
|
||||
|
||||
RUN python manage.py collectstatic --noinput --clear
|
||||
|
||||
VOLUME ["/data"]
|
||||
|
||||
# Migrating at startup keeps "docker run" simple. Use a release step instead if
|
||||
# you run more than one container against the same database.
|
||||
CMD set -xe; \
|
||||
python manage.py migrate --noinput; \
|
||||
exec gunicorn privatestudio.wsgi:application \
|
||||
--bind 0.0.0.0:${PORT} \
|
||||
-k gthread --workers 2 --threads 8 --timeout 600
|
||||
@@ -0,0 +1,28 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2026, Shaun Kruger
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,3 @@
|
||||
# The JS/CSS bundle is built by npm and is not tracked in git, so
|
||||
# setuptools_scm will not pick it up on its own.
|
||||
graft privatestudio/static/bundle
|
||||
@@ -0,0 +1,166 @@
|
||||
# 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
|
||||
```
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
# Running and Managing Private Studio
|
||||
|
||||
Private Studio is a standard Django project. All administration goes through `manage.py`, which uses `privatestudio.settings.dev` unless `DJANGO_SETTINGS_MODULE` is set.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -e ".[dev]"
|
||||
python manage.py migrate
|
||||
```
|
||||
|
||||
## Access Model
|
||||
|
||||
- **Users** are standard `django.contrib.auth` users.
|
||||
- **Studios** each own one unique `bucket_name` and point to one Django **Group**.
|
||||
- A user can access a studio (its S3 bucket, profiles and jobs) when they are in that studio's group. Superusers can access every studio.
|
||||
- **API keys** belong to a user and authenticate as that user. Only a SHA256 hash of each key is stored.
|
||||
|
||||
## Commands
|
||||
|
||||
### Create users
|
||||
|
||||
```bash
|
||||
python manage.py createsuperuser # admin user
|
||||
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_user('alice')"
|
||||
```
|
||||
|
||||
You can also create users in the admin at `/admin/`.
|
||||
|
||||
### create_studio
|
||||
|
||||
```bash
|
||||
python manage.py create_studio <bucket_name> --group <group> [--name "Display Name"] [--add-user USER ...]
|
||||
```
|
||||
|
||||
This creates the group if it doesn't exist, adds the given users to it, and creates the studio. Bucket names must be lowercase letters, digits and hyphens.
|
||||
|
||||
### create_key
|
||||
|
||||
```bash
|
||||
python manage.py create_key <username>
|
||||
```
|
||||
|
||||
This prints a new API key. The key is shown only once. Users can also create and revoke their own keys through `/api/keys`.
|
||||
|
||||
### Run the server
|
||||
|
||||
```bash
|
||||
python manage.py runserver 0.0.0.0:8000
|
||||
```
|
||||
|
||||
In production, set `DJANGO_SETTINGS_MODULE=privatestudio.settings.production` and serve `privatestudio.wsgi:application` or `privatestudio.asgi:application` with your WSGI/ASGI server of choice. See the configuration table in [README.md](README.md).
|
||||
|
||||
### cleanup_uploads
|
||||
|
||||
```bash
|
||||
python manage.py cleanup_uploads [--days 7] [--dry-run]
|
||||
```
|
||||
|
||||
This removes unfinished uploads with no activity for `--days` (default `UPLOAD_EXPIRY_DAYS`), part directories without an active upload, and temporary files older than a day. Run it daily, for example from cron.
|
||||
|
||||
## Serving large uploads
|
||||
|
||||
Uploads and downloads are streamed, but the server in front of Django must allow them:
|
||||
|
||||
- **WSGI** (e.g. gunicorn): request bodies are read straight from the socket. A slow upload occupies a worker thread, so use threaded workers (`-k gthread --threads 8`) and a `--timeout` longer than the slowest part and the final join of a large file. A chunked request without `Content-Length` (boto3 over HTTPS) needs a server that sets `wsgi.input_terminated`, as gunicorn does; otherwise it is refused with 411.
|
||||
- **ASGI** (e.g. uvicorn): Django writes each request body to a temporary file before the view runs. Point `TMPDIR` at a disk with room for the largest single upload. Browser parts are 16 MB, but a plain S3 `PUT` of a whole file needs its full size.
|
||||
- **nginx**: set `client_max_body_size` above the part size (or `0` for large single PUTs), use `proxy_request_buffering off` for WSGI so bodies are not buffered twice, and raise `proxy_read_timeout` so completing a large upload is not cut off.
|
||||
- **Locking** uses `flock` on files in `STORAGE_PATH`. Run all app servers on the host that owns the storage, or on a filesystem where `flock` works across hosts.
|
||||
|
||||
## Typical Workflow
|
||||
|
||||
```bash
|
||||
python manage.py migrate
|
||||
python manage.py createsuperuser --username admin
|
||||
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_user('alice')"
|
||||
python manage.py create_studio demo --name "Demo Studio" --group demo-team --add-user alice
|
||||
python manage.py create_key alice
|
||||
python manage.py runserver
|
||||
|
||||
curl -H "Authorization: Bearer $KEY" http://localhost:8000/api/userinfo
|
||||
curl -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 http://localhost:8000/s3/demo/video.mp4
|
||||
curl -H "Authorization: Bearer $KEY" http://localhost:8000/s3/demo
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
pytest # all tests
|
||||
pytest privatestudio/studio/tests/test_s3.py -k signature
|
||||
pytest --cov=privatestudio
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **401 Unauthorized**: the API key is wrong or revoked, or the S3 credentials have expired (by default they last 1 hour, set by `S3_CREDENTIAL_TTL_HOURS`).
|
||||
- **403 on a bucket**: the user isn't in the studio's group. Add them in the admin.
|
||||
- **404 on a bucket**: no studio has that `bucket_name`.
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Upload an asset to the Private Studio web API using boto3.
|
||||
|
||||
This script demonstrates how to use boto3 to upload files to the Private Studio
|
||||
S3-compatible storage API.
|
||||
|
||||
Usage:
|
||||
python upload_asset.py \\
|
||||
--base-url http://localhost:8000 \\
|
||||
--api-key <your-api-key> \\
|
||||
--file /path/to/file.mp4 \\
|
||||
--key assets/my-video.mp4
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import requests
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
except ImportError:
|
||||
print("Error: boto3 is required. Install it with: pip install boto3", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def upload_asset(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
file_path: str,
|
||||
bucket: str,
|
||||
key: str,
|
||||
user_name: int = 1,
|
||||
) -> dict:
|
||||
"""
|
||||
Upload an asset to the Private Studio API.
|
||||
|
||||
Args:
|
||||
base_url: Base URL of the Private Studio API (e.g., http://localhost:8000)
|
||||
api_key: API key for authentication
|
||||
file_path: Path to the file to upload
|
||||
key: S3 key/path for the file (e.g., assets/my-file.mp4)
|
||||
user_name: User ID (defaults to 1)
|
||||
|
||||
Returns:
|
||||
Response from the API containing object_id, key, size, and filename
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the file doesn't exist
|
||||
ClientError: If the API returns an error
|
||||
"""
|
||||
|
||||
# Enable boto3 debug logging to see request/response details
|
||||
# import logging
|
||||
# boto3.set_stream_logger('botocore', logging.DEBUG)
|
||||
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
|
||||
# userinfo = requests.get(f"{base_url}/api/userinfo", headers={"Authorization": f"Bearer {api_key}"})
|
||||
# userinfo.raise_for_status()
|
||||
# user_data = userinfo.json()
|
||||
|
||||
s3creds = requests.post(f"{base_url}/api/s3keys", headers={"Authorization": f"Bearer {api_key}"})
|
||||
s3creds.raise_for_status()
|
||||
s3_creds = s3creds.json()
|
||||
|
||||
access_key = s3_creds.get("access_key")
|
||||
secret_key = s3_creds.get("secret_key")
|
||||
|
||||
print(f"\nS3 Credentials obtained:")
|
||||
print(f" Access Key: {access_key}")
|
||||
print(f" Secret Key: {secret_key[:10]}...{secret_key[-10:]}") # Masked for security
|
||||
print(f" Bucket: {bucket}")
|
||||
|
||||
file_path_obj = Path(file_path)
|
||||
if not file_path_obj.exists():
|
||||
raise FileNotFoundError(f"File not found: {file_path}")
|
||||
|
||||
# Configure boto3 client for S3-compatible API
|
||||
print(f"\nConfiguring boto3 client:")
|
||||
print(f" Endpoint URL: {base_url}/s3")
|
||||
print(f" Region: us-east-1")
|
||||
print(f" Signature Version: s3v4")
|
||||
print(f" Addressing Style: path")
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=f"{base_url}/s3",
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
region_name="us-east-1",
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Upload the file
|
||||
file_size = file_path_obj.stat().st_size
|
||||
|
||||
# print(f"\n{'='*60}")
|
||||
# print(f"Starting upload:")
|
||||
# print(f" File: {file_path}")
|
||||
# print(f" Size: {file_size} bytes ({file_size / (1024*1024):.2f} MB)")
|
||||
# print(f" Bucket: {bucket}")
|
||||
# print(f" Key: {key}")
|
||||
# print(f" Endpoint: {base_url}/s3/{bucket}/{key}")
|
||||
# print(f"{'='*60}\n")
|
||||
|
||||
with open(file_path, "rb") as f:
|
||||
print(f"Opened file: {file_path}")
|
||||
response = s3_client.put_object(
|
||||
Bucket=bucket,
|
||||
Key=key,
|
||||
Body=f,
|
||||
)
|
||||
|
||||
print("Upload successful!")
|
||||
print(f"Response: {response}")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"key": key,
|
||||
"size": file_size,
|
||||
"etag": response.get("ETag"),
|
||||
}
|
||||
|
||||
except ClientError as e:
|
||||
error_code = e.response.get("Error", {}).get("Code")
|
||||
error_message = e.response.get("Error", {}).get("Message")
|
||||
# status_code = e.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
# headers = e.response.get("ResponseMetadata", {}).get("HTTPHeaders", {})
|
||||
#
|
||||
# print(f"\n{'='*60}", file=sys.stderr)
|
||||
print(f"Error uploading file: {error_code} - {error_message}", file=sys.stderr)
|
||||
# print(f"HTTP Status Code: {status_code}", file=sys.stderr)
|
||||
# print(f"Response Headers: {headers}", file=sys.stderr)
|
||||
# print(f"Full Response: {e.response}", file=sys.stderr)
|
||||
# print(f"{'='*60}\n", file=sys.stderr)
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"\n{'='*60}", file=sys.stderr)
|
||||
print(f"Unexpected error: {e}", file=sys.stderr)
|
||||
print(f"Error type: {type(e).__name__}", file=sys.stderr)
|
||||
import traceback
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
print(f"{'='*60}\n", file=sys.stderr)
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
"""Parse arguments and execute upload."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Upload an asset to the Private Studio web API",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
python upload_asset.py --base-url http://localhost:8000 --api-key sk_test_123abc --file video.mp4 --key assets/video.mp4
|
||||
python upload_asset.py --base-url https://api.example.com --api-key sk_prod_456def --file image.jpg --key media/image.jpg --user-id 2
|
||||
""",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--base-url",
|
||||
required=True,
|
||||
help="Base URL of the Private Studio API (e.g., http://localhost:8000)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-key",
|
||||
required=True,
|
||||
help="API key for authentication",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--file",
|
||||
required=True,
|
||||
help="Path to the file to upload",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--key",
|
||||
required=True,
|
||||
help="S3 key/path for the file (e.g., assets/my-file.mp4)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id",
|
||||
type=int,
|
||||
default=1,
|
||||
help="User ID (defaults to 1)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--bucket",
|
||||
required=True,
|
||||
help="S3 bucket name (e.g., demo)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
result = upload_asset(
|
||||
base_url=args.base_url,
|
||||
api_key=args.api_key,
|
||||
file_path=args.file,
|
||||
key=args.key,
|
||||
user_name=args.user_id,
|
||||
bucket=args.bucket,
|
||||
)
|
||||
print(f"\nUpload completed: {result}")
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f"Upload failed: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "privatestudio.settings.dev")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
||||
Generated
+2858
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "privatestudio",
|
||||
"version": "0.1.0",
|
||||
"description": "Javascript and CSS dependencies for privatestudio CMS",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"devbuild": "webpack --mode development --output-path ./privatestudio/static/bundle/",
|
||||
"build": "npm run build-bundle && npm run build-htmx && npm run build-tinymce",
|
||||
"build-bundle": "webpack --mode production --output-path ./privatestudio/static/bundle/",
|
||||
"build-htmx": "cp node_modules/htmx.org/dist/htmx*.js ./privatestudio/static/bundle/",
|
||||
"build-tinymce": "mkdir -p ./privatestudio/static/bundle/tinymce && cp -r node_modules/tinymce/* ./privatestudio/static/bundle/tinymce/",
|
||||
"watch": "npm run build-htmx && npm run build-tinymce && webpack --mode development --output-path ./privatestudio/static/bundle/ --watch",
|
||||
"build:digitalocean": "npm install --production=false && npm run build"
|
||||
},
|
||||
"author": "Shaun Kruger",
|
||||
"license": "BSD-3-Clause",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": "v24.22.x",
|
||||
"npm": "11.19.x"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autoprefixer": "^10.4.20",
|
||||
"css-loader": "^7.1.2",
|
||||
"html-webpack-plugin": "^5.6.0",
|
||||
"mini-css-extract-plugin": "^2.9.1",
|
||||
"postcss-loader": "^8.1.1",
|
||||
"sass": "^1.79.3",
|
||||
"sass-loader": "^16.0.2",
|
||||
"style-loader": "^4.0.0",
|
||||
"webpack": "^5.94.0",
|
||||
"webpack-cli": "^5.1.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"bootstrap": "^5.3.3",
|
||||
"htmx.org": "^1.9.12",
|
||||
"jquery": "^3.7.1",
|
||||
"tinymce": "^8.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
"""ASGI config for the privatestudio project."""
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "privatestudio.settings.dev")
|
||||
|
||||
application = get_asgi_application()
|
||||
@@ -0,0 +1,44 @@
|
||||
import nh3
|
||||
|
||||
from django import forms
|
||||
from django.forms import Textarea
|
||||
|
||||
NH3_TAGS = {
|
||||
"a",
|
||||
"p",
|
||||
"strong",
|
||||
"img",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"b",
|
||||
"s",
|
||||
"u",
|
||||
"i",
|
||||
"em",
|
||||
}
|
||||
|
||||
NH3_ATTR = {
|
||||
"a": {
|
||||
"href",
|
||||
"target",
|
||||
},
|
||||
"img": {
|
||||
"alt",
|
||||
"src",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class HtmlTextField(forms.CharField):
|
||||
widget = Textarea
|
||||
|
||||
def to_python(self, value):
|
||||
value = super().to_python(value)
|
||||
if value not in self.empty_values:
|
||||
value = nh3.clean(
|
||||
value,
|
||||
tags=NH3_TAGS,
|
||||
attributes=NH3_ATTR,
|
||||
)
|
||||
return value
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Base Django settings for the privatestudio project.
|
||||
|
||||
Environment specific settings live in dev.py and production.py.
|
||||
"""
|
||||
import os
|
||||
|
||||
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
BASE_DIR = os.path.dirname(PROJECT_DIR)
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"privatestudio.studio.app.StudioConfig",
|
||||
"corsheaders",
|
||||
"ninja",
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
|
||||
"allauth",
|
||||
"allauth.account",
|
||||
"allauth.socialaccount",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
"corsheaders.middleware.CorsMiddleware",
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"allauth.account.middleware.AccountMiddleware",
|
||||
|
||||
]
|
||||
|
||||
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
|
||||
|
||||
ROOT_URLCONF = "privatestudio.urls"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [
|
||||
os.path.join(PROJECT_DIR, "templates"),
|
||||
],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = "privatestudio.wsgi.application"
|
||||
ASGI_APPLICATION = "privatestudio.asgi.application"
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"privatestudio": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# Database
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
|
||||
}
|
||||
}
|
||||
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
|
||||
LANGUAGE_CODE = "en-us"
|
||||
TIME_ZONE = os.environ.get("DJANGO_TIME_ZONE", "UTC")
|
||||
USE_I18N = True
|
||||
USE_TZ = True
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/4.2/howto/static-files/
|
||||
|
||||
STATICFILES_FINDERS = [
|
||||
"django.contrib.staticfiles.finders.FileSystemFinder",
|
||||
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
|
||||
]
|
||||
|
||||
STATICFILES_DIRS = [
|
||||
os.path.join(PROJECT_DIR, "static"),
|
||||
]
|
||||
|
||||
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, "static")
|
||||
STATIC_URL = "/static/"
|
||||
|
||||
|
||||
# Object bodies are streamed, so this only limits API and form bodies.
|
||||
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024
|
||||
|
||||
|
||||
# Private Studio configuration
|
||||
|
||||
PRIVATESTUDIO_STORAGE_PATH = os.environ.get("STORAGE_PATH", os.path.join(BASE_DIR, "storage"))
|
||||
PRIVATESTUDIO_S3_CREDENTIAL_TTL_HOURS = int(os.environ.get("S3_CREDENTIAL_TTL_HOURS", "1"))
|
||||
|
||||
# Size of the parts the browser uploader sends. Larger parts are used for files that need over 10,000.
|
||||
PRIVATESTUDIO_UPLOAD_PART_SIZE = int(os.environ.get("UPLOAD_PART_SIZE_MB", "16")) * 1024 * 1024
|
||||
# Largest multipart upload in bytes. 0 means no limit.
|
||||
PRIVATESTUDIO_UPLOAD_MAX_SIZE = int(os.environ.get("UPLOAD_MAX_SIZE", "0"))
|
||||
# cleanup_uploads removes unfinished uploads without activity for this long.
|
||||
PRIVATESTUDIO_UPLOAD_EXPIRY_DAYS = int(os.environ.get("UPLOAD_EXPIRY_DAYS", "7"))
|
||||
@@ -0,0 +1,17 @@
|
||||
from .base import * # noqa: F401,F403
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = "django-insecure-privatestudio-dev-key-change-me"
|
||||
|
||||
# SECURITY WARNING: define the correct hosts in production!
|
||||
ALLOWED_HOSTS = ["*"]
|
||||
|
||||
CORS_ALLOW_ALL_ORIGINS = True
|
||||
|
||||
try:
|
||||
from .local import * # noqa: F401,F403
|
||||
except ImportError:
|
||||
pass
|
||||
@@ -0,0 +1,58 @@
|
||||
import os
|
||||
|
||||
import dj_database_url
|
||||
|
||||
from .base import * # noqa: F401,F403
|
||||
|
||||
DEBUG = False
|
||||
|
||||
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "*").split(",")
|
||||
|
||||
SECRET_KEY = os.environ.get("SECRET_KEY", "This isn't a good secret key default value, you should set one in the environment")
|
||||
|
||||
if os.environ.get("DATABASE_URL"):
|
||||
DATABASES = {
|
||||
"default": dj_database_url.config(),
|
||||
}
|
||||
else:
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": os.path.join("/data", "db.sqlite3"),
|
||||
}
|
||||
}
|
||||
|
||||
CORS_ALLOWED_ORIGINS = [o for o in os.environ.get("CORS_ALLOWED_ORIGINS", "").split(",") if o]
|
||||
|
||||
CSRF_TRUSTED_ORIGINS = [f"https://{h}" for h in ALLOWED_HOSTS if h != "*"]
|
||||
|
||||
if os.environ.get("SECURE_PROXY_SSL_HEADER"):
|
||||
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "INFO",
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"root": {
|
||||
"handlers": ["console"],
|
||||
"level": "WARNING",
|
||||
"propagate": True,
|
||||
},
|
||||
"privatestudio": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
from local_settings import * # noqa: F401,F403
|
||||
except ImportError:
|
||||
pass
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
@@ -0,0 +1,35 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<style>
|
||||
.ink { fill: #1f2937; stroke: #1f2937; }
|
||||
@media (prefers-color-scheme: dark) { .ink { fill: #e5e7eb; stroke: #e5e7eb; } }
|
||||
</style>
|
||||
<defs>
|
||||
<mask id="reel">
|
||||
<rect x="-12" y="-12" width="24" height="24" fill="#fff"/>
|
||||
<g fill="#000">
|
||||
<circle cx="0" cy="-5" r="2.6"/>
|
||||
<circle cx="4.33" cy="2.5" r="2.6"/>
|
||||
<circle cx="-4.33" cy="2.5" r="2.6"/>
|
||||
<circle r="1.1"/>
|
||||
</g>
|
||||
</mask>
|
||||
</defs>
|
||||
<g class="ink">
|
||||
<!-- film reels -->
|
||||
<g transform="translate(18 13)"><circle r="9.5" mask="url(#reel)" stroke="none"/></g>
|
||||
<g transform="translate(38 13)"><circle r="9.5" mask="url(#reel)" stroke="none"/></g>
|
||||
<!-- camera body -->
|
||||
<rect x="11" y="24" width="33" height="16" rx="2.5" stroke="none"/>
|
||||
<!-- lens barrel and hood -->
|
||||
<rect x="43" y="28.5" width="6" height="7" stroke="none"/>
|
||||
<path d="M48 29 L57 25 L57 39 L48 35 Z" stroke="none"/>
|
||||
<!-- tripod head -->
|
||||
<rect x="23" y="39" width="10" height="4" rx="1" stroke="none"/>
|
||||
<!-- tripod legs -->
|
||||
<g fill="none" stroke-width="3" stroke-linecap="round">
|
||||
<path d="M28 43 L13 61"/>
|
||||
<path d="M28 43 L43 61"/>
|
||||
<path d="M28 43 L28 60"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1,14 @@
|
||||
|
||||
|
||||
document.body.addEventListener("initialize_tinymce", function(evt){
|
||||
tinymce.remove();
|
||||
tinymce.init({
|
||||
selector: evt.detail.selector,
|
||||
license_key: 'gpl',
|
||||
menubar: '',
|
||||
toolbar: 'undo redo | bold italic | bullist numlist | link emoticons',
|
||||
plugins: [
|
||||
'link', 'emoticons', 'lists'
|
||||
]
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
from django.contrib import admin, messages
|
||||
from django.utils.html import format_html
|
||||
|
||||
from privatestudio.studio import models
|
||||
from privatestudio.studio.auth import generate_api_key, hash_api_key
|
||||
|
||||
|
||||
@admin.register(models.Studio)
|
||||
class StudioAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "bucket_name", "group", "created_at")
|
||||
search_fields = ("name", "bucket_name")
|
||||
|
||||
|
||||
@admin.register(models.APIKey)
|
||||
class APIKeyAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "user", "created_at", "is_active")
|
||||
list_filter = ("is_active",)
|
||||
readonly_fields = ("key_hash",)
|
||||
|
||||
def get_fields(self, request, obj=None):
|
||||
fields = super().get_fields(request, obj)
|
||||
if obj is None:
|
||||
# Generated in save_model, so there is nothing to show yet.
|
||||
return [f for f in fields if f != "key_hash"]
|
||||
return fields
|
||||
|
||||
def save_model(self, request, obj, form, change):
|
||||
if change:
|
||||
super().save_model(request, obj, form, change)
|
||||
return
|
||||
plain_key = generate_api_key()
|
||||
obj.key_hash = hash_api_key(plain_key)
|
||||
super().save_model(request, obj, form, change)
|
||||
messages.warning(
|
||||
request,
|
||||
format_html(
|
||||
"API key for {}: <code>{}</code> Copy it now; it will not be shown again.",
|
||||
obj.user,
|
||||
plain_key,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@admin.register(models.S3Credential)
|
||||
class S3CredentialAdmin(admin.ModelAdmin):
|
||||
list_display = ("access_key", "user", "created_at", "expires_at")
|
||||
exclude = ("secret_key",)
|
||||
|
||||
|
||||
@admin.register(models.UploadedAsset)
|
||||
class UploadedAssetAdmin(admin.ModelAdmin):
|
||||
list_display = ("s3_path", "studio", "size", "uploaded_by", "upload_timestamp")
|
||||
list_filter = ("studio",)
|
||||
|
||||
|
||||
@admin.register(models.MultipartUpload)
|
||||
class MultipartUploadAdmin(admin.ModelAdmin):
|
||||
list_display = ("key", "studio", "status", "total_size", "created_by", "created_at")
|
||||
list_filter = ("status", "studio")
|
||||
readonly_fields = ("upload_id",)
|
||||
|
||||
|
||||
@admin.register(models.UploadPart)
|
||||
class UploadPartAdmin(admin.ModelAdmin):
|
||||
list_display = ("upload", "part_number", "size", "uploaded_at")
|
||||
|
||||
|
||||
@admin.register(models.TranscodeProfile)
|
||||
class TranscodeProfileAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "studio", "created_by", "created_at")
|
||||
list_filter = ("studio",)
|
||||
|
||||
|
||||
@admin.register(models.TranscodeJob)
|
||||
class TranscodeJobAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "studio", "asset", "profile", "status", "requested_at", "completed_at")
|
||||
list_filter = ("studio", "status")
|
||||
|
||||
|
||||
@admin.register(models.PackagingJob)
|
||||
class PackagingJobAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "studio", "transcode_job", "status", "requested_at", "completed_at")
|
||||
list_filter = ("studio", "status")
|
||||
|
||||
|
||||
@admin.register(models.TranscodedAsset)
|
||||
class TranscodedAssetAdmin(admin.ModelAdmin):
|
||||
list_display = ("s3_path", "studio", "transcode_job", "format", "created_at")
|
||||
list_filter = ("studio", "format")
|
||||
|
||||
|
||||
@admin.register(models.ContentGroup)
|
||||
class ContentGroupAdmin(admin.ModelAdmin):
|
||||
list_display = ("title", "kind", "studio", "created_at")
|
||||
list_filter = ("studio", "kind")
|
||||
search_fields = ("title",)
|
||||
|
||||
|
||||
@admin.register(models.ContentAsset)
|
||||
class ContentAssetAdmin(admin.ModelAdmin):
|
||||
list_display = ("title", "kind", "group", "season_number", "episode_number", "release_date")
|
||||
list_filter = ("studio", "kind")
|
||||
search_fields = ("title",)
|
||||
raw_id_fields = ("uploaded_asset",)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Django Ninja API wiring."""
|
||||
from ninja import NinjaAPI
|
||||
|
||||
from privatestudio.studio.auth import ApiKeyAuth
|
||||
from privatestudio.studio.routers import keys, profiles, s3_keys, transcode, userinfo
|
||||
|
||||
api = NinjaAPI(
|
||||
title="Private Studio",
|
||||
description="Video transcoding web service with S3-compatible interface",
|
||||
version="0.1.0",
|
||||
auth=ApiKeyAuth(),
|
||||
urls_namespace="api",
|
||||
)
|
||||
|
||||
|
||||
@api.exception_handler(ValueError)
|
||||
def value_error_handler(request, exc):
|
||||
return api.create_response(request, {"detail": str(exc)}, status=400)
|
||||
|
||||
|
||||
api.add_router("", keys.router, tags=["Keys"])
|
||||
api.add_router("", s3_keys.router, tags=["S3 Keys"])
|
||||
api.add_router("", userinfo.router, tags=["UserInfo"])
|
||||
api.add_router("", profiles.router, tags=["Profiles"])
|
||||
api.add_router("", transcode.router, tags=["Transcode"])
|
||||
@@ -0,0 +1,8 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class StudioConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "privatestudio.studio"
|
||||
label = "studio"
|
||||
verbose_name = "Private Studio"
|
||||
@@ -0,0 +1,121 @@
|
||||
"""API key authentication helpers."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from ninja.security import HttpBearer
|
||||
|
||||
from privatestudio.studio.models import APIKey
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def hash_api_key(key: str) -> str:
|
||||
"""Hash an API key using SHA256."""
|
||||
return hashlib.sha256(key.encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_api_key(plain_key: str, hashed_key: str) -> bool:
|
||||
"""Verify a plain API key against its hash."""
|
||||
return hmac.compare_digest(hash_api_key(plain_key), hashed_key)
|
||||
|
||||
|
||||
def generate_api_key() -> str:
|
||||
"""Generate a random API key."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def create_api_key(user) -> tuple[str, APIKey]:
|
||||
"""
|
||||
Create a new API key for a user.
|
||||
|
||||
Returns (plain_key, api_key_record). The plain key is only returned here;
|
||||
only its hash is stored.
|
||||
"""
|
||||
plain_key = generate_api_key()
|
||||
api_key = APIKey.objects.create(user=user, key_hash=hash_api_key(plain_key), is_active=True)
|
||||
return plain_key, api_key
|
||||
|
||||
|
||||
def revoke_api_key(api_key: APIKey) -> None:
|
||||
"""Revoke an API key by marking it inactive."""
|
||||
api_key.is_active = False
|
||||
api_key.save(update_fields=["is_active"])
|
||||
|
||||
|
||||
def user_for_api_key(token: str):
|
||||
"""Return the active user owning ``token`` or None."""
|
||||
if not token:
|
||||
return None
|
||||
api_key = (
|
||||
APIKey.objects.select_related("user")
|
||||
.filter(key_hash=hash_api_key(token), is_active=True)
|
||||
.first()
|
||||
)
|
||||
if api_key is None or not api_key.user.is_active:
|
||||
return None
|
||||
return api_key.user
|
||||
|
||||
|
||||
class ApiKeyAuth(HttpBearer):
|
||||
"""Django Ninja bearer token authentication backed by APIKey."""
|
||||
|
||||
def authenticate(self, request, token):
|
||||
user = user_for_api_key(token)
|
||||
if user is not None:
|
||||
request.user = user
|
||||
return user
|
||||
|
||||
|
||||
def _bearer_token(request) -> Optional[str]:
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
scheme, _, token = auth_header.partition(" ")
|
||||
if scheme.lower() != "bearer":
|
||||
return None
|
||||
return token.strip() or None
|
||||
|
||||
|
||||
def is_s3_v4_request(request) -> bool:
|
||||
return request.headers.get("Authorization", "").startswith("AWS4-HMAC-SHA256")
|
||||
|
||||
|
||||
def authenticate_s3_request(request):
|
||||
"""
|
||||
Hybrid auth for S3 endpoints: AWS v4 signatures first, then bearer tokens.
|
||||
|
||||
Returns the authenticated user or None.
|
||||
"""
|
||||
from privatestudio.studio.s3_credentials import get_s3_credential, verify_aws_v4_signature
|
||||
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
|
||||
if auth_header.startswith("AWS4-HMAC-SHA256"):
|
||||
try:
|
||||
cred_part = auth_header.split("Credential=")[1].split(",")[0]
|
||||
access_key = cred_part.split("/")[0]
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
credential = get_s3_credential(access_key)
|
||||
if credential is None:
|
||||
return None
|
||||
|
||||
headers = dict(request.headers)
|
||||
headers.setdefault("Host", request.get_host())
|
||||
|
||||
if verify_aws_v4_signature(
|
||||
auth_header,
|
||||
request.method,
|
||||
request.path,
|
||||
request.META.get("QUERY_STRING", ""),
|
||||
headers,
|
||||
credential.secret_key,
|
||||
):
|
||||
user = get_user_model().objects.filter(pk=credential.user_id, is_active=True).first()
|
||||
return user
|
||||
return None
|
||||
|
||||
return user_for_api_key(_bearer_token(request))
|
||||
@@ -0,0 +1,27 @@
|
||||
from django import forms
|
||||
|
||||
from privatestudio.studio.models import ContentAsset
|
||||
from privatestudio.fields import HtmlTextField
|
||||
|
||||
|
||||
class ContentAssetForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = ContentAsset
|
||||
fields = [
|
||||
"kind", "title", "description", "release_date",
|
||||
"group", "season_number", "episode_number", "sequence_number",
|
||||
]
|
||||
widgets = {
|
||||
"release_date": forms.DateInput(attrs={"type": "date"}, format="%Y-%m-%d"),
|
||||
"description": forms.Textarea(attrs={"rows": 4}),
|
||||
}
|
||||
field_classes = {
|
||||
"description": HtmlTextField,
|
||||
}
|
||||
|
||||
def __init__(self, *args, studio, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["group"].queryset = studio.content_groups.all()
|
||||
for field in self.fields.values():
|
||||
css = "form-select" if isinstance(field.widget, forms.Select) else "form-control"
|
||||
field.widget.attrs["class"] = css
|
||||
@@ -0,0 +1,79 @@
|
||||
import time
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.db.models import Max
|
||||
from django.db.models.functions import Coalesce, Greatest
|
||||
from django.utils import timezone
|
||||
|
||||
from privatestudio.studio import uploads
|
||||
from privatestudio.studio.models import MultipartUpload, UploadStatus
|
||||
from privatestudio.studio.storage import LockBusy, UploadGone, get_storage
|
||||
|
||||
TEMP_AGE_SECONDS = 24 * 3600
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Remove abandoned uploads, orphaned part directories and old temporary files."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("--days", type=int, default=settings.PRIVATESTUDIO_UPLOAD_EXPIRY_DAYS,
|
||||
help="Remove uploads without activity for this many days (default %(default)s)")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Only report what would be removed")
|
||||
|
||||
def handle(self, *args, days, dry_run, **options):
|
||||
storage = get_storage()
|
||||
cutoff = timezone.now() - timedelta(days=days)
|
||||
verb = "Would remove" if dry_run else "Removed"
|
||||
|
||||
expired = MultipartUpload.objects.annotate(
|
||||
last_activity=Greatest("created_at", Coalesce(Max("parts__uploaded_at"), "created_at")),
|
||||
).filter(last_activity__lt=cutoff)
|
||||
for upload in expired:
|
||||
if not dry_run:
|
||||
if upload.status == UploadStatus.ACTIVE:
|
||||
try:
|
||||
uploads.abort(upload)
|
||||
except uploads.UploadError as e:
|
||||
self.stdout.write(f"Skipped {upload}: {e.message}")
|
||||
continue
|
||||
storage.remove_upload(upload.upload_id)
|
||||
upload.delete()
|
||||
self.stdout.write(f"{verb} upload {upload.upload_id} {upload}")
|
||||
|
||||
old = time.time() - TEMP_AGE_SECONDS
|
||||
for path in self.children(storage.multipart_path):
|
||||
try:
|
||||
upload_id = uuid.UUID(path.name)
|
||||
except ValueError:
|
||||
continue
|
||||
if path.stat().st_mtime > old:
|
||||
continue
|
||||
if MultipartUpload.objects.filter(upload_id=upload_id, status=UploadStatus.ACTIVE).exists():
|
||||
continue
|
||||
if not dry_run:
|
||||
try:
|
||||
with storage.lock_upload(upload_id, timeout=0):
|
||||
storage.remove_upload(upload_id)
|
||||
except LockBusy:
|
||||
continue
|
||||
except UploadGone:
|
||||
storage.remove_upload(upload_id)
|
||||
self.stdout.write(f"{verb} directory {path.name}")
|
||||
|
||||
# Writes move a file's mtime, so an upload in progress is never this old.
|
||||
for path in [*self.children(storage.temp_path), *storage.multipart_path.glob("*/*.tmp")]:
|
||||
try:
|
||||
stale = path.stat().st_mtime < old
|
||||
if stale and not dry_run:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
if stale:
|
||||
self.stdout.write(f"{verb} temporary file {path.name}")
|
||||
|
||||
@staticmethod
|
||||
def children(directory):
|
||||
return list(directory.iterdir()) if directory.is_dir() else []
|
||||
@@ -0,0 +1,23 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Create an API key for a user. The key is printed once and cannot be recovered."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("username", help="Username to create the key for")
|
||||
|
||||
def handle(self, *args, **options):
|
||||
User = get_user_model()
|
||||
try:
|
||||
user = User.objects.get_by_natural_key(options["username"])
|
||||
except User.DoesNotExist:
|
||||
raise CommandError(f"User '{options['username']}' not found")
|
||||
|
||||
plain_key, api_key = create_api_key(user)
|
||||
self.stdout.write(self.style.SUCCESS(f"API key {api_key.id} created for user {user.get_username()}"))
|
||||
self.stdout.write(f"Key: {plain_key}")
|
||||
self.stdout.write("Keep this key safe - you won't be able to see it again!")
|
||||
@@ -0,0 +1,42 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.utils.text import slugify
|
||||
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Create a studio (S3 bucket) whose access is granted by membership in a group."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("bucket_name", help="Unique bucket name for the studio")
|
||||
parser.add_argument("--name", help="Display name (defaults to the bucket name)")
|
||||
parser.add_argument("--group", required=True, help="Group granting access (created if missing)")
|
||||
parser.add_argument("--add-user", action="append", default=[], metavar="USERNAME",
|
||||
help="Add a user to the group (may be repeated)")
|
||||
|
||||
def handle(self, *args, **options):
|
||||
bucket_name = options["bucket_name"]
|
||||
if slugify(bucket_name) != bucket_name:
|
||||
raise CommandError(f"Invalid bucket name '{bucket_name}': use lowercase letters, digits and hyphens")
|
||||
if Studio.objects.filter(bucket_name=bucket_name).exists():
|
||||
raise CommandError(f"Studio with bucket '{bucket_name}' already exists")
|
||||
|
||||
User = get_user_model()
|
||||
users = []
|
||||
for username in options["add_user"]:
|
||||
try:
|
||||
users.append(User.objects.get_by_natural_key(username))
|
||||
except User.DoesNotExist:
|
||||
raise CommandError(f"User '{username}' not found")
|
||||
|
||||
group, created = Group.objects.get_or_create(name=options["group"])
|
||||
if created:
|
||||
self.stdout.write(f"Created group '{group.name}'")
|
||||
for user in users:
|
||||
user.groups.add(group)
|
||||
self.stdout.write(f"Added {user.get_username()} to group '{group.name}'")
|
||||
|
||||
studio = Studio.objects.create(name=options["name"] or bucket_name, bucket_name=bucket_name, group=group)
|
||||
self.stdout.write(self.style.SUCCESS(f"Studio created: {studio}"))
|
||||
@@ -0,0 +1,131 @@
|
||||
# Generated by Django 6.1.3 on 2026-11-29 22:51
|
||||
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('auth', '0012_alter_user_first_name_max_length'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='APIKey',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key_hash', models.CharField(max_length=64, unique=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_keys', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='S3Credential',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('access_key', models.CharField(max_length=64, unique=True)),
|
||||
('secret_key', models.CharField(max_length=128)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('expires_at', models.DateTimeField()),
|
||||
('authorized_key', models.TextField(blank=True, null=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='s3_credentials', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Studio',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
('bucket_name', models.SlugField(max_length=63, unique=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('group', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='studios', to='auth.group')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['bucket_name'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodeJob',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('profile_definition', models.TextField(blank=True, default='')),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20)),
|
||||
('requested_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('completed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('requested_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcode_jobs', to='studio.studio')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodedAsset',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('filename', models.TextField()),
|
||||
('s3_path', models.TextField()),
|
||||
('format', models.CharField(max_length=32)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcoded_assets', to='studio.studio')),
|
||||
('transcode_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcoded_assets', to='studio.transcodejob')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='PackagingJob',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20)),
|
||||
('requested_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('completed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('requested_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='packaging_jobs', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='packaging_jobs', to='studio.studio')),
|
||||
('transcode_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='packaging_jobs', to='studio.transcodejob')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodeProfile',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
('profile_definition', models.TextField()),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_profiles', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcode_profiles', to='studio.studio')),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transcodejob',
|
||||
name='profile',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to='studio.transcodeprofile'),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UploadedAsset',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('filename', models.TextField()),
|
||||
('size', models.BigIntegerField()),
|
||||
('s3_path', models.TextField()),
|
||||
('upload_timestamp', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='uploaded_assets', to='studio.studio')),
|
||||
('uploaded_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='uploaded_assets', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transcodejob',
|
||||
name='asset',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcode_jobs', to='studio.uploadedasset'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='transcodeprofile',
|
||||
constraint=models.UniqueConstraint(fields=('studio', 'name'), name='unique_profile_name_per_studio'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='uploadedasset',
|
||||
constraint=models.UniqueConstraint(fields=('studio', 's3_path'), name='unique_asset_path_per_studio'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,51 @@
|
||||
# Generated by Django 6.1.3 on 2026-12-01 23:59
|
||||
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('studio', '0001_initial'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='MultipartUpload',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('upload_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('key', models.TextField()),
|
||||
('filename', models.TextField()),
|
||||
('total_size', models.BigIntegerField(blank=True, null=True)),
|
||||
('part_size', models.BigIntegerField(blank=True, null=True)),
|
||||
('last_modified', models.BigIntegerField(blank=True, null=True)),
|
||||
('overwrite', models.BooleanField(default=True)),
|
||||
('status', models.CharField(choices=[('active', 'Active'), ('completed', 'Completed'), ('aborted', 'Aborted')], default='active', max_length=20)),
|
||||
('etag', models.CharField(blank=True, default='', max_length=64)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='multipart_uploads', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='multipart_uploads', to='studio.studio')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UploadPart',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('part_number', models.PositiveIntegerField()),
|
||||
('size', models.BigIntegerField()),
|
||||
('etag', models.CharField(max_length=32)),
|
||||
('uploaded_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('upload', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parts', to='studio.multipartupload')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['part_number'],
|
||||
'constraints': [models.UniqueConstraint(fields=('upload', 'part_number'), name='unique_part_per_upload')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,72 @@
|
||||
# Generated by Django 6.1.3 on 2026-12-02 01:06
|
||||
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('studio', '0002_multipart_uploads'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='packagingjob',
|
||||
name='status',
|
||||
field=models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='transcodejob',
|
||||
name='status',
|
||||
field=models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ContentGroup',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('kind', models.CharField(choices=[('series', 'Series'), ('collection', 'Movie collection')], max_length=20)),
|
||||
('title', models.CharField(max_length=255)),
|
||||
('description', models.TextField(blank=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='content_groups', to='studio.studio')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['title'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ContentAsset',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('kind', models.CharField(choices=[('video', 'Video'), ('episode', 'Episode'), ('movie', 'Movie')], default='video', max_length=20)),
|
||||
('title', models.CharField(max_length=255)),
|
||||
('description', models.TextField(blank=True)),
|
||||
('release_date', models.DateField(blank=True, null=True)),
|
||||
('season_number', models.PositiveIntegerField(blank=True, null=True)),
|
||||
('episode_number', models.PositiveIntegerField(blank=True, null=True)),
|
||||
('sequence_number', models.PositiveIntegerField(blank=True, help_text='Order of a movie within its collection.', null=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='content_assets', to='studio.studio')),
|
||||
('uploaded_asset', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, related_name='content_assets', to='studio.uploadedasset', null=True, blank=True)),
|
||||
('group', models.ForeignKey(blank=True, help_text='The series an episode belongs to, or the collection a movie belongs to.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='content_assets', to='studio.contentgroup')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['group__title', 'season_number', 'episode_number', 'sequence_number', 'title'],
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='contentgroup',
|
||||
constraint=models.UniqueConstraint(fields=('studio', 'kind', 'title'), name='unique_content_group_per_studio'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='contentasset',
|
||||
index=models.Index(fields=['kind'], name='studio_cont_kind_c87ed2_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='contentasset',
|
||||
index=models.Index(fields=['release_date'], name='studio_cont_release_cc6f45_idx'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Django models for the video transcoding service."""
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
class JobStatus(models.TextChoices):
|
||||
DRAFT = "draft", "Draft"
|
||||
PENDING = "pending", "Pending"
|
||||
IN_PROGRESS = "in_progress", "In progress"
|
||||
COMPLETED = "completed", "Completed"
|
||||
FAILED = "failed", "Failed"
|
||||
|
||||
|
||||
class StudioQuerySet(models.QuerySet):
|
||||
def for_user(self, user):
|
||||
"""Studios the given user may access through group membership."""
|
||||
if user.is_superuser:
|
||||
return self.all()
|
||||
return self.filter(group__user=user).distinct()
|
||||
|
||||
|
||||
class Studio(models.Model):
|
||||
"""A studio owns an S3 bucket. Members of ``group`` may access it."""
|
||||
name = models.CharField(max_length=255)
|
||||
bucket_name = models.SlugField(max_length=63, unique=True)
|
||||
group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name="studios")
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
objects = StudioQuerySet.as_manager()
|
||||
|
||||
class Meta:
|
||||
ordering = ["bucket_name"]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.name} ({self.bucket_name})"
|
||||
|
||||
def user_has_access(self, user) -> bool:
|
||||
if not user or not user.is_active:
|
||||
return False
|
||||
if user.is_superuser:
|
||||
return True
|
||||
return user.groups.filter(pk=self.group_id).exists()
|
||||
|
||||
|
||||
class APIKey(models.Model):
|
||||
"""API key for bearer token authentication. Only the hash is stored."""
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="api_keys")
|
||||
key_hash = models.CharField(max_length=64, unique=True)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
is_active = models.BooleanField(default=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"API key {self.pk} for {self.user}"
|
||||
|
||||
|
||||
class S3Credential(models.Model):
|
||||
"""Temporary AWS v4 signature credentials for S3 access."""
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="s3_credentials")
|
||||
access_key = models.CharField(max_length=64, unique=True)
|
||||
secret_key = models.CharField(max_length=128)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
expires_at = models.DateTimeField()
|
||||
authorized_key = models.TextField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.access_key
|
||||
|
||||
@property
|
||||
def is_expired(self) -> bool:
|
||||
return timezone.now() >= self.expires_at
|
||||
|
||||
|
||||
class UploadedAsset(models.Model):
|
||||
"""Uploaded video file stored in a studio's bucket."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="uploaded_assets")
|
||||
uploaded_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="uploaded_assets",
|
||||
)
|
||||
filename = models.TextField()
|
||||
size = models.BigIntegerField()
|
||||
s3_path = models.TextField()
|
||||
upload_timestamp = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["studio", "s3_path"], name="unique_asset_path_per_studio"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.studio.bucket_name}/{self.s3_path}"
|
||||
|
||||
|
||||
class UploadStatus(models.TextChoices):
|
||||
ACTIVE = "active", "Active"
|
||||
COMPLETED = "completed", "Completed"
|
||||
ABORTED = "aborted", "Aborted"
|
||||
|
||||
|
||||
class MultipartUpload(models.Model):
|
||||
"""An upload sent in parts, from an S3 client or the browser."""
|
||||
upload_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="multipart_uploads")
|
||||
created_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="multipart_uploads",
|
||||
)
|
||||
key = models.TextField()
|
||||
filename = models.TextField()
|
||||
# Browser uploads declare these. S3 clients don't, so they are null for those.
|
||||
total_size = models.BigIntegerField(null=True, blank=True)
|
||||
part_size = models.BigIntegerField(null=True, blank=True)
|
||||
last_modified = models.BigIntegerField(null=True, blank=True)
|
||||
overwrite = models.BooleanField(default=True)
|
||||
status = models.CharField(max_length=20, choices=UploadStatus.choices, default=UploadStatus.ACTIVE)
|
||||
etag = models.CharField(max_length=64, blank=True, default="")
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.studio.bucket_name}/{self.key} ({self.status})"
|
||||
|
||||
|
||||
class UploadPart(models.Model):
|
||||
"""A received part of a multipart upload."""
|
||||
upload = models.ForeignKey(MultipartUpload, on_delete=models.CASCADE, related_name="parts")
|
||||
part_number = models.PositiveIntegerField()
|
||||
size = models.BigIntegerField()
|
||||
etag = models.CharField(max_length=32)
|
||||
uploaded_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta:
|
||||
ordering = ["part_number"]
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["upload", "part_number"], name="unique_part_per_upload"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"Part {self.part_number} of {self.upload_id}"
|
||||
|
||||
|
||||
class TranscodeProfile(models.Model):
|
||||
"""Named encoding profile (YAML definition) belonging to a studio."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcode_profiles")
|
||||
created_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_profiles",
|
||||
)
|
||||
name = models.CharField(max_length=255)
|
||||
profile_definition = models.TextField()
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["studio", "name"], name="unique_profile_name_per_studio"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
class TranscodeJob(models.Model):
|
||||
"""Requested transcode operation."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcode_jobs")
|
||||
requested_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
|
||||
)
|
||||
asset = models.ForeignKey(UploadedAsset, on_delete=models.CASCADE, related_name="transcode_jobs")
|
||||
profile = models.ForeignKey(
|
||||
TranscodeProfile, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
|
||||
)
|
||||
# Inline profile definitions (or a snapshot of the named profile) used for this job.
|
||||
profile_definition = models.TextField(blank=True, default="")
|
||||
status = models.CharField(max_length=20, choices=JobStatus.choices, default=JobStatus.PENDING)
|
||||
requested_at = models.DateTimeField(default=timezone.now)
|
||||
completed_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"Transcode job {self.pk} ({self.status})"
|
||||
|
||||
|
||||
class PackagingJob(models.Model):
|
||||
"""Requested packaging operation."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="packaging_jobs")
|
||||
requested_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="packaging_jobs",
|
||||
)
|
||||
transcode_job = models.ForeignKey(TranscodeJob, on_delete=models.CASCADE, related_name="packaging_jobs")
|
||||
status = models.CharField(max_length=20, choices=JobStatus.choices, default=JobStatus.PENDING)
|
||||
requested_at = models.DateTimeField(default=timezone.now)
|
||||
completed_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"Packaging job {self.pk} ({self.status})"
|
||||
|
||||
|
||||
class TranscodedAsset(models.Model):
|
||||
"""Output file from a transcode job."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcoded_assets")
|
||||
transcode_job = models.ForeignKey(TranscodeJob, on_delete=models.CASCADE, related_name="transcoded_assets")
|
||||
filename = models.TextField()
|
||||
s3_path = models.TextField()
|
||||
format = models.CharField(max_length=32) # e.g. "mp4", "audio"
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.studio.bucket_name}/{self.s3_path}"
|
||||
|
||||
|
||||
class ContentKind(models.TextChoices):
|
||||
VIDEO = "video", "Video"
|
||||
EPISODE = "episode", "Episode"
|
||||
MOVIE = "movie", "Movie"
|
||||
|
||||
|
||||
class ContentGroupKind(models.TextChoices):
|
||||
SERIES = "series", "Series"
|
||||
COLLECTION = "collection", "Movie collection"
|
||||
|
||||
|
||||
class ContentGroup(models.Model):
|
||||
"""A series of episodes or a collection of related movies within a studio."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="content_groups")
|
||||
kind = models.CharField(max_length=20, choices=ContentGroupKind.choices)
|
||||
title = models.CharField(max_length=255)
|
||||
description = models.TextField(blank=True)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta:
|
||||
ordering = ["title"]
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["studio", "kind", "title"], name="unique_content_group_per_studio"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.title} ({self.get_kind_display()})"
|
||||
|
||||
|
||||
class ContentAsset(models.Model):
|
||||
"""Catalog metadata for an uploaded file."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="content_assets")
|
||||
uploaded_asset = models.ForeignKey(UploadedAsset, on_delete=models.SET_NULL, related_name="content_assets", null=True, blank=True)
|
||||
kind = models.CharField(max_length=20, choices=ContentKind.choices, default=ContentKind.VIDEO)
|
||||
title = models.CharField(max_length=255)
|
||||
description = models.TextField(blank=True)
|
||||
release_date = models.DateField(null=True, blank=True)
|
||||
group = models.ForeignKey(
|
||||
ContentGroup, on_delete=models.SET_NULL, null=True, blank=True, related_name="content_assets",
|
||||
help_text="The series an episode belongs to, or the collection a movie belongs to.",
|
||||
)
|
||||
season_number = models.PositiveIntegerField(null=True, blank=True)
|
||||
episode_number = models.PositiveIntegerField(null=True, blank=True)
|
||||
sequence_number = models.PositiveIntegerField(
|
||||
null=True, blank=True, help_text="Order of a movie within its collection.",
|
||||
)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ["group__title", "season_number", "episode_number", "sequence_number", "title"]
|
||||
indexes = [
|
||||
models.Index(fields=["kind"]),
|
||||
models.Index(fields=["release_date"]),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
def clean(self):
|
||||
errors = {}
|
||||
group = self.group
|
||||
if self.studio_id and self.uploaded_asset_id and self.uploaded_asset.studio_id != self.studio_id:
|
||||
errors["uploaded_asset"] = "The file must belong to the same studio."
|
||||
if group is not None and self.studio_id and group.studio_id != self.studio_id:
|
||||
errors["group"] = "The group must belong to the same studio."
|
||||
if self.kind == ContentKind.EPISODE:
|
||||
if group is None or group.kind != ContentGroupKind.SERIES:
|
||||
errors.setdefault("group", "An episode must belong to a series.")
|
||||
else:
|
||||
for field in ("season_number", "episode_number"):
|
||||
if getattr(self, field) is not None:
|
||||
errors[field] = "Only episodes have season and episode numbers."
|
||||
if group is not None:
|
||||
if self.kind != ContentKind.MOVIE:
|
||||
errors.setdefault("group", "Only episodes and movies can belong to a group.")
|
||||
elif group.kind != ContentGroupKind.COLLECTION:
|
||||
errors.setdefault("group", "A movie can only belong to a movie collection.")
|
||||
if self.sequence_number is not None and (self.kind != ContentKind.MOVIE or group is None):
|
||||
errors["sequence_number"] = "Only movies in a collection have a sequence number."
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Read request bodies in bounded blocks, under both WSGI and ASGI."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
from typing import Iterator, Optional
|
||||
|
||||
from django.core.handlers.wsgi import WSGIRequest
|
||||
from django.http import UnreadablePostError
|
||||
|
||||
from privatestudio.studio.storage import BLOCK_SIZE, WriteResult
|
||||
|
||||
UNSIGNED = "UNSIGNED-PAYLOAD"
|
||||
STREAMING_TRAILER = "STREAMING-UNSIGNED-PAYLOAD-TRAILER"
|
||||
CRC32_HEADER = "x-amz-checksum-crc32"
|
||||
MAX_LINE = 8192
|
||||
|
||||
|
||||
class BodyError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
def _incomplete() -> BodyError:
|
||||
return BodyError(400, "IncompleteBody", "The request body ended early")
|
||||
|
||||
|
||||
class RequestBody:
|
||||
"""
|
||||
Iterate over a request's payload, checking the integrity data sent with it.
|
||||
|
||||
Iterating raises BodyError for a truncated, oversized or mismatching body, so
|
||||
consume it completely before publishing anything. ``verify_write`` checks the
|
||||
CRC32, which is only computed by the code that writes the blocks.
|
||||
"""
|
||||
|
||||
def __init__(self, request, max_bytes: Optional[int] = None, verify_hash: bool = True):
|
||||
self.max_bytes = max_bytes
|
||||
self._crc32: Optional[str] = request.headers.get(CRC32_HEADER)
|
||||
self._trailer_expected = False
|
||||
self._sha256: Optional[str] = None
|
||||
|
||||
payload = request.headers.get("x-amz-content-sha256") if verify_hash else None
|
||||
encodings = [e.strip().lower() for e in request.headers.get("Content-Encoding", "").split(",")]
|
||||
self._aws_chunked = payload == STREAMING_TRAILER or (
|
||||
payload in (None, UNSIGNED) and "aws-chunked" in encodings
|
||||
)
|
||||
if self._aws_chunked:
|
||||
trailer = request.headers.get("x-amz-trailer", "").strip().lower()
|
||||
if trailer not in ("", CRC32_HEADER):
|
||||
raise BodyError(501, "NotImplemented", f"Trailer {trailer} is not supported")
|
||||
self._trailer_expected = bool(trailer)
|
||||
elif payload and payload.startswith("STREAMING-"):
|
||||
raise BodyError(501, "NotImplemented", f"{payload} is not supported")
|
||||
elif payload and payload != UNSIGNED:
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", payload):
|
||||
raise BodyError(400, "InvalidRequest", "Invalid X-Amz-Content-Sha256")
|
||||
self._sha256 = payload
|
||||
|
||||
self._length = self._content_length(request)
|
||||
self._decoded_length = None
|
||||
if self._aws_chunked and "x-amz-decoded-content-length" in request.headers:
|
||||
self._decoded_length = self._parse_length(request.headers["x-amz-decoded-content-length"])
|
||||
declared = self._decoded_length if self._aws_chunked else self._length
|
||||
if max_bytes is not None and declared is not None and declared > max_bytes:
|
||||
raise self._too_large()
|
||||
self._read = self._reader(request)
|
||||
|
||||
@staticmethod
|
||||
def _parse_length(value: str) -> int:
|
||||
if not re.fullmatch(r"[0-9]{1,19}", value):
|
||||
raise BodyError(400, "InvalidRequest", "Invalid content length")
|
||||
return int(value)
|
||||
|
||||
def _content_length(self, request) -> Optional[int]:
|
||||
value = request.META.get("CONTENT_LENGTH")
|
||||
if value not in (None, ""):
|
||||
return self._parse_length(str(value))
|
||||
if "chunked" in request.headers.get("Transfer-Encoding", "").lower():
|
||||
return None
|
||||
return 0
|
||||
|
||||
def _reader(self, request):
|
||||
if self._length is None and isinstance(request, WSGIRequest):
|
||||
# Django limits a WSGI stream without Content-Length to 0 bytes. Reading the
|
||||
# raw input is only safe when the server guarantees that it ends.
|
||||
if not request.environ.get("wsgi.input_terminated"):
|
||||
raise BodyError(411, "MissingContentLength", "Content-Length is required")
|
||||
return request.environ["wsgi.input"].read
|
||||
return request.read
|
||||
|
||||
def _too_large(self) -> BodyError:
|
||||
return BodyError(413, "EntityTooLarge", f"The body is larger than {self.max_bytes} bytes")
|
||||
|
||||
def _raw(self) -> Iterator[bytes]:
|
||||
received = 0
|
||||
while True:
|
||||
try:
|
||||
block = self._read(BLOCK_SIZE)
|
||||
except UnreadablePostError as e:
|
||||
raise _incomplete() from e
|
||||
if not block:
|
||||
break
|
||||
received += len(block)
|
||||
yield block
|
||||
if self._length is not None and received != self._length:
|
||||
raise _incomplete()
|
||||
|
||||
def _decoded(self) -> Iterator[bytes]:
|
||||
"""Decode aws-chunked framing: ``size\\r\\n data\\r\\n ... 0\\r\\n trailers \\r\\n``."""
|
||||
raw = self._raw()
|
||||
buffer = bytearray()
|
||||
|
||||
def fill():
|
||||
block = next(raw, None)
|
||||
if block is None:
|
||||
raise _incomplete()
|
||||
buffer.extend(block)
|
||||
|
||||
def line() -> bytes:
|
||||
while (end := buffer.find(b"\r\n")) < 0:
|
||||
if len(buffer) > MAX_LINE:
|
||||
raise BodyError(400, "InvalidRequest", "Malformed aws-chunked body")
|
||||
fill()
|
||||
value = bytes(buffer[:end])
|
||||
del buffer[:end + 2]
|
||||
return value
|
||||
|
||||
total = 0
|
||||
while True:
|
||||
size_text = line().split(b";")[0].strip()
|
||||
if not re.fullmatch(rb"[0-9a-fA-F]{1,16}", size_text):
|
||||
raise BodyError(400, "InvalidRequest", "Malformed aws-chunked body")
|
||||
remaining = int(size_text, 16)
|
||||
if remaining == 0:
|
||||
break
|
||||
while remaining:
|
||||
if not buffer:
|
||||
fill()
|
||||
data = bytes(buffer[:remaining])
|
||||
del buffer[:len(data)]
|
||||
remaining -= len(data)
|
||||
total += len(data)
|
||||
yield data
|
||||
if line():
|
||||
raise BodyError(400, "InvalidRequest", "Malformed aws-chunked body")
|
||||
|
||||
found = False
|
||||
while trailer := line():
|
||||
name, _, value = trailer.partition(b":")
|
||||
if name.strip().lower() == CRC32_HEADER.encode():
|
||||
found = True
|
||||
self._crc32 = value.strip().decode("ascii", "replace")
|
||||
if self._trailer_expected and not found:
|
||||
raise _incomplete()
|
||||
for _ in raw: # Reach the end, which checks the length.
|
||||
pass
|
||||
if self._decoded_length is not None and total != self._decoded_length:
|
||||
raise _incomplete()
|
||||
|
||||
def __iter__(self) -> Iterator[bytes]:
|
||||
sha256 = hashlib.sha256() if self._sha256 else None
|
||||
total = 0
|
||||
for block in self._decoded() if self._aws_chunked else self._raw():
|
||||
total += len(block)
|
||||
if self.max_bytes is not None and total > self.max_bytes:
|
||||
raise self._too_large()
|
||||
if sha256:
|
||||
sha256.update(block)
|
||||
yield block
|
||||
if sha256 and not hmac.compare_digest(sha256.hexdigest(), self._sha256):
|
||||
raise BodyError(400, "XAmzContentSHA256Mismatch", "The body does not match X-Amz-Content-Sha256")
|
||||
|
||||
def verify_write(self, result: WriteResult) -> None:
|
||||
if self._crc32 is None:
|
||||
return
|
||||
try:
|
||||
expected = base64.b64decode(self._crc32, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
expected = b""
|
||||
if expected != result.crc32.to_bytes(4, "big"):
|
||||
raise BodyError(400, "BadDigest", "The body does not match its CRC32 checksum")
|
||||
|
||||
|
||||
class BodyReader:
|
||||
"""Give a RequestBody the ``read(size)`` method that Django's form parser needs."""
|
||||
|
||||
def __init__(self, body: RequestBody):
|
||||
self._blocks = iter(body)
|
||||
self._buffer = b""
|
||||
|
||||
def read(self, size: int = BLOCK_SIZE) -> bytes:
|
||||
while len(self._buffer) < size:
|
||||
block = next(self._blocks, None)
|
||||
if block is None:
|
||||
break
|
||||
self._buffer += block
|
||||
data, self._buffer = self._buffer[:size], self._buffer[size:]
|
||||
return data
|
||||
|
||||
def finish(self) -> None:
|
||||
"""Consume what is left, so that the integrity checks run."""
|
||||
self._buffer = b""
|
||||
for _ in self._blocks:
|
||||
pass
|
||||
|
||||
|
||||
def read_small_body(request, limit: int) -> bytes:
|
||||
return b"".join(RequestBody(request, max_bytes=limit))
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Shared helpers for API routers."""
|
||||
import yaml
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
|
||||
def get_studio_for_user(user, bucket: str) -> Studio:
|
||||
"""Resolve a bucket name to a Studio the user may access (404/403 otherwise)."""
|
||||
studio = Studio.objects.filter(bucket_name=bucket).first()
|
||||
if studio is None:
|
||||
raise HttpError(404, f"Studio '{bucket}' not found")
|
||||
if not studio.user_has_access(user):
|
||||
raise HttpError(403, f"No access to studio '{bucket}'")
|
||||
return studio
|
||||
|
||||
|
||||
def parse_yaml_body(request) -> dict:
|
||||
"""Parse the raw request body as a YAML mapping (400 on failure)."""
|
||||
try:
|
||||
data = yaml.safe_load(request.body.decode("utf-8") or "")
|
||||
except (yaml.YAMLError, UnicodeDecodeError) as e:
|
||||
raise HttpError(400, f"Invalid YAML: {e}")
|
||||
if not isinstance(data, dict):
|
||||
raise HttpError(400, "Request body must be a YAML mapping")
|
||||
return data
|
||||
@@ -0,0 +1,51 @@
|
||||
"""API key management endpoints."""
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.auth import create_api_key, revoke_api_key
|
||||
from privatestudio.studio.models import APIKey
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class APIKeyCreateResponse(Schema):
|
||||
id: int
|
||||
key: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class APIKeyListItem(Schema):
|
||||
id: int
|
||||
created_at: str
|
||||
is_active: bool
|
||||
|
||||
|
||||
class MessageResponse(Schema):
|
||||
message: str
|
||||
|
||||
|
||||
@router.post("/keys", response=APIKeyCreateResponse)
|
||||
def create_api_key_endpoint(request):
|
||||
"""Create a new API key for the authenticated user."""
|
||||
plain_key, api_key = create_api_key(request.auth)
|
||||
return {"id": api_key.id, "key": plain_key, "created_at": api_key.created_at.isoformat()}
|
||||
|
||||
|
||||
@router.get("/keys", response=list[APIKeyListItem])
|
||||
def list_api_keys(request):
|
||||
"""List all API keys for the authenticated user."""
|
||||
return [
|
||||
{"id": key.id, "created_at": key.created_at.isoformat(), "is_active": key.is_active}
|
||||
for key in APIKey.objects.filter(user=request.auth).order_by("id")
|
||||
]
|
||||
|
||||
|
||||
@router.delete("/keys/{key_id}", response=MessageResponse)
|
||||
def revoke_api_key_endpoint(request, key_id: int):
|
||||
"""Revoke an API key (mark it as inactive)."""
|
||||
api_key = get_object_or_404(APIKey, pk=key_id)
|
||||
if api_key.user_id != request.auth.id:
|
||||
raise HttpError(403, "Cannot revoke someone else's API key")
|
||||
revoke_api_key(api_key)
|
||||
return {"message": "API key revoked"}
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Transcode profile management endpoints (scoped to a studio)."""
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import TranscodeProfile
|
||||
from privatestudio.studio.routers.common import get_studio_for_user, parse_yaml_body
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class ProfileResponse(Schema):
|
||||
id: int
|
||||
name: str
|
||||
profile_definition: str
|
||||
created_at: str
|
||||
|
||||
|
||||
def _profile_response(profile: TranscodeProfile) -> dict:
|
||||
return {
|
||||
"id": profile.id,
|
||||
"name": profile.name,
|
||||
"profile_definition": profile.profile_definition,
|
||||
"created_at": profile.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/studios/{bucket}/profiles", response=ProfileResponse)
|
||||
def create_profile(request, bucket: str, name: str):
|
||||
"""
|
||||
Create a new transcode profile.
|
||||
|
||||
The request body must contain the YAML profile definition.
|
||||
"""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
profile_data = parse_yaml_body(request)
|
||||
if "profiles" not in profile_data:
|
||||
raise HttpError(400, "Profile definition must contain a 'profiles' section")
|
||||
|
||||
if TranscodeProfile.objects.filter(studio=studio, name=name).exists():
|
||||
raise HttpError(409, f"Profile '{name}' already exists")
|
||||
|
||||
profile = TranscodeProfile.objects.create(
|
||||
studio=studio,
|
||||
created_by=request.auth,
|
||||
name=name,
|
||||
profile_definition=request.body.decode("utf-8"),
|
||||
)
|
||||
return _profile_response(profile)
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/profiles", response=list[ProfileResponse])
|
||||
def list_profiles(request, bucket: str):
|
||||
"""List all transcode profiles for the studio."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
return [_profile_response(p) for p in studio.transcode_profiles.order_by("id")]
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/profiles/{profile_id}", response=ProfileResponse)
|
||||
def get_profile(request, bucket: str, profile_id: int):
|
||||
"""Get a specific transcode profile."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
return _profile_response(get_object_or_404(TranscodeProfile, pk=profile_id, studio=studio))
|
||||
@@ -0,0 +1,27 @@
|
||||
"""S3 credential generation endpoint."""
|
||||
from ninja import Router, Schema
|
||||
|
||||
from privatestudio.studio.s3_credentials import create_s3_credential
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class S3KeyResponse(Schema):
|
||||
access_key: str
|
||||
secret_key: str
|
||||
expires_at: str
|
||||
|
||||
|
||||
@router.post("/s3keys", response=S3KeyResponse)
|
||||
def generate_s3_keys(request):
|
||||
"""
|
||||
Generate temporary AWS v4 signature credentials for S3 access.
|
||||
|
||||
The secret key is only returned here.
|
||||
"""
|
||||
credential = create_s3_credential(request.auth)
|
||||
return {
|
||||
"access_key": credential.access_key,
|
||||
"secret_key": credential.secret_key,
|
||||
"expires_at": credential.expires_at.isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
"""YAML-based transcode job request endpoints (scoped to a studio)."""
|
||||
from typing import Optional
|
||||
|
||||
import yaml
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import TranscodeJob, TranscodeProfile, UploadedAsset
|
||||
from privatestudio.studio.routers.common import get_studio_for_user, parse_yaml_body
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class TranscodeJobResponse(Schema):
|
||||
id: int
|
||||
asset_id: int
|
||||
profile_id: Optional[int]
|
||||
status: str
|
||||
requested_at: str
|
||||
|
||||
|
||||
def _job_response(job: TranscodeJob) -> dict:
|
||||
return {
|
||||
"id": job.id,
|
||||
"asset_id": job.asset_id,
|
||||
"profile_id": job.profile_id,
|
||||
"status": job.status,
|
||||
"requested_at": job.requested_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/studios/{bucket}/transcode", response=TranscodeJobResponse)
|
||||
def request_transcode(request, bucket: str):
|
||||
"""
|
||||
Request a transcode job with a YAML definition in the request body.
|
||||
|
||||
```yaml
|
||||
asset: "video.mp4" # Asset key, filename or ID
|
||||
profile: "hd-profile" # Profile name, or an inline profile definition
|
||||
```
|
||||
"""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
request_data = parse_yaml_body(request)
|
||||
|
||||
asset_ref = request_data.get("asset")
|
||||
if not asset_ref:
|
||||
raise HttpError(400, "Request must specify 'asset'")
|
||||
|
||||
assets = UploadedAsset.objects.filter(studio=studio)
|
||||
if isinstance(asset_ref, int):
|
||||
asset = assets.filter(pk=asset_ref).first()
|
||||
else:
|
||||
asset_ref = str(asset_ref)
|
||||
asset = assets.filter(s3_path=asset_ref).first() or assets.filter(filename=asset_ref).first()
|
||||
if asset is None:
|
||||
raise HttpError(404, f"Asset '{asset_ref}' not found")
|
||||
|
||||
profile_ref = request_data.get("profile")
|
||||
if not profile_ref:
|
||||
raise HttpError(400, "Request must specify 'profile'")
|
||||
|
||||
profile = None
|
||||
if isinstance(profile_ref, str):
|
||||
profile = TranscodeProfile.objects.filter(studio=studio, name=profile_ref).first()
|
||||
if profile is None:
|
||||
raise HttpError(404, f"Profile '{profile_ref}' not found")
|
||||
profile_definition = profile.profile_definition
|
||||
elif isinstance(profile_ref, dict):
|
||||
if "profiles" not in profile_ref:
|
||||
raise HttpError(400, "Inline profile must contain a 'profiles' section")
|
||||
profile_definition = yaml.safe_dump(profile_ref)
|
||||
else:
|
||||
raise HttpError(400, "Profile must be a string (name) or object (definition)")
|
||||
|
||||
job = TranscodeJob.objects.create(
|
||||
studio=studio,
|
||||
requested_by=request.auth,
|
||||
asset=asset,
|
||||
profile=profile,
|
||||
profile_definition=profile_definition,
|
||||
)
|
||||
return _job_response(job)
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/transcode/{job_id}", response=TranscodeJobResponse)
|
||||
def get_transcode_job(request, bucket: str, job_id: int):
|
||||
"""Get the status of a transcode job."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
return _job_response(get_object_or_404(TranscodeJob, pk=job_id, studio=studio))
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/transcode", response=list[TranscodeJobResponse])
|
||||
def list_transcode_jobs(request, bucket: str, status: Optional[str] = None):
|
||||
"""List transcode jobs for the studio."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
jobs = studio.transcode_jobs.order_by("id")
|
||||
if status:
|
||||
jobs = jobs.filter(status=status)
|
||||
return [_job_response(job) for job in jobs]
|
||||
@@ -0,0 +1,28 @@
|
||||
"""User information endpoint."""
|
||||
from ninja import Router, Schema
|
||||
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class StudioInfo(Schema):
|
||||
name: str
|
||||
bucket: str
|
||||
|
||||
|
||||
class UserInfoResponse(Schema):
|
||||
user_id: int
|
||||
username: str
|
||||
studios: list[StudioInfo]
|
||||
|
||||
|
||||
@router.get("/userinfo", response=UserInfoResponse)
|
||||
def get_user_info(request):
|
||||
"""Get information about the current user and the studios they can access."""
|
||||
user = request.auth
|
||||
return {
|
||||
"user_id": user.id,
|
||||
"username": user.get_username(),
|
||||
"studios": [{"name": s.name, "bucket": s.bucket_name} for s in Studio.objects.for_user(user)],
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
"""AWS v4 signature verification and credential management."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils import timezone
|
||||
|
||||
from privatestudio.studio.models import S3Credential
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def generate_access_key() -> str:
|
||||
"""Generate a random access key (AWS-like format)."""
|
||||
# AWS access keys are 20 chars, alphanumeric starting with AKIA
|
||||
random_part = secrets.token_urlsafe(15).replace("-", "").replace("_", "")[:15]
|
||||
return f"AKIA{random_part.upper()}"
|
||||
|
||||
|
||||
def generate_secret_key() -> str:
|
||||
"""Generate a random secret key (AWS-like format)."""
|
||||
# AWS secret keys are 40 chars, base64-encoded
|
||||
return secrets.token_urlsafe(32).replace("-", "").replace("_", "")[:40]
|
||||
|
||||
|
||||
def create_s3_credential(user, ttl_hours: Optional[int] = None) -> S3Credential:
|
||||
"""
|
||||
Create temporary S3 credentials for a user.
|
||||
|
||||
The returned credential carries the secret key; it is only shown to the
|
||||
user once, at creation time.
|
||||
"""
|
||||
if ttl_hours is None:
|
||||
ttl_hours = settings.PRIVATESTUDIO_S3_CREDENTIAL_TTL_HOURS
|
||||
now = timezone.now()
|
||||
return S3Credential.objects.create(
|
||||
user=user,
|
||||
access_key=generate_access_key(),
|
||||
secret_key=generate_secret_key(),
|
||||
created_at=now,
|
||||
expires_at=now + timedelta(hours=ttl_hours),
|
||||
)
|
||||
|
||||
|
||||
def get_s3_credential(access_key: str) -> Optional[S3Credential]:
|
||||
"""Retrieve a non-expired S3 credential by access key."""
|
||||
return S3Credential.objects.filter(access_key=access_key, expires_at__gt=timezone.now()).first()
|
||||
|
||||
|
||||
def cleanup_expired_credentials() -> int:
|
||||
"""Delete all expired S3 credentials. Returns count of deleted credentials."""
|
||||
deleted, _ = S3Credential.objects.filter(expires_at__lte=timezone.now()).delete()
|
||||
return deleted
|
||||
|
||||
|
||||
def sign_string(key: str, msg: str) -> str:
|
||||
"""Create an HMAC-SHA256 signature."""
|
||||
return hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def sign_string_bytes(key: bytes, msg: str) -> bytes:
|
||||
"""Create an HMAC-SHA256 signature (returns bytes)."""
|
||||
return hmac.new(key, msg.encode(), hashlib.sha256).digest()
|
||||
|
||||
|
||||
def verify_aws_v4_signature(
|
||||
auth_header: str,
|
||||
method: str,
|
||||
path: str,
|
||||
query_string: str,
|
||||
headers: dict,
|
||||
secret_key: str,
|
||||
) -> bool:
|
||||
"""
|
||||
Verify an AWS v4 signature.
|
||||
|
||||
The payload is covered by the signed X-Amz-Content-Sha256 header. The code
|
||||
that reads the body must check the body against it (see request_body.py).
|
||||
|
||||
Args:
|
||||
auth_header: The Authorization header value
|
||||
method: HTTP method (GET, PUT, POST, DELETE)
|
||||
path: Decoded request path
|
||||
query_string: Query string
|
||||
headers: Request headers dict
|
||||
secret_key: The secret key to verify against
|
||||
|
||||
Returns:
|
||||
True if signature is valid, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Parse Authorization header
|
||||
# Format: AWS4-HMAC-SHA256 Credential=<access_key>/<date>/<region>/s3/aws4_request, SignedHeaders=<headers>, Signature=<signature>
|
||||
if not auth_header or not auth_header.startswith("AWS4-HMAC-SHA256"):
|
||||
return False
|
||||
|
||||
parts = auth_header.split(", ")
|
||||
if len(parts) != 3:
|
||||
return False
|
||||
|
||||
# Extract credential, signed headers, and signature
|
||||
cred_part = parts[0].split("Credential=")[1]
|
||||
signed_headers_part = parts[1].split("SignedHeaders=")[1]
|
||||
signature = parts[2].split("Signature=")[1]
|
||||
|
||||
# Parse credential
|
||||
cred_parts = cred_part.split("/")
|
||||
if len(cred_parts) < 5:
|
||||
return False
|
||||
|
||||
access_key = cred_parts[0]
|
||||
amz_date = cred_parts[1] # YYYYMMDD format
|
||||
region = cred_parts[2]
|
||||
|
||||
# Get X-Amz-Date header to extract full timestamp
|
||||
amz_date_header = None
|
||||
for key, value in headers.items():
|
||||
if key.lower() == "x-amz-date":
|
||||
amz_date_header = value
|
||||
break
|
||||
|
||||
if not amz_date_header:
|
||||
return False
|
||||
|
||||
# Calculate the canonical request
|
||||
canonical_request = _build_canonical_request(
|
||||
method,
|
||||
path,
|
||||
query_string,
|
||||
headers,
|
||||
signed_headers_part,
|
||||
)
|
||||
|
||||
# Create string to sign with the full timestamp from X-Amz-Date
|
||||
string_to_sign = _build_string_to_sign(amz_date, amz_date_header, region, canonical_request)
|
||||
|
||||
# Calculate signature
|
||||
kSecret = f"AWS4{secret_key}".encode()
|
||||
kDate = sign_string_bytes(kSecret, amz_date)
|
||||
kRegion = sign_string_bytes(kDate, region)
|
||||
kService = sign_string_bytes(kRegion, "s3")
|
||||
kSigning = sign_string_bytes(kService, "aws4_request")
|
||||
|
||||
calculated_signature = hmac.new(
|
||||
kSigning, string_to_sign.encode(), hashlib.sha256
|
||||
).hexdigest()
|
||||
|
||||
# Compare signatures using constant-time comparison
|
||||
return hmac.compare_digest(calculated_signature, signature)
|
||||
|
||||
except ValueError as e:
|
||||
logger.warning("Rejected v4 signature: %s", e)
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error verifying v4 signature: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _build_canonical_request(
|
||||
method: str,
|
||||
path: str,
|
||||
query_string: str,
|
||||
headers: dict,
|
||||
signed_headers: str,
|
||||
) -> str:
|
||||
"""Build the canonical request for AWS v4 signing."""
|
||||
# Canonical request format:
|
||||
# CanonicalRequest =
|
||||
# HTTPMethod + '\n' +
|
||||
# CanonicalURI + '\n' +
|
||||
# CanonicalQueryString + '\n' +
|
||||
# CanonicalHeaders + '\n' +
|
||||
# SignedHeaders + '\n' +
|
||||
# HashedPayload
|
||||
|
||||
# Normalize path
|
||||
canonical_uri = _normalize_path(path)
|
||||
|
||||
# Normalize query string
|
||||
canonical_query_string = _normalize_query_string(query_string)
|
||||
|
||||
# Build canonical headers
|
||||
canonical_headers = _build_canonical_headers(headers, signed_headers)
|
||||
|
||||
# The body hash is declared by the client. It must be signed, or it proves nothing.
|
||||
body_hash = None
|
||||
for key, value in headers.items():
|
||||
if key.lower() == "x-amz-content-sha256":
|
||||
body_hash = value
|
||||
break
|
||||
if not body_hash or "x-amz-content-sha256" not in signed_headers.lower().split(";"):
|
||||
raise ValueError("X-Amz-Content-Sha256 must be present and signed")
|
||||
|
||||
canonical_request = (
|
||||
f"{method}\n"
|
||||
f"{canonical_uri}\n"
|
||||
f"{canonical_query_string}\n"
|
||||
f"{canonical_headers}\n"
|
||||
f"{signed_headers}\n"
|
||||
f"{body_hash}"
|
||||
)
|
||||
|
||||
return canonical_request
|
||||
|
||||
|
||||
def _normalize_path(path: str) -> str:
|
||||
"""Normalize path for canonical request."""
|
||||
# Ensure path starts with /
|
||||
if not path:
|
||||
path = "/"
|
||||
elif not path.startswith("/"):
|
||||
path = "/" + path
|
||||
# Clients sign the percent-encoded path, but WSGI and ASGI decode it.
|
||||
return quote(path, safe="/~")
|
||||
|
||||
|
||||
def _normalize_query_string(query_string: str) -> str:
|
||||
"""Normalize query string for canonical request."""
|
||||
if not query_string:
|
||||
return ""
|
||||
|
||||
# Parse and sort query parameters
|
||||
params = []
|
||||
for param in query_string.split("&"):
|
||||
if "=" in param:
|
||||
key, value = param.split("=", 1)
|
||||
params.append((key, value))
|
||||
else:
|
||||
params.append((param, ""))
|
||||
|
||||
# Sort by key
|
||||
params.sort(key=lambda x: x[0])
|
||||
|
||||
# Reconstruct
|
||||
return "&".join(f"{k}={v}" for k, v in params)
|
||||
|
||||
|
||||
def _build_canonical_headers(headers: dict, signed_headers: str) -> str:
|
||||
"""Build canonical headers string."""
|
||||
# Get the headers that were signed
|
||||
signed_header_list = [h.strip().lower() for h in signed_headers.split(";")]
|
||||
|
||||
# Build canonical headers
|
||||
canonical_headers_list = []
|
||||
for header_name in signed_header_list:
|
||||
# Find the header (case-insensitive)
|
||||
header_value = None
|
||||
for key, value in headers.items():
|
||||
if key.lower() == header_name:
|
||||
header_value = value
|
||||
break
|
||||
|
||||
if header_value is not None:
|
||||
# Trim spaces and lowercase header name
|
||||
trimmed_value = " ".join(header_value.split())
|
||||
canonical_headers_list.append(f"{header_name}:{trimmed_value}")
|
||||
|
||||
# Add trailing newline
|
||||
if canonical_headers_list:
|
||||
return "\n".join(canonical_headers_list) + "\n"
|
||||
return ""
|
||||
|
||||
|
||||
def _build_string_to_sign(amz_date: str, amz_date_header: str, region: str, canonical_request: str) -> str:
|
||||
"""Build the string to sign for AWS v4.
|
||||
|
||||
Args:
|
||||
amz_date: Date in YYYYMMDD format (from credential)
|
||||
amz_date_header: Full X-Amz-Date header value (format: YYYYMMDDTHHMMSSZ)
|
||||
region: AWS region
|
||||
canonical_request: The canonical request string
|
||||
"""
|
||||
# StringToSign =
|
||||
# "AWS4-HMAC-SHA256" + "\n" +
|
||||
# timeStampISO8601Format + "\n" +
|
||||
# <Scope> + "\n" +
|
||||
# Hex(SHA256Hash(<CanonicalRequest>))
|
||||
|
||||
canonical_request_hash = hashlib.sha256(canonical_request.encode()).hexdigest()
|
||||
scope = f"{amz_date}/{region}/s3/aws4_request"
|
||||
|
||||
string_to_sign = (
|
||||
f"AWS4-HMAC-SHA256\n"
|
||||
f"{amz_date_header}\n"
|
||||
f"{scope}\n"
|
||||
f"{canonical_request_hash}"
|
||||
)
|
||||
|
||||
return string_to_sign
|
||||
@@ -0,0 +1,288 @@
|
||||
"""S3-compatible object upload/download/delete/list views."""
|
||||
import errno
|
||||
import logging
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from asgiref.sync import sync_to_async
|
||||
from django.core.handlers.asgi import ASGIRequest
|
||||
from django.http import FileResponse, HttpResponse, JsonResponse, StreamingHttpResponse
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views import View
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from privatestudio.studio import uploads
|
||||
from privatestudio.studio.auth import authenticate_s3_request, is_s3_v4_request
|
||||
from privatestudio.studio.models import MultipartUpload, Studio
|
||||
from privatestudio.studio.request_body import BodyError, BodyReader, RequestBody, read_small_body
|
||||
from privatestudio.studio.storage import BLOCK_SIZE, get_storage
|
||||
from privatestudio.studio.uploads import UploadError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
XMLNS = "http://s3.amazonaws.com/doc/2006-03-01/"
|
||||
MAX_COMPLETE_BODY = 4 * 1024 * 1024
|
||||
|
||||
|
||||
def _error(status: int, detail: str, **headers) -> JsonResponse:
|
||||
response = JsonResponse({"detail": detail}, status=status)
|
||||
for name, value in headers.items():
|
||||
response[name] = value
|
||||
return response
|
||||
|
||||
|
||||
def _xml(root: ET.Element, status: int = 200) -> HttpResponse:
|
||||
body = ET.tostring(root, encoding="utf-8", xml_declaration=True)
|
||||
return HttpResponse(body, status=status, content_type="application/xml")
|
||||
|
||||
|
||||
def _xml_result(name: str, fields: dict) -> ET.Element:
|
||||
root = ET.Element(name, xmlns=XMLNS)
|
||||
for tag, value in fields.items():
|
||||
ET.SubElement(root, tag).text = str(value)
|
||||
return root
|
||||
|
||||
|
||||
def _xml_error(status: int, code: str, message: str) -> HttpResponse:
|
||||
root = ET.Element("Error")
|
||||
ET.SubElement(root, "Code").text = code
|
||||
ET.SubElement(root, "Message").text = message
|
||||
return _xml(root, status)
|
||||
|
||||
|
||||
def _is_multipart_call(request) -> bool:
|
||||
return "uploads" in request.GET or "uploadId" in request.GET
|
||||
|
||||
|
||||
def _file_response(request, f):
|
||||
"""Stream an open file in blocks, closing it at the end."""
|
||||
if not isinstance(request, ASGIRequest):
|
||||
return FileResponse(f, content_type="application/octet-stream")
|
||||
|
||||
# Under ASGI, Django reads a synchronous iterator into a list before sending it.
|
||||
async def blocks():
|
||||
try:
|
||||
while block := await sync_to_async(f.read, thread_sensitive=False)(BLOCK_SIZE):
|
||||
yield block
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
f.seek(0, 2)
|
||||
size = f.tell()
|
||||
f.seek(0)
|
||||
response = StreamingHttpResponse(blocks(), content_type="application/octet-stream")
|
||||
response["Content-Length"] = str(size)
|
||||
response._resource_closers.append(f.close)
|
||||
return response
|
||||
|
||||
|
||||
@method_decorator(csrf_exempt, name="dispatch")
|
||||
class S3BaseView(View):
|
||||
"""Authenticate the request and resolve the bucket to a Studio the user can access."""
|
||||
|
||||
http_method_names = ["get", "put", "delete", "head"]
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if request.method.lower() not in self.http_method_names:
|
||||
return self.http_method_not_allowed(request, *args, **kwargs)
|
||||
|
||||
user = authenticate_s3_request(request)
|
||||
if user is None:
|
||||
return _error(401, "Invalid or missing credentials", **{"WWW-Authenticate": "Bearer"})
|
||||
self.user = user
|
||||
|
||||
self.studio = Studio.objects.filter(bucket_name=kwargs["bucket"]).first()
|
||||
if self.studio is None:
|
||||
return _error(404, "Bucket not found")
|
||||
if not self.studio.user_has_access(user):
|
||||
return _error(403, "Access to this bucket is denied")
|
||||
|
||||
self.storage = get_storage()
|
||||
try:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
except (UploadError, BodyError) as e:
|
||||
return self.failure(request, e.status, e.code, e.message)
|
||||
except ValueError as e:
|
||||
return self.failure(request, 400, "InvalidArgument", str(e))
|
||||
except OSError as e:
|
||||
if e.errno not in (errno.ENOSPC, errno.EDQUOT):
|
||||
raise
|
||||
logger.error("Storage is full: %s", e)
|
||||
return self.failure(request, 507, "InsufficientStorage", "The server has run out of storage")
|
||||
|
||||
@staticmethod
|
||||
def failure(request, status, code, message):
|
||||
if _is_multipart_call(request):
|
||||
return _xml_error(status, code, message)
|
||||
return _error(status, message)
|
||||
|
||||
|
||||
class ObjectView(S3BaseView):
|
||||
"""
|
||||
A single object: /s3/<bucket>/<key>.
|
||||
|
||||
Multipart uploads use the same URL with ``uploads`` or ``uploadId`` parameters.
|
||||
"""
|
||||
|
||||
http_method_names = ["get", "put", "post", "delete", "head"]
|
||||
|
||||
def put(self, request, bucket, key):
|
||||
if "uploadId" in request.GET:
|
||||
return self.upload_part(request, key)
|
||||
|
||||
filename = key.split("/")[-1]
|
||||
if request.content_type == "multipart/form-data":
|
||||
# Multipart form upload (backward compatibility)
|
||||
result, filename = self.put_form(request, key, filename)
|
||||
else:
|
||||
# Raw binary upload (boto3 / AWS v4 signature compatibility)
|
||||
body = RequestBody(request)
|
||||
result = self.storage.put_stream(self.studio.bucket_name, key, body, body.verify_write)
|
||||
|
||||
asset = uploads.record_asset(self.studio, self.user, key, filename, result.size)
|
||||
|
||||
if is_s3_v4_request(request):
|
||||
# S3 PutObject response: 200 with ETag header and an empty body
|
||||
response = HttpResponse(status=200)
|
||||
response["ETag"] = f'"{result.md5}"'
|
||||
response["x-amz-version-id"] = str(asset.id)
|
||||
return response
|
||||
|
||||
return JsonResponse({
|
||||
"object_id": asset.id,
|
||||
"key": key,
|
||||
"size": result.size,
|
||||
"filename": asset.filename,
|
||||
})
|
||||
|
||||
def put_form(self, request, key, filename):
|
||||
# Django only parses multipart bodies for POST, so parse PUT bodies here. Large
|
||||
# files are spooled to a temporary file.
|
||||
reader = BodyReader(RequestBody(request))
|
||||
_, files = request.parse_file_upload(request.META, reader)
|
||||
upload = files.get("file")
|
||||
try:
|
||||
reader.finish()
|
||||
if upload is None:
|
||||
raise UploadError(400, "InvalidRequest", "The form has no 'file' field")
|
||||
result = self.storage.put_stream(self.studio.bucket_name, key, upload.chunks(BLOCK_SIZE))
|
||||
return result, upload.name or filename
|
||||
finally:
|
||||
for _, values in files.lists():
|
||||
for value in values:
|
||||
value.close()
|
||||
|
||||
def get(self, request, bucket, key):
|
||||
if "uploadId" in request.GET:
|
||||
return self.list_parts(request, key)
|
||||
f = self.storage.open_object(self.studio.bucket_name, key)
|
||||
if f is None:
|
||||
return _error(404, "Object not found")
|
||||
return _file_response(request, f)
|
||||
|
||||
def head(self, request, bucket, key):
|
||||
size = self.storage.get_object_size(self.studio.bucket_name, key)
|
||||
if size is None:
|
||||
return HttpResponse(status=404)
|
||||
response = HttpResponse(content_type="application/octet-stream")
|
||||
response["Content-Length"] = str(size)
|
||||
return response
|
||||
|
||||
def delete(self, request, bucket, key):
|
||||
if "uploadId" in request.GET:
|
||||
uploads.abort(self.get_upload(request, key))
|
||||
return HttpResponse(status=204)
|
||||
if not self.storage.delete_object(self.studio.bucket_name, key):
|
||||
return _error(404, "Object not found")
|
||||
self.studio.uploaded_assets.filter(s3_path=key).delete()
|
||||
return JsonResponse({"message": "Object deleted"})
|
||||
|
||||
# Multipart uploads
|
||||
|
||||
def post(self, request, bucket, key):
|
||||
if "uploads" in request.GET:
|
||||
upload = uploads.create(self.studio, self.user, key)
|
||||
return _xml(_xml_result("InitiateMultipartUploadResult", {
|
||||
"Bucket": bucket, "Key": key, "UploadId": upload.upload_id,
|
||||
}))
|
||||
if "uploadId" in request.GET:
|
||||
return self.complete_upload(request, bucket, key)
|
||||
return _error(400, "POST needs an 'uploads' or 'uploadId' parameter")
|
||||
|
||||
def get_upload(self, request, key) -> MultipartUpload:
|
||||
try:
|
||||
upload_id = uuid.UUID(request.GET["uploadId"])
|
||||
except ValueError:
|
||||
upload_id = None
|
||||
upload = MultipartUpload.objects.filter(studio=self.studio, key=key, upload_id=upload_id).first()
|
||||
if upload_id is None or upload is None:
|
||||
raise UploadError(404, "NoSuchUpload", "The upload does not exist")
|
||||
return upload
|
||||
|
||||
def upload_part(self, request, key):
|
||||
upload = self.get_upload(request, key)
|
||||
try:
|
||||
number = int(request.GET.get("partNumber", ""))
|
||||
except ValueError:
|
||||
raise UploadError(400, "InvalidArgument", "partNumber must be a number") from None
|
||||
if "x-amz-copy-source" in request.headers:
|
||||
raise UploadError(501, "NotImplemented", "UploadPartCopy is not supported")
|
||||
response = HttpResponse(status=200)
|
||||
response["ETag"] = f'"{uploads.put_part(upload, number, request)}"'
|
||||
return response
|
||||
|
||||
def list_parts(self, request, key):
|
||||
upload = self.get_upload(request, key)
|
||||
if upload.status != "active":
|
||||
raise UploadError(404, "NoSuchUpload", "The upload is no longer active")
|
||||
root = _xml_result("ListPartsResult", {
|
||||
"Bucket": self.studio.bucket_name, "Key": key, "UploadId": upload.upload_id, "IsTruncated": "false",
|
||||
})
|
||||
for part in upload.parts.all():
|
||||
element = ET.SubElement(root, "Part")
|
||||
ET.SubElement(element, "PartNumber").text = str(part.part_number)
|
||||
ET.SubElement(element, "LastModified").text = part.uploaded_at.isoformat()
|
||||
ET.SubElement(element, "ETag").text = f'"{part.etag}"'
|
||||
ET.SubElement(element, "Size").text = str(part.size)
|
||||
return _xml(root)
|
||||
|
||||
def complete_upload(self, request, bucket, key):
|
||||
upload = self.get_upload(request, key)
|
||||
parts = _parse_complete(read_small_body(request, MAX_COMPLETE_BODY))
|
||||
upload = uploads.complete(upload, parts)
|
||||
return _xml(_xml_result("CompleteMultipartUploadResult", {
|
||||
"Location": request.build_absolute_uri(request.path),
|
||||
"Bucket": bucket, "Key": key, "ETag": f'"{upload.etag}"',
|
||||
}))
|
||||
|
||||
|
||||
def _parse_complete(body: bytes) -> list[tuple[int, str]]:
|
||||
malformed = UploadError(400, "MalformedXML", "The request body is not a valid CompleteMultipartUpload")
|
||||
try:
|
||||
text = body.decode("utf-8")
|
||||
# Refuse declarations, so no entity can be expanded.
|
||||
if "<!" in text:
|
||||
raise malformed
|
||||
root = ET.fromstring(text)
|
||||
return [
|
||||
(int(part.findtext("{*}PartNumber")), part.findtext("{*}ETag") or "")
|
||||
for part in root.findall("{*}Part")
|
||||
]
|
||||
except (ET.ParseError, ValueError, TypeError) as e:
|
||||
raise malformed from e
|
||||
|
||||
|
||||
class BucketView(S3BaseView):
|
||||
"""List objects in a bucket: /s3/<bucket>."""
|
||||
|
||||
http_method_names = ["get"]
|
||||
|
||||
def get(self, request, bucket):
|
||||
prefix = request.GET.get("prefix", "")
|
||||
delimiter = request.GET.get("delimiter", "")
|
||||
objects = self.storage.list_objects(self.studio.bucket_name, prefix, delimiter)
|
||||
return JsonResponse({
|
||||
"bucket": self.studio.bucket_name,
|
||||
"prefix": prefix,
|
||||
"contents": [{"key": key} for key in objects],
|
||||
})
|
||||
@@ -0,0 +1,277 @@
|
||||
"""S3-compatible local file storage, organised per studio bucket."""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO, Callable, Iterable, Optional
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
BLOCK_SIZE = 1024 * 1024
|
||||
|
||||
|
||||
class InvalidKey(ValueError):
|
||||
"""The object key cannot be stored."""
|
||||
|
||||
|
||||
class LockBusy(Exception):
|
||||
"""Another request is holding the upload's lock."""
|
||||
|
||||
|
||||
class UploadGone(Exception):
|
||||
"""The upload's working directory no longer exists."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class WriteResult:
|
||||
size: int
|
||||
md5: str
|
||||
crc32: int
|
||||
|
||||
|
||||
class S3FileStorage:
|
||||
"""
|
||||
Local file storage backend with an S3-like interface.
|
||||
|
||||
Data is written in bounded blocks to a work directory on the same filesystem
|
||||
as the buckets, then renamed into place. Work directory names start with a
|
||||
dot, which bucket names (slugs) cannot contain.
|
||||
"""
|
||||
|
||||
def __init__(self, base_path):
|
||||
self.base_path = Path(base_path)
|
||||
self.base_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Paths
|
||||
|
||||
@property
|
||||
def temp_path(self) -> Path:
|
||||
return self.base_path / ".tmp"
|
||||
|
||||
@property
|
||||
def multipart_path(self) -> Path:
|
||||
return self.base_path / ".multipart"
|
||||
|
||||
def _get_bucket_path(self, bucket: str) -> Path:
|
||||
bucket_path = self.base_path / bucket
|
||||
bucket_path.mkdir(parents=True, exist_ok=True)
|
||||
return bucket_path
|
||||
|
||||
def _get_file_path(self, bucket: str, key: str) -> Path:
|
||||
"""Resolve the path for a key, ensuring it stays inside the bucket directory."""
|
||||
bucket_path = self._get_bucket_path(bucket).resolve()
|
||||
file_path = (bucket_path / key).resolve()
|
||||
if file_path != bucket_path and bucket_path not in file_path.parents:
|
||||
raise InvalidKey(f"Invalid key: {key}")
|
||||
return file_path
|
||||
|
||||
def validate_key(self, bucket: str, key: str) -> Path:
|
||||
"""Return the path to write ``key`` to, or raise InvalidKey."""
|
||||
segments = key.split("/")
|
||||
if any(s in ("", ".", "..") for s in segments):
|
||||
raise InvalidKey(f"Invalid key: {key}")
|
||||
if any(len(s.encode("utf-8", "surrogatepass")) > 255 for s in segments):
|
||||
raise InvalidKey("Invalid key: a path segment is longer than 255 bytes")
|
||||
if any(ord(c) < 32 or ord(c) == 127 for c in key):
|
||||
raise InvalidKey("Invalid key: control characters are not allowed")
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_dir():
|
||||
raise InvalidKey(f"Key conflicts with an existing folder: {key}")
|
||||
bucket_path = self._get_bucket_path(bucket).resolve()
|
||||
for parent in file_path.parents:
|
||||
if parent == bucket_path:
|
||||
break
|
||||
if parent.exists() and not parent.is_dir():
|
||||
raise InvalidKey(f"Key conflicts with an existing file: {key}")
|
||||
return file_path
|
||||
|
||||
def _upload_path(self, upload_id) -> Path:
|
||||
return self.multipart_path / str(uuid.UUID(str(upload_id)))
|
||||
|
||||
# Writing
|
||||
|
||||
@staticmethod
|
||||
def _write_file(path: Path, chunks: Iterable[bytes]) -> WriteResult:
|
||||
"""Write chunks to a new file. The caller removes the file on failure."""
|
||||
md5 = hashlib.md5(usedforsecurity=False)
|
||||
crc = size = 0
|
||||
# Not mkstemp: that would leave the published file with mode 0600.
|
||||
with open(path, "xb") as f:
|
||||
for chunk in chunks:
|
||||
f.write(chunk)
|
||||
md5.update(chunk)
|
||||
crc = zlib.crc32(chunk, crc)
|
||||
size += len(chunk)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
return WriteResult(size, md5.hexdigest(), crc)
|
||||
|
||||
def _publish(self, temp: Path, bucket: str, key: str) -> None:
|
||||
file_path = self.validate_key(bucket, key)
|
||||
try:
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(temp, file_path)
|
||||
except (FileExistsError, NotADirectoryError, IsADirectoryError) as e:
|
||||
raise InvalidKey(f"Key conflicts with an existing file or folder: {key}") from e
|
||||
|
||||
def put_stream(
|
||||
self, bucket: str, key: str, chunks: Iterable[bytes],
|
||||
verify: Optional[Callable[[WriteResult], None]] = None,
|
||||
) -> WriteResult:
|
||||
"""
|
||||
Store an object from an iterable of byte blocks.
|
||||
|
||||
An exception from ``chunks`` or ``verify`` leaves any existing object untouched.
|
||||
"""
|
||||
self.validate_key(bucket, key)
|
||||
self.temp_path.mkdir(exist_ok=True)
|
||||
temp = self.temp_path / uuid.uuid4().hex
|
||||
try:
|
||||
result = self._write_file(temp, chunks)
|
||||
if verify:
|
||||
verify(result)
|
||||
self._publish(temp, bucket, key)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
return result
|
||||
|
||||
# Multipart uploads
|
||||
|
||||
def create_upload(self, upload_id) -> None:
|
||||
self._upload_path(upload_id).mkdir(parents=True)
|
||||
|
||||
@contextmanager
|
||||
def lock_upload(self, upload_id, timeout: float = 30):
|
||||
"""
|
||||
Hold an exclusive lock on an upload.
|
||||
|
||||
flock is released by the kernel if the worker dies. It only works while a
|
||||
single host (or a filesystem with working flock) serves the storage.
|
||||
"""
|
||||
try:
|
||||
f = open(self._upload_path(upload_id) / "lock", "ab")
|
||||
except FileNotFoundError:
|
||||
raise UploadGone() from None
|
||||
with f:
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
break
|
||||
except BlockingIOError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise LockBusy() from None
|
||||
time.sleep(0.05)
|
||||
yield
|
||||
|
||||
def stage_part(self, upload_id, chunks: Iterable[bytes]) -> tuple[Path, WriteResult]:
|
||||
"""Write part data to a staging file. The caller publishes or removes it."""
|
||||
temp = self._upload_path(upload_id) / f"{uuid.uuid4().hex}.tmp"
|
||||
try:
|
||||
return temp, self._write_file(temp, chunks)
|
||||
except FileNotFoundError:
|
||||
raise UploadGone() from None
|
||||
except BaseException:
|
||||
temp.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
def _part_path(self, upload_id, part_number: int, etag: str) -> Path:
|
||||
# The name includes the ETag, so a database row always identifies exact content.
|
||||
return self._upload_path(upload_id) / f"{part_number:05d}.{etag}.part"
|
||||
|
||||
def publish_part(self, upload_id, part_number: int, etag: str, staged: Path) -> None:
|
||||
"""Name a staged part. Call with the upload's lock held."""
|
||||
os.replace(staged, self._part_path(upload_id, part_number, etag))
|
||||
|
||||
def remove_replaced_parts(self, upload_id, part_number: int, etag: str) -> None:
|
||||
current = self._part_path(upload_id, part_number, etag)
|
||||
for path in current.parent.glob(f"{part_number:05d}.*.part"):
|
||||
if path != current:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def assemble(self, upload_id, parts: Iterable[tuple[int, str, int]], bucket: str, key: str) -> int:
|
||||
"""
|
||||
Join ``(part_number, etag, size)`` parts in order into the final object.
|
||||
|
||||
Call with the upload's lock held. Parts are kept, so a failed join can be
|
||||
retried. Returns the object size.
|
||||
"""
|
||||
self.validate_key(bucket, key)
|
||||
temp = self._upload_path(upload_id) / f"{uuid.uuid4().hex}.tmp"
|
||||
total = 0
|
||||
try:
|
||||
with open(temp, "xb") as out:
|
||||
for number, etag, size in parts:
|
||||
with open(self._part_path(upload_id, number, etag), "rb") as part:
|
||||
shutil.copyfileobj(part, out, BLOCK_SIZE)
|
||||
total += size
|
||||
if out.tell() != total:
|
||||
raise ValueError(f"Part {number} has the wrong size on disk")
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
self._publish(temp, bucket, key)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
return total
|
||||
|
||||
def remove_upload(self, upload_id) -> None:
|
||||
shutil.rmtree(self._upload_path(upload_id), ignore_errors=True)
|
||||
|
||||
def free_space(self) -> int:
|
||||
return shutil.disk_usage(self.base_path).free
|
||||
|
||||
# Reading, deleting and listing
|
||||
|
||||
def open_object(self, bucket: str, key: str) -> Optional[BinaryIO]:
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_file():
|
||||
return open(file_path, "rb")
|
||||
return None
|
||||
|
||||
def delete_object(self, bucket: str, key: str) -> bool:
|
||||
"""Delete a file. Returns True if deleted, False if not found."""
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_file():
|
||||
file_path.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_objects(self, bucket: str, prefix: str = "", delimiter: str = "") -> list[str]:
|
||||
"""List objects in a bucket, optionally with prefix/delimiter."""
|
||||
bucket_path = self._get_bucket_path(bucket)
|
||||
items = []
|
||||
if delimiter == "/":
|
||||
# Return only direct children
|
||||
for item in bucket_path.iterdir():
|
||||
rel_path = item.relative_to(bucket_path).as_posix()
|
||||
if item.is_dir():
|
||||
rel_path += "/"
|
||||
if not prefix or rel_path.startswith(prefix):
|
||||
items.append(rel_path)
|
||||
else:
|
||||
for item in bucket_path.rglob("*"):
|
||||
if item.is_file():
|
||||
rel_path = item.relative_to(bucket_path).as_posix()
|
||||
if not prefix or rel_path.startswith(prefix):
|
||||
items.append(rel_path)
|
||||
return sorted(items)
|
||||
|
||||
def get_object_size(self, bucket: str, key: str) -> Optional[int]:
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_file():
|
||||
return file_path.stat().st_size
|
||||
return None
|
||||
|
||||
def object_exists(self, bucket: str, key: str) -> bool:
|
||||
return self._get_file_path(bucket, key).is_file()
|
||||
|
||||
|
||||
def get_storage() -> S3FileStorage:
|
||||
"""Return a storage instance rooted at settings.PRIVATESTUDIO_STORAGE_PATH."""
|
||||
return S3FileStorage(settings.PRIVATESTUDIO_STORAGE_PATH)
|
||||
@@ -0,0 +1,11 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block title %}Page not found{% endblock %}
|
||||
|
||||
{% block body_class %}template-404{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Page not found</h1>
|
||||
|
||||
<h2>Sorry, this page could not be found.</h2>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" dir="ltr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Internal server error</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>Internal server error</h1>
|
||||
|
||||
<h2>Sorry, there seems to be an error. Please try again soon.</h2>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
{% extends "privatestudio/base_usermanage.html" %}
|
||||
@@ -0,0 +1 @@
|
||||
{% extends "privatestudio/base_usermanage.html" %}
|
||||
@@ -0,0 +1 @@
|
||||
{% extends 'privatestudio/base.html' %}
|
||||
@@ -0,0 +1,67 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>
|
||||
{% block title %}
|
||||
Private Studio
|
||||
{% endblock %}
|
||||
{% block title_suffix %}
|
||||
{% endblock %}
|
||||
</title>
|
||||
{# {% if page.search_description %}#}
|
||||
{# <meta name="description" content="{{ page.search_description }}" />#}
|
||||
{# {% endif %}#}
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="{% static 'favicon.ico' %}" sizes="any" />
|
||||
<link rel="icon" href="{% static 'favicon.svg' %}" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="{% static 'apple-touch-icon.png' %}" />
|
||||
|
||||
{# Force all links in the live preview panel to be opened in a new tab #}
|
||||
{% if request.in_preview_panel %}
|
||||
<base target="_blank">
|
||||
{% endif %}
|
||||
|
||||
{# Global stylesheets #}
|
||||
<link rel="stylesheet" href="{% static 'bundle/main.css' %}" crossorigin="anonymous"/>
|
||||
<script src="{% static 'bundle/tinymce/tinymce.min.js' %}" crossorigin="anonymous"></script>
|
||||
|
||||
{% block extra_css %}
|
||||
{# Override this in templates to add extra stylesheets #}
|
||||
{% endblock %}
|
||||
</head>
|
||||
|
||||
<body class="{% block body_class %}{% endblock %}">
|
||||
{# This JS is at the top of the page because of HTMX order of declaration problems #}
|
||||
<script src="{% static 'bundle/htmx.min.js' %}" crossorigin="anonymous"></script>
|
||||
|
||||
{% include 'privatestudio/nav_header.html' %}
|
||||
|
||||
<div class="container">
|
||||
{% block notifications %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-info">
|
||||
{{ message|linebreaksbr }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
|
||||
{% block outer_content %}
|
||||
{% block content %}{% endblock %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
|
||||
{% include 'privatestudio/nav_footer.html' %}
|
||||
|
||||
{# Global javascript #}
|
||||
<script src="{% static 'bundle/main.js' %}" crossorigin="anonymous"></script>
|
||||
<script src="{% static 'tinymcehelper.js' %}" crossorigin="anonymous"></script>
|
||||
|
||||
{% block extra_js %}
|
||||
{# Override this in templates to add extra javascript #}
|
||||
{% endblock %}
|
||||
{% block extra_body %}
|
||||
{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<script type="application/javascript">
|
||||
tinymce.init({
|
||||
selector: '{{ selector }}',
|
||||
license_key: 'gpl',
|
||||
menubar: '',
|
||||
toolbar: 'undo redo | bold italic | bullist numlist | link emoticons',
|
||||
plugins: [
|
||||
'link', 'emoticons', 'lists'
|
||||
],
|
||||
setup: function (editor) {
|
||||
editor.on('change', function () {
|
||||
tinymce.triggerSave();
|
||||
})
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,28 @@
|
||||
<section class="card my-4">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 card-title">Upload files</h2>
|
||||
<form method="post" data-uploader data-create-url="{% url 'studio:upload_create' studio.bucket_name %}"
|
||||
data-bucket="{{ studio.bucket_name }}" data-user-id="{{ request.user.pk }}">
|
||||
{% csrf_token %}
|
||||
<div class="row g-2 align-items-end">
|
||||
<div class="col-md-5">
|
||||
<label for="upload-files" class="form-label">Files</label>
|
||||
<input id="upload-files" class="form-control" type="file" multiple required>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label for="upload-folder" class="form-label">Folder <span class="text-body-secondary">(optional)</span></label>
|
||||
<input id="upload-folder" class="form-control" name="folder" type="text" placeholder="videos/raw"
|
||||
autocomplete="off">
|
||||
</div>
|
||||
<div class="col-md-2 d-grid">
|
||||
{# Enabled by the uploader script, so the form can't be submitted without it. #}
|
||||
<button type="submit" class="btn btn-primary" disabled>Upload</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="form-text mb-0">
|
||||
Large files upload in parts. If an upload stops, pick the same file again to continue where it left off.
|
||||
</p>
|
||||
<ul class="list-group mt-3" data-upload-list></ul>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1 @@
|
||||
{% extends 'base.html' %}
|
||||
@@ -0,0 +1,15 @@
|
||||
{% extends 'privatestudio/base.html' %}
|
||||
|
||||
{% block outer_content %}
|
||||
<div class="row">
|
||||
<div class="col-sm-3">
|
||||
<ul>
|
||||
<li><a href="{% url 'account_email' %}">Email</a></li>
|
||||
<li><a href="{% url 'account_change_password' %}">Change Password</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="col-sm-9">
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,77 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:detail' studio.bucket_name %}?tab=content">{{ studio.name }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">{{ content_asset.title }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>{{ content_asset.title }}</h1>
|
||||
|
||||
<dl class="row">
|
||||
<dt class="col-sm-3">File</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.uploaded_asset.s3_path }}</dd>
|
||||
<dt class="col-sm-3">Size (bytes)</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.uploaded_asset.size }}</dd>
|
||||
<dt class="col-sm-3">Uploaded</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.uploaded_asset.upload_timestamp }}</dd>
|
||||
<dt class="col-sm-3">Last updated</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.updated_at }}</dd>
|
||||
</dl>
|
||||
|
||||
{% with editing=form.errors %}
|
||||
{% if not editing %}
|
||||
<div id="content-details" class="collapse show content-edit-toggle">
|
||||
<dl class="row">
|
||||
<dt class="col-sm-3">Kind</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.get_kind_display }}</dd>
|
||||
<dt class="col-sm-3">Title</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.title }}</dd>
|
||||
<dt class="col-sm-3">Description</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.description|default:"—"|safe }}</dd>
|
||||
<dt class="col-sm-3">Release date</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.release_date|default:"—" }}</dd>
|
||||
<dt class="col-sm-3">Series / Collection</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.group|default:"—" }}</dd>
|
||||
{% if content_asset.season_number is not None or content_asset.episode_number is not None %}
|
||||
<dt class="col-sm-3">Season</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.season_number|default:"—" }}</dd>
|
||||
<dt class="col-sm-3">Episode</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.episode_number|default:"—" }}</dd>
|
||||
{% endif %}
|
||||
{% if content_asset.sequence_number is not None %}
|
||||
<dt class="col-sm-3">Sequence</dt>
|
||||
<dd class="col-sm-9">{{ content_asset.sequence_number }}</dd>
|
||||
{% endif %}
|
||||
</dl>
|
||||
<button type="button" class="btn btn-primary" data-bs-toggle="collapse" data-bs-target=".content-edit-toggle" aria-controls="content-details content-form">Edit</button>
|
||||
<a href="{% url 'studio:detail' studio.bucket_name %}?tab=content" class="btn btn-link">Back to content</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<form id="content-form" method="post" novalidate{% if not editing %} class="collapse content-edit-toggle"{% endif %}>
|
||||
{% csrf_token %}
|
||||
{% for error in form.non_field_errors %}
|
||||
<div class="alert alert-danger">{{ error }}</div>
|
||||
{% endfor %}
|
||||
{% for field in form %}
|
||||
<div class="mb-3">
|
||||
<label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}</label>
|
||||
{{ field }}
|
||||
{% if field.help_text %}<div class="form-text">{{ field.help_text }}</div>{% endif %}
|
||||
{% for error in field.errors %}<div class="invalid-feedback d-block">{{ error }}</div>{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<button type="submit" class="btn btn-primary">Save</button>
|
||||
{% if editing %}
|
||||
<a href="{{ request.path }}" class="btn btn-secondary">Cancel</a>
|
||||
{% else %}
|
||||
<button type="button" class="btn btn-secondary" data-bs-toggle="collapse" data-bs-target=".content-edit-toggle" aria-controls="content-details content-form">Cancel</button>
|
||||
{% endif %}
|
||||
</form>
|
||||
{% endwith %}
|
||||
{% include 'includes/_tinymce.html' with selector="textarea#id_description" %}
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,30 @@
|
||||
<table class="table table-striped table-sm align-middle">
|
||||
<tr>
|
||||
<th>Title</th>
|
||||
<th>Kind</th>
|
||||
<th>Series / Collection</th>
|
||||
<th>Position</th>
|
||||
<th>Release Date</th>
|
||||
<th>File</th>
|
||||
</tr>
|
||||
{% for content in content_assets %}
|
||||
<tr>
|
||||
<td><a href="{% url 'studio:content_asset' studio.bucket_name content.pk %}">{{ content.title }}</a></td>
|
||||
<td>{{ content.get_kind_display }}</td>
|
||||
<td>{{ content.group.title|default:"" }}</td>
|
||||
<td>
|
||||
{% if content.season_number or content.episode_number %}
|
||||
{% if content.season_number %}S{{ content.season_number }}{% endif %}{% if content.episode_number %}E{{ content.episode_number }}{% endif %}
|
||||
{% elif content.sequence_number %}
|
||||
#{{ content.sequence_number }}
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ content.release_date|default:"" }}</td>
|
||||
<td>{{ content.uploaded_asset.s3_path }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="6">No content yet. Use "Create content" on an uploaded file.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
@@ -0,0 +1,32 @@
|
||||
<table class="table table-striped table-sm align-middle">
|
||||
<tr>
|
||||
<th>File Name</th>
|
||||
<th>Size (bytes)</th>
|
||||
<th>Upload Timestamp</th>
|
||||
<th>Content</th>
|
||||
</tr>
|
||||
{% for asset in uploaded_assets %}
|
||||
<tr>
|
||||
<td>{{ asset.s3_path }}</td>
|
||||
<td>{{ asset.size }}</td>
|
||||
<td>{{ asset.upload_timestamp }}</td>
|
||||
<td>
|
||||
{% if asset.content_asset_id %}
|
||||
<a href="{% url 'studio:content_asset' asset.studio.bucket_name asset.content_asset_id %}">View content</a>
|
||||
{% else %}
|
||||
<form method="post" action="{% url 'studio:content_asset_create' asset.studio.bucket_name asset.id %}" hx-boost="false" class="m-0">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-outline-primary btn-sm">Create content</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
<tr style="display:none;" id="asset_{{ asset.id }}">
|
||||
<td colspan="4">Click to refresh</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="4">No uploaded assets found.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
@@ -0,0 +1,3 @@
|
||||
<div class="privatestudiofooter">
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,32 @@
|
||||
<nav class="studio-navbar navbar navbar-expand-lg navbar-light bg-light navbar-fixed-top justify-content-between">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="/">Private Studio</a>
|
||||
<button class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarContainer" aria-expanded="false" aria-controls="navbarContainer" aria-label="Toggle Navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div id="navbarContainer" class="collapse navbar-collapse justify-content-between">
|
||||
<ul class="navbar-nav">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{% url 'studio:list' %}">Studios</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul class="navbar-nav d-flex">
|
||||
<li class="nav-item dropdown">
|
||||
<a href="#" id="accountDropdown" class="nav-link dropdown-toggle" data-bs-toggle="dropdown" role="button" aria-expanded="false">Account <span class="caret"></span></a>
|
||||
<ul class="dropdown-menu">
|
||||
{% if not request.user.is_authenticated %}
|
||||
<li><a class="dropdown-item" href="{% url "account_login" %}">Login</a></li>
|
||||
{% else %}
|
||||
{% if request.user.is_superuser or request.user.groups.exists %}
|
||||
<li><a class="dropdown-item" href="/admin/">Admin</a></li>
|
||||
{% endif %}
|
||||
{# <li><a class="dropdown-item" href="{% url 'contributor:redirect' %}">Contributor Profile</a></li>#}
|
||||
<li><a class="dropdown-item" href="{% url "account_email" %}">Account Settings</a></li>
|
||||
<li><a class="dropdown-item" href="{% url "account_logout" %}">Logout</a></li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -0,0 +1,34 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<h1>{{ studio.name }}</h1>
|
||||
<p>Bucket Name: {{ studio.bucket_name }}</p>
|
||||
<p>Group: {{ studio.group.name }}</p>
|
||||
|
||||
{% with content_tab=request.GET.tab %}
|
||||
<ul class="nav nav-tabs mb-3" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link{% if content_tab != 'content' %} active{% endif %}" id="files-tab" data-bs-toggle="tab" data-bs-target="#files-pane" type="button" role="tab" aria-controls="files-pane" aria-selected="{% if content_tab != 'content' %}true{% else %}false{% endif %}">Uploaded files</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link{% if content_tab == 'content' %} active{% endif %}" id="content-tab" data-bs-toggle="tab" data-bs-target="#content-pane" type="button" role="tab" aria-controls="content-pane" aria-selected="{% if content_tab == 'content' %}true{% else %}false{% endif %}">Content</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane fade{% if content_tab != 'content' %} show active{% endif %}" id="files-pane" role="tabpanel" aria-labelledby="files-tab" tabindex="0">
|
||||
<div id="uploaded_assets" hx-get="{% url 'studio:uploaded_assets' studio.bucket_name %}" hx-trigger="load, assets-changed from:body" hx-target="#uploaded_assets" hx-swap="innerHTML">
|
||||
<p>Loading uploaded assets...</p>
|
||||
</div>
|
||||
|
||||
{% include "privatestudio/_file_uploader.html" %}
|
||||
</div>
|
||||
<div class="tab-pane fade{% if content_tab == 'content' %} show active{% endif %}" id="content-pane" role="tabpanel" aria-labelledby="content-tab" tabindex="0">
|
||||
<div id="content_assets" hx-get="{% url 'studio:content_assets' studio.bucket_name %}" hx-trigger="load, assets-changed from:body" hx-target="#content_assets" hx-swap="innerHTML">
|
||||
<p>Loading content...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endwith %}
|
||||
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,10 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Studios</h1>
|
||||
<ul>
|
||||
{% for studio in studios %}
|
||||
<li><a href="{% url 'studio:detail' studio.bucket_name %}">{{ studio.name }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,28 @@
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
|
||||
class StudioTestCase(TestCase):
|
||||
"""Creates a user in a group that grants access to the 'demo' studio, plus an API key."""
|
||||
|
||||
def setUp(self):
|
||||
self.storage_dir = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, self.storage_dir, ignore_errors=True)
|
||||
settings_override = override_settings(PRIVATESTUDIO_STORAGE_PATH=self.storage_dir)
|
||||
settings_override.enable()
|
||||
self.addCleanup(settings_override.disable)
|
||||
|
||||
self.group = Group.objects.create(name="demo-team")
|
||||
self.studio = Studio.objects.create(name="Demo", bucket_name="demo", group=self.group)
|
||||
self.user = User.objects.create_user("testuser")
|
||||
self.user.groups.add(self.group)
|
||||
self.key, _ = create_api_key(self.user)
|
||||
|
||||
def auth(self, key=None):
|
||||
return {"Authorization": f"Bearer {key or self.key}"}
|
||||
@@ -0,0 +1,64 @@
|
||||
import re
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.urls import reverse
|
||||
|
||||
from privatestudio.studio.auth import hash_api_key, user_for_api_key
|
||||
from privatestudio.studio.models import APIKey
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
ADD_URL = reverse("admin:studio_apikey_add")
|
||||
LIST_URL = reverse("admin:studio_apikey_changelist")
|
||||
TOKEN_RE = re.compile(r"<code>([^<]+)</code>")
|
||||
|
||||
|
||||
class APIKeyAdminTests(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.client.force_login(User.objects.create_superuser("admin"))
|
||||
self.existing = APIKey.objects.get()
|
||||
self.change_url = reverse("admin:studio_apikey_change", args=[self.existing.pk])
|
||||
|
||||
def form_data(self, **extra):
|
||||
return {
|
||||
"user": self.user.pk,
|
||||
"created_at_0": "2026-01-01",
|
||||
"created_at_1": "12:00:00",
|
||||
"is_active": "on",
|
||||
**extra,
|
||||
}
|
||||
|
||||
def add_key(self):
|
||||
"""Submit the add form and return the token shown to the admin."""
|
||||
response = self.client.post(ADD_URL, self.form_data(), follow=True)
|
||||
self.assertRedirects(response, LIST_URL)
|
||||
return TOKEN_RE.search(response.content.decode()).group(1)
|
||||
|
||||
def test_add_shows_working_token_once(self):
|
||||
token = self.add_key()
|
||||
self.assertEqual(APIKey.objects.get(key_hash=hash_api_key(token)).user, self.user)
|
||||
self.assertEqual(user_for_api_key(token), self.user)
|
||||
self.assertNotContains(self.client.get(LIST_URL), token)
|
||||
|
||||
def test_each_key_is_unique(self):
|
||||
self.assertNotEqual(self.add_key(), self.add_key())
|
||||
self.assertEqual(APIKey.objects.count(), 3)
|
||||
|
||||
def test_submitted_key_hash_is_ignored(self):
|
||||
self.client.post(ADD_URL, self.form_data(key_hash=hash_api_key("chosen")))
|
||||
self.assertIsNone(user_for_api_key("chosen"))
|
||||
|
||||
def test_change_keeps_hash_and_shows_no_token(self):
|
||||
data = self.form_data()
|
||||
del data["is_active"]
|
||||
response = self.client.post(self.change_url, data, follow=True)
|
||||
self.assertRedirects(response, LIST_URL)
|
||||
self.assertIsNone(TOKEN_RE.search(response.content.decode()))
|
||||
original_hash = self.existing.key_hash
|
||||
self.existing.refresh_from_db()
|
||||
self.assertEqual(self.existing.key_hash, original_hash)
|
||||
self.assertFalse(self.existing.is_active)
|
||||
|
||||
def test_key_hash_only_on_change_form(self):
|
||||
self.assertNotContains(self.client.get(ADD_URL), "field-key_hash")
|
||||
self.assertContains(self.client.get(self.change_url), self.existing.key_hash)
|
||||
@@ -0,0 +1,154 @@
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
from privatestudio.studio.models import TranscodeJob, UploadedAsset
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
PROFILE_YAML = "profiles:\n hd:\n resolution: 1280x720\n bitrate: 2500k\n"
|
||||
|
||||
|
||||
class HealthTests(StudioTestCase):
|
||||
def test_health_check(self):
|
||||
response = self.client.get("/health")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"status": "ok"})
|
||||
|
||||
|
||||
class APIKeyTests(StudioTestCase):
|
||||
def test_create_api_key(self):
|
||||
response = self.client.post("/api/keys", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertIn("id", data)
|
||||
self.assertIn("key", data)
|
||||
self.assertIn("created_at", data)
|
||||
|
||||
def test_list_api_keys(self):
|
||||
response = self.client.get("/api/keys", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertEqual(len(data), 1)
|
||||
self.assertIs(data[0]["is_active"], True)
|
||||
|
||||
def test_authentication_required(self):
|
||||
self.assertEqual(self.client.get("/api/keys").status_code, 401)
|
||||
|
||||
def test_invalid_api_key(self):
|
||||
self.assertEqual(self.client.get("/api/keys", headers=self.auth("invalid_key")).status_code, 401)
|
||||
|
||||
def test_revoke_api_key(self):
|
||||
key_id = self.client.get("/api/keys", headers=self.auth()).json()[0]["id"]
|
||||
response = self.client.delete(f"/api/keys/{key_id}", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(self.client.get("/api/keys", headers=self.auth()).status_code, 401)
|
||||
|
||||
def test_cannot_revoke_other_users_key(self):
|
||||
other = User.objects.create_user("other")
|
||||
_, other_key = create_api_key(other)
|
||||
response = self.client.delete(f"/api/keys/{other_key.id}", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
|
||||
class S3KeyTests(StudioTestCase):
|
||||
def test_generate_s3_credentials(self):
|
||||
response = self.client.post("/api/s3keys", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertTrue(data["access_key"].startswith("AKIA"))
|
||||
self.assertGreaterEqual(len(data["secret_key"]), 30)
|
||||
self.assertIn("T", data["expires_at"])
|
||||
|
||||
data2 = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
self.assertNotEqual(data["access_key"], data2["access_key"])
|
||||
self.assertNotEqual(data["secret_key"], data2["secret_key"])
|
||||
|
||||
|
||||
class UserInfoTests(StudioTestCase):
|
||||
def test_userinfo_lists_studios(self):
|
||||
response = self.client.get("/api/userinfo", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {
|
||||
"user_id": self.user.id,
|
||||
"username": "testuser",
|
||||
"studios": [{"name": "Demo", "bucket": "demo"}],
|
||||
})
|
||||
|
||||
|
||||
class ProfileTests(StudioTestCase):
|
||||
def create_profile(self, name="hd-profile", body=PROFILE_YAML, key=None):
|
||||
return self.client.post(
|
||||
f"/api/studios/demo/profiles?name={name}", data=body,
|
||||
content_type="application/yaml", headers=self.auth(key),
|
||||
)
|
||||
|
||||
def test_create_list_get_profile(self):
|
||||
response = self.create_profile()
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
profile_id = response.json()["id"]
|
||||
|
||||
listing = self.client.get("/api/studios/demo/profiles", headers=self.auth()).json()
|
||||
self.assertEqual([p["name"] for p in listing], ["hd-profile"])
|
||||
|
||||
detail = self.client.get(f"/api/studios/demo/profiles/{profile_id}", headers=self.auth())
|
||||
self.assertEqual(detail.status_code, 200)
|
||||
self.assertEqual(detail.json()["profile_definition"], PROFILE_YAML)
|
||||
|
||||
def test_duplicate_profile_conflicts(self):
|
||||
self.create_profile()
|
||||
self.assertEqual(self.create_profile().status_code, 409)
|
||||
|
||||
def test_invalid_profile_yaml(self):
|
||||
self.assertEqual(self.create_profile(body="not: [valid").status_code, 400)
|
||||
self.assertEqual(self.create_profile(body="foo: bar\n").status_code, 400)
|
||||
|
||||
def test_non_member_forbidden(self):
|
||||
outsider = User.objects.create_user("outsider")
|
||||
outsider_key, _ = create_api_key(outsider)
|
||||
self.assertEqual(self.create_profile(key=outsider_key).status_code, 403)
|
||||
|
||||
def test_unknown_studio(self):
|
||||
response = self.client.get("/api/studios/nope/profiles", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
|
||||
class TranscodeTests(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.asset = UploadedAsset.objects.create(
|
||||
studio=self.studio, uploaded_by=self.user, filename="video.mp4", size=10, s3_path="raw/video.mp4",
|
||||
)
|
||||
|
||||
def request_transcode(self, body):
|
||||
return self.client.post(
|
||||
"/api/studios/demo/transcode", data=body, content_type="application/yaml", headers=self.auth(),
|
||||
)
|
||||
|
||||
def test_transcode_with_named_profile(self):
|
||||
self.client.post(
|
||||
"/api/studios/demo/profiles?name=hd", data=PROFILE_YAML,
|
||||
content_type="application/yaml", headers=self.auth(),
|
||||
)
|
||||
response = self.request_transcode("asset: raw/video.mp4\nprofile: hd\n")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
data = response.json()
|
||||
self.assertEqual(data["asset_id"], self.asset.id)
|
||||
self.assertIsNotNone(data["profile_id"])
|
||||
self.assertEqual(data["status"], "pending")
|
||||
|
||||
job_id = data["id"]
|
||||
self.assertEqual(self.client.get(f"/api/studios/demo/transcode/{job_id}", headers=self.auth()).status_code, 200)
|
||||
listing = self.client.get("/api/studios/demo/transcode?status=pending", headers=self.auth()).json()
|
||||
self.assertEqual([j["id"] for j in listing], [job_id])
|
||||
|
||||
def test_transcode_with_inline_profile_by_filename(self):
|
||||
response = self.request_transcode("asset: video.mp4\nprofile:\n profiles:\n sd:\n bitrate: 800k\n")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
self.assertIsNone(response.json()["profile_id"])
|
||||
job = TranscodeJob.objects.get()
|
||||
self.assertIn("800k", job.profile_definition)
|
||||
|
||||
def test_transcode_errors(self):
|
||||
self.assertEqual(self.request_transcode("profile: hd\n").status_code, 400)
|
||||
self.assertEqual(self.request_transcode("asset: missing.mp4\nprofile: hd\n").status_code, 404)
|
||||
self.assertEqual(self.request_transcode("asset: video.mp4\nprofile: missing\n").status_code, 404)
|
||||
self.assertEqual(self.request_transcode("asset: video.mp4\nprofile: [1]\n").status_code, 400)
|
||||
@@ -0,0 +1,191 @@
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.urls import reverse
|
||||
|
||||
from privatestudio.studio.models import (
|
||||
ContentAsset, ContentGroup, ContentGroupKind, ContentKind, Studio, UploadedAsset,
|
||||
)
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
|
||||
class ContentTestCase(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.client.force_login(self.user)
|
||||
self.asset = UploadedAsset.objects.create(
|
||||
studio=self.studio, filename="pilot.mp4", size=10, s3_path="shows/pilot.mp4",
|
||||
)
|
||||
self.series = ContentGroup.objects.create(studio=self.studio, kind=ContentGroupKind.SERIES, title="Show")
|
||||
self.collection = ContentGroup.objects.create(
|
||||
studio=self.studio, kind=ContentGroupKind.COLLECTION, title="Saga",
|
||||
)
|
||||
other_group = Group.objects.create(name="other-team")
|
||||
self.other_studio = Studio.objects.create(name="Other", bucket_name="other", group=other_group)
|
||||
self.other_asset = UploadedAsset.objects.create(
|
||||
studio=self.other_studio, filename="secret.mp4", size=10, s3_path="secret.mp4",
|
||||
)
|
||||
self.other_series = ContentGroup.objects.create(
|
||||
studio=self.other_studio, kind=ContentGroupKind.SERIES, title="Other show",
|
||||
)
|
||||
|
||||
def content(self, asset=None, **fields):
|
||||
asset = asset or self.asset
|
||||
return ContentAsset.objects.create(
|
||||
studio=asset.studio, uploaded_asset=asset, title=fields.pop("title", "T"), **fields,
|
||||
)
|
||||
|
||||
|
||||
class ContentAssetCleanTests(ContentTestCase):
|
||||
def assert_invalid(self, field, **fields):
|
||||
content = ContentAsset(studio=self.studio, uploaded_asset=self.asset, title="T", **fields)
|
||||
with self.assertRaises(ValidationError) as ctx:
|
||||
content.full_clean()
|
||||
self.assertIn(field, ctx.exception.message_dict)
|
||||
|
||||
def assert_valid(self, **fields):
|
||||
ContentAsset(studio=self.studio, uploaded_asset=self.asset, title="T", **fields).full_clean()
|
||||
|
||||
def test_valid_combinations(self):
|
||||
self.assert_valid(kind=ContentKind.VIDEO)
|
||||
self.assert_valid(kind=ContentKind.MOVIE)
|
||||
self.assert_valid(kind=ContentKind.MOVIE, group=self.collection, sequence_number=2)
|
||||
self.assert_valid(kind=ContentKind.EPISODE, group=self.series, season_number=1, episode_number=3)
|
||||
|
||||
def test_episode_needs_series(self):
|
||||
self.assert_invalid("group", kind=ContentKind.EPISODE)
|
||||
self.assert_invalid("group", kind=ContentKind.EPISODE, group=self.collection)
|
||||
|
||||
def test_movie_group_must_be_collection(self):
|
||||
self.assert_invalid("group", kind=ContentKind.MOVIE, group=self.series)
|
||||
|
||||
def test_video_has_no_group(self):
|
||||
self.assert_invalid("group", kind=ContentKind.VIDEO, group=self.series)
|
||||
|
||||
def test_episode_numbers_only_for_episodes(self):
|
||||
self.assert_invalid("season_number", kind=ContentKind.MOVIE, season_number=1)
|
||||
self.assert_invalid("episode_number", kind=ContentKind.VIDEO, episode_number=1)
|
||||
|
||||
def test_sequence_only_for_movies_in_collection(self):
|
||||
self.assert_invalid("sequence_number", kind=ContentKind.MOVIE, sequence_number=1)
|
||||
self.assert_invalid("sequence_number", kind=ContentKind.EPISODE, group=self.series, sequence_number=1)
|
||||
|
||||
def test_group_from_other_studio(self):
|
||||
self.assert_invalid("group", kind=ContentKind.EPISODE, group=self.other_series)
|
||||
|
||||
def test_file_from_other_studio(self):
|
||||
content = ContentAsset(studio=self.studio, uploaded_asset=self.other_asset, title="T")
|
||||
with self.assertRaises(ValidationError) as ctx:
|
||||
content.full_clean()
|
||||
self.assertIn("uploaded_asset", ctx.exception.message_dict)
|
||||
|
||||
|
||||
class UploadedAssetsListTests(ContentTestCase):
|
||||
url = reverse("studio:uploaded_assets", args=["demo"])
|
||||
|
||||
def test_create_button_without_content(self):
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, reverse("studio:content_asset_create", args=["demo", self.asset.pk]))
|
||||
self.assertContains(response, "Create content")
|
||||
|
||||
def test_link_with_content(self):
|
||||
content = self.content()
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, reverse("studio:content_asset", args=["demo", content.pk]))
|
||||
self.assertNotContains(response, "Create content")
|
||||
|
||||
|
||||
class ContentAssetCreateTests(ContentTestCase):
|
||||
def url(self, asset):
|
||||
return reverse("studio:content_asset_create", args=["demo", asset.pk])
|
||||
|
||||
def test_creates_once_and_redirects(self):
|
||||
response = self.client.post(self.url(self.asset))
|
||||
content = ContentAsset.objects.get()
|
||||
self.assertRedirects(response, reverse("studio:content_asset", args=["demo", content.pk]))
|
||||
self.assertEqual(content.title, "pilot")
|
||||
self.assertEqual(content.kind, ContentKind.VIDEO)
|
||||
self.assertEqual(content.studio, self.studio)
|
||||
self.assertRedirects(self.client.post(self.url(self.asset)), response.url)
|
||||
self.assertEqual(ContentAsset.objects.count(), 1)
|
||||
|
||||
def test_get_not_allowed(self):
|
||||
self.assertEqual(self.client.get(self.url(self.asset)).status_code, 405)
|
||||
|
||||
def test_other_studio_asset(self):
|
||||
self.assertEqual(self.client.post(self.url(self.other_asset)).status_code, 404)
|
||||
url = reverse("studio:content_asset_create", args=["other", self.other_asset.pk])
|
||||
self.assertEqual(self.client.post(url).status_code, 403)
|
||||
self.assertFalse(ContentAsset.objects.exists())
|
||||
|
||||
|
||||
class ContentAssetsListTests(ContentTestCase):
|
||||
def test_lists_only_studio_content(self):
|
||||
self.content(title="Mine")
|
||||
self.content(asset=self.other_asset, title="Theirs")
|
||||
response = self.client.get(reverse("studio:content_assets", args=["demo"]))
|
||||
self.assertContains(response, "Mine")
|
||||
self.assertNotContains(response, "Theirs")
|
||||
|
||||
|
||||
class ContentAssetUpdateTests(ContentTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.obj = self.content(title="pilot")
|
||||
self.url = reverse("studio:content_asset", args=["demo", self.obj.pk])
|
||||
|
||||
def test_get_renders_form_with_studio_groups(self):
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, "shows/pilot.mp4")
|
||||
self.assertContains(response, "Show (Series)")
|
||||
self.assertNotContains(response, "Other show")
|
||||
|
||||
def test_post_saves(self):
|
||||
response = self.client.post(self.url, {
|
||||
"kind": ContentKind.EPISODE, "title": "Pilot", "description": "First one",
|
||||
"release_date": "2026-01-15", "group": self.series.pk, "season_number": 1, "episode_number": 1,
|
||||
})
|
||||
self.assertRedirects(response, self.url)
|
||||
self.obj.refresh_from_db()
|
||||
self.assertEqual(self.obj.title, "Pilot")
|
||||
self.assertEqual(self.obj.group, self.series)
|
||||
self.assertEqual(str(self.obj.release_date), "2026-01-15")
|
||||
self.assertEqual((self.obj.season_number, self.obj.episode_number), (1, 1))
|
||||
|
||||
def test_get_shows_details_with_hidden_form(self):
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, 'id="content-details" class="collapse show content-edit-toggle"')
|
||||
self.assertContains(response, 'id="content-form" method="post" novalidate class="collapse content-edit-toggle"')
|
||||
self.assertContains(response, ">Edit</button>")
|
||||
|
||||
def test_post_invalid_shows_errors(self):
|
||||
response = self.client.post(self.url, {"kind": ContentKind.EPISODE, "title": "Renamed"})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "An episode must belong to a series.")
|
||||
# The form is shown open, with no read-only view to switch back to.
|
||||
self.assertNotContains(response, 'id="content-details"')
|
||||
self.assertContains(response, 'id="content-form" method="post" novalidate>')
|
||||
# The heading keeps the saved title; the form keeps the submitted one.
|
||||
self.assertContains(response, "<h1>pilot</h1>")
|
||||
self.assertContains(response, 'value="Renamed"')
|
||||
|
||||
def test_other_studio_group_rejected(self):
|
||||
response = self.client.post(self.url, {
|
||||
"kind": ContentKind.EPISODE, "title": "Pilot", "group": self.other_series.pk,
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.obj.refresh_from_db()
|
||||
self.assertIsNone(self.obj.group)
|
||||
|
||||
def test_other_studio_content_inaccessible(self):
|
||||
theirs = self.content(asset=self.other_asset)
|
||||
self.assertEqual(self.client.get(reverse("studio:content_asset", args=["demo", theirs.pk])).status_code, 404)
|
||||
self.assertEqual(self.client.get(reverse("studio:content_asset", args=["other", theirs.pk])).status_code, 403)
|
||||
|
||||
|
||||
class StudioDetailTabsTests(ContentTestCase):
|
||||
def test_tabs(self):
|
||||
url = reverse("studio:detail", args=["demo"])
|
||||
response = self.client.get(url)
|
||||
self.assertContains(response, reverse("studio:content_assets", args=["demo"]))
|
||||
self.assertContains(response, 'id="files-tab" data-bs-toggle="tab"')
|
||||
self.assertContains(self.client.get(url + "?tab=content"), 'class="nav-link active" id="content-tab"')
|
||||
@@ -0,0 +1,114 @@
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
from privatestudio.studio.models import Studio, UploadedAsset
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
|
||||
class S3InterfaceTests(StudioTestCase):
|
||||
def upload(self, key, content=b"test file content", bucket="demo", api_key=None):
|
||||
body = encode_multipart(BOUNDARY, {"file": SimpleUploadedFile(key.split("/")[-1], content, "video/mp4")})
|
||||
return self.client.put(f"/s3/{bucket}/{key}", data=body, content_type=MULTIPART_CONTENT,
|
||||
headers=self.auth(api_key))
|
||||
|
||||
def test_upload_file(self):
|
||||
response = self.upload("test.mp4")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
data = response.json()
|
||||
self.assertEqual(data["key"], "test.mp4")
|
||||
self.assertEqual(data["size"], len(b"test file content"))
|
||||
self.assertEqual(UploadedAsset.objects.get().uploaded_by, self.user)
|
||||
|
||||
def test_raw_upload_and_reupload_updates_asset(self):
|
||||
for content in (b"first", b"second version"):
|
||||
response = self.client.put("/s3/demo/dir/raw.bin", data=content,
|
||||
content_type="application/octet-stream", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
asset = UploadedAsset.objects.get()
|
||||
self.assertEqual(asset.size, len(b"second version"))
|
||||
self.assertEqual(asset.filename, "raw.bin")
|
||||
|
||||
def test_download_file(self):
|
||||
self.upload("test.mp4")
|
||||
response = self.client.get("/s3/demo/test.mp4", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.getvalue(), b"test file content")
|
||||
|
||||
def test_delete_file(self):
|
||||
self.upload("test.mp4")
|
||||
self.assertEqual(self.client.delete("/s3/demo/test.mp4", headers=self.auth()).status_code, 200)
|
||||
self.assertEqual(self.client.get("/s3/demo/test.mp4", headers=self.auth()).status_code, 404)
|
||||
self.assertFalse(UploadedAsset.objects.exists())
|
||||
|
||||
def test_list_objects(self):
|
||||
self.upload("test1.mp4", b"content1")
|
||||
self.upload("sub/test2.mp4", b"content2")
|
||||
data = self.client.get("/s3/demo", headers=self.auth()).json()
|
||||
self.assertEqual([c["key"] for c in data["contents"]], ["sub/test2.mp4", "test1.mp4"])
|
||||
data = self.client.get("/s3/demo/?delimiter=/", headers=self.auth()).json()
|
||||
self.assertEqual([c["key"] for c in data["contents"]], ["sub/", "test1.mp4"])
|
||||
|
||||
def test_authentication_required(self):
|
||||
self.assertEqual(self.client.get("/s3/demo").status_code, 401)
|
||||
|
||||
def test_unknown_bucket(self):
|
||||
self.assertEqual(self.client.get("/s3/nope", headers=self.auth()).status_code, 404)
|
||||
|
||||
def test_path_traversal_rejected(self):
|
||||
response = self.client.put("/s3/demo/../escape.bin", data=b"x",
|
||||
content_type="application/octet-stream", headers=self.auth())
|
||||
self.assertIn(response.status_code, (400, 404))
|
||||
|
||||
def test_per_studio_isolation(self):
|
||||
self.upload("private.mp4", b"studio content")
|
||||
|
||||
outsider = User.objects.create_user("testuser2")
|
||||
other_group = Group.objects.create(name="other-team")
|
||||
outsider.groups.add(other_group)
|
||||
Studio.objects.create(name="Other", bucket_name="other", group=other_group)
|
||||
outsider_key, _ = create_api_key(outsider)
|
||||
|
||||
self.assertEqual(self.client.get("/s3/demo/private.mp4", headers=self.auth(outsider_key)).status_code, 403)
|
||||
self.assertEqual(self.upload("x.mp4", bucket="other").status_code, 403)
|
||||
self.assertEqual(self.upload("x.mp4", bucket="other", api_key=outsider_key).status_code, 200)
|
||||
|
||||
def test_group_membership_grants_access(self):
|
||||
member = User.objects.create_user("member")
|
||||
member.groups.add(self.group)
|
||||
member_key, _ = create_api_key(member)
|
||||
self.upload("shared.mp4")
|
||||
response = self.client.get("/s3/demo/shared.mp4", headers=self.auth(member_key))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
|
||||
class S3SignatureTests(StudioTestCase):
|
||||
def signed_put(self, url_path, data, access_key, secret_key):
|
||||
from botocore.auth import S3SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
|
||||
request = AWSRequest(method="PUT", url=f"http://testserver{url_path}", data=data)
|
||||
S3SigV4Auth(Credentials(access_key, secret_key), "s3", "us-east-1").add_auth(request)
|
||||
return self.client.put(
|
||||
url_path, data=data, content_type="",
|
||||
headers={
|
||||
"Authorization": request.headers["Authorization"],
|
||||
"X-Amz-Date": request.headers["X-Amz-Date"],
|
||||
"X-Amz-Content-Sha256": request.headers["X-Amz-Content-Sha256"],
|
||||
},
|
||||
)
|
||||
|
||||
def test_upload_with_v4_signature(self):
|
||||
creds = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
response = self.signed_put("/s3/demo/boto3-test.mp4", b"test file content from boto3",
|
||||
creds["access_key"], creds["secret_key"])
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
self.assertIn("ETag", response.headers)
|
||||
self.assertEqual(response.content, b"")
|
||||
|
||||
def test_bad_signature_rejected(self):
|
||||
creds = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
response = self.signed_put("/s3/demo/boto3-test.mp4", b"data", creds["access_key"], "wrong-secret")
|
||||
self.assertEqual(response.status_code, 401)
|
||||
@@ -0,0 +1,417 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management import call_command
|
||||
from django.test import Client, RequestFactory, override_settings
|
||||
|
||||
from privatestudio.studio import uploads
|
||||
from privatestudio.studio.models import MultipartUpload, UploadedAsset, UploadPart, UploadStatus
|
||||
from privatestudio.studio.request_body import BodyError, RequestBody
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
MIB = 1024 * 1024
|
||||
|
||||
|
||||
def aws_chunked(data: bytes, chunk=4, trailer=True) -> bytes:
|
||||
out = b""
|
||||
for i in range(0, len(data), chunk):
|
||||
piece = data[i:i + chunk]
|
||||
out += f"{len(piece):x}\r\n".encode() + piece + b"\r\n"
|
||||
out += b"0\r\n"
|
||||
if trailer:
|
||||
crc = base64.b64encode(zlib.crc32(data).to_bytes(4, "big")).decode()
|
||||
out += f"x-amz-checksum-crc32:{crc}\r\n".encode()
|
||||
return out + b"\r\n"
|
||||
|
||||
|
||||
class RequestBodyTests(StudioTestCase):
|
||||
factory = RequestFactory()
|
||||
|
||||
def put(self, data, **headers):
|
||||
return self.factory.put("/", data=data, content_type="application/octet-stream", headers=headers)
|
||||
|
||||
def read(self, request, **kwargs):
|
||||
return b"".join(RequestBody(request, **kwargs))
|
||||
|
||||
def test_sha256_checked(self):
|
||||
data = b"hello world"
|
||||
self.assertEqual(self.read(self.put(data, **{"X-Amz-Content-Sha256": hashlib.sha256(data).hexdigest()})), data)
|
||||
with self.assertRaises(BodyError) as cm:
|
||||
self.read(self.put(data, **{"X-Amz-Content-Sha256": "0" * 64}))
|
||||
self.assertEqual(cm.exception.code, "XAmzContentSHA256Mismatch")
|
||||
|
||||
def test_aws_chunked_decoded_and_crc_checked(self):
|
||||
data = os.urandom(50)
|
||||
request = self.put(aws_chunked(data), **{
|
||||
"X-Amz-Content-Sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "Content-Encoding": "aws-chunked",
|
||||
"X-Amz-Trailer": "x-amz-checksum-crc32", "X-Amz-Decoded-Content-Length": str(len(data)),
|
||||
})
|
||||
body = RequestBody(request)
|
||||
self.assertEqual(b"".join(body), data)
|
||||
result = mock.Mock(crc32=zlib.crc32(data))
|
||||
body.verify_write(result)
|
||||
result.crc32 ^= 1
|
||||
with self.assertRaises(BodyError):
|
||||
body.verify_write(result)
|
||||
|
||||
def test_aws_chunked_missing_trailer_and_wrong_length(self):
|
||||
headers = {"X-Amz-Content-Sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
|
||||
"X-Amz-Trailer": "x-amz-checksum-crc32"}
|
||||
with self.assertRaises(BodyError):
|
||||
self.read(self.put(aws_chunked(b"abcdef", trailer=False), **headers))
|
||||
with self.assertRaises(BodyError):
|
||||
self.read(self.put(aws_chunked(b"abcdef"), **headers, **{"X-Amz-Decoded-Content-Length": "7"}))
|
||||
with self.assertRaises(BodyError):
|
||||
self.read(self.put(aws_chunked(b"abcdef")[:-8], **headers))
|
||||
|
||||
def test_signed_streaming_rejected(self):
|
||||
with self.assertRaises(BodyError) as cm:
|
||||
RequestBody(self.put(b"x", **{"X-Amz-Content-Sha256": "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"}))
|
||||
self.assertEqual(cm.exception.status, 501)
|
||||
|
||||
def test_size_limit(self):
|
||||
with self.assertRaises(BodyError) as cm:
|
||||
RequestBody(self.put(b"x" * 10), max_bytes=5)
|
||||
self.assertEqual(cm.exception.status, 413)
|
||||
|
||||
def test_truncated_body(self):
|
||||
from django.core.handlers.wsgi import LimitedStream
|
||||
|
||||
request = self.put(b"short")
|
||||
request.META["CONTENT_LENGTH"] = "10"
|
||||
request._stream = LimitedStream(io.BytesIO(b"short"), 10)
|
||||
with self.assertRaises(BodyError) as cm:
|
||||
self.read(request)
|
||||
self.assertEqual(cm.exception.code, "IncompleteBody")
|
||||
|
||||
def test_chunked_wsgi_input(self):
|
||||
request = self.put(b"")
|
||||
request.META.pop("CONTENT_LENGTH", None)
|
||||
request.META["HTTP_TRANSFER_ENCODING"] = "chunked"
|
||||
request.environ["wsgi.input"] = io.BytesIO(b"streamed without a length")
|
||||
with self.assertRaises(BodyError) as cm:
|
||||
RequestBody(request)
|
||||
self.assertEqual(cm.exception.status, 411)
|
||||
request.environ["wsgi.input_terminated"] = True
|
||||
self.assertEqual(self.read(request), b"streamed without a length")
|
||||
|
||||
|
||||
class S3MultipartTests(StudioTestCase):
|
||||
"""The S3 multipart calls, as made by boto3 through its HTTP layer."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
creds = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
self.s3 = boto3.client(
|
||||
"s3", endpoint_url="http://testserver/s3", region_name="us-east-1",
|
||||
aws_access_key_id=creds["access_key"], aws_secret_access_key=creds["secret_key"],
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 0}),
|
||||
)
|
||||
self.s3.meta.events.register("before-send", self.send_with_test_client)
|
||||
|
||||
def send_with_test_client(self, request, **kwargs):
|
||||
"""Route boto3's prepared request through Django's test client."""
|
||||
from botocore.awsrequest import AWSResponse
|
||||
|
||||
body = request.body
|
||||
if hasattr(body, "read"):
|
||||
body = body.read()
|
||||
url = request.url.split("testserver", 1)[1]
|
||||
headers = {k: v.decode() if isinstance(v, bytes) else v for k, v in request.headers.items()}
|
||||
content_type = headers.pop("Content-Type", "")
|
||||
headers.pop("Content-Length", None)
|
||||
response = self.client.generic(
|
||||
request.method, url, data=body or b"", content_type=content_type, headers=headers,
|
||||
)
|
||||
content = response.getvalue() if response.streaming else response.content
|
||||
raw = mock.Mock()
|
||||
raw.stream.return_value = iter([content])
|
||||
return AWSResponse(request.url, response.status_code, dict(response.items()), raw)
|
||||
|
||||
def test_boto3_upload_file_uses_multipart(self):
|
||||
from boto3.s3.transfer import TransferConfig
|
||||
|
||||
data = os.urandom(12 * MIB + 123)
|
||||
config = TransferConfig(multipart_threshold=5 * MIB, multipart_chunksize=5 * MIB, use_threads=False)
|
||||
self.s3.upload_fileobj(io.BytesIO(data), "demo", "big dir/clip one.mp4", Config=config)
|
||||
|
||||
stored = Path(self.storage_dir, "demo", "big dir", "clip one.mp4")
|
||||
self.assertEqual(hashlib.sha256(stored.read_bytes()).digest(), hashlib.sha256(data).digest())
|
||||
upload = MultipartUpload.objects.get()
|
||||
self.assertEqual(upload.status, UploadStatus.COMPLETED)
|
||||
self.assertTrue(upload.etag.endswith("-3"))
|
||||
self.assertEqual(UploadedAsset.objects.get(s3_path="big dir/clip one.mp4").size, len(data))
|
||||
self.assertFalse(Path(self.storage_dir, ".multipart", str(upload.upload_id)).exists())
|
||||
response = self.client.get("/s3/demo/big%20dir/clip%20one.mp4", headers=self.auth())
|
||||
self.assertEqual(b"".join(response.streaming_content), data)
|
||||
|
||||
def test_parts_out_of_order_replaced_listed_and_completed(self):
|
||||
upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"]
|
||||
etags = {}
|
||||
for number, data in ((2, b"second"), (1, b"wrong"), (1, b"first-")):
|
||||
etags[number] = self.s3.upload_part(
|
||||
Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=number, Body=data)["ETag"]
|
||||
listed = self.s3.list_parts(Bucket="demo", Key="v.bin", UploadId=upload_id)["Parts"]
|
||||
self.assertEqual([(p["PartNumber"], p["Size"]) for p in listed], [(1, 6), (2, 6)])
|
||||
self.assertEqual(len(list(Path(self.storage_dir, ".multipart", upload_id).glob("*.part"))), 2)
|
||||
|
||||
parts = [{"PartNumber": n, "ETag": etags[n]} for n in (1, 2)]
|
||||
result = self.s3.complete_multipart_upload(
|
||||
Bucket="demo", Key="v.bin", UploadId=upload_id, MultipartUpload={"Parts": parts})
|
||||
self.assertEqual(Path(self.storage_dir, "demo", "v.bin").read_bytes(), b"first-second")
|
||||
# Completing again returns the same result.
|
||||
again = self.s3.complete_multipart_upload(
|
||||
Bucket="demo", Key="v.bin", UploadId=upload_id, MultipartUpload={"Parts": parts})
|
||||
self.assertEqual(result["ETag"], again["ETag"])
|
||||
|
||||
def test_complete_rejects_bad_parts(self):
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"]
|
||||
etag = self.s3.upload_part(Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=1, Body=b"x")["ETag"]
|
||||
for parts, code in (
|
||||
([{"PartNumber": 1, "ETag": '"' + "0" * 32 + '"'}], "InvalidPart"),
|
||||
([{"PartNumber": 2, "ETag": etag}], "InvalidPart"),
|
||||
([{"PartNumber": 1, "ETag": etag}, {"PartNumber": 1, "ETag": etag}], "InvalidPartOrder"),
|
||||
):
|
||||
with self.assertRaises(ClientError) as cm:
|
||||
self.s3.complete_multipart_upload(
|
||||
Bucket="demo", Key="v.bin", UploadId=upload_id, MultipartUpload={"Parts": parts})
|
||||
self.assertEqual(cm.exception.response["Error"]["Code"], code)
|
||||
self.assertFalse(Path(self.storage_dir, "demo", "v.bin").exists())
|
||||
|
||||
def test_abort(self):
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"]
|
||||
self.s3.upload_part(Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=1, Body=b"x")
|
||||
self.s3.abort_multipart_upload(Bucket="demo", Key="v.bin", UploadId=upload_id)
|
||||
self.assertFalse(Path(self.storage_dir, ".multipart", upload_id).exists())
|
||||
with self.assertRaises(ClientError) as cm:
|
||||
self.s3.upload_part(Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=2, Body=b"x")
|
||||
self.assertEqual(cm.exception.response["Error"]["Code"], "NoSuchUpload")
|
||||
|
||||
def test_upload_id_scoped_to_key(self):
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"]
|
||||
with self.assertRaises(ClientError) as cm:
|
||||
self.s3.upload_part(Bucket="demo", Key="other.bin", UploadId=upload_id, PartNumber=1, Body=b"x")
|
||||
self.assertEqual(cm.exception.response["Error"]["Code"], "NoSuchUpload")
|
||||
|
||||
def test_put_object_aws_chunked_with_trailer(self):
|
||||
"""boto3 sends this over HTTPS: aws-chunked framing with a CRC32 trailer."""
|
||||
data = os.urandom(3000)
|
||||
response = self.client.put(
|
||||
"/s3/demo/chunked.bin", data=aws_chunked(data, chunk=1000), content_type="",
|
||||
headers={**self.auth(), "Content-Encoding": "aws-chunked", "X-Amz-Trailer": "x-amz-checksum-crc32",
|
||||
"X-Amz-Decoded-Content-Length": str(len(data))},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
self.assertEqual(Path(self.storage_dir, "demo", "chunked.bin").read_bytes(), data)
|
||||
|
||||
def test_failed_put_keeps_existing_object(self):
|
||||
self.client.put("/s3/demo/keep.bin", data=b"original", content_type="", headers=self.auth())
|
||||
response = self.client.put(
|
||||
"/s3/demo/keep.bin", data=b"replacement", content_type="",
|
||||
headers={**self.auth(), "x-amz-checksum-crc32": base64.b64encode(b"\0\0\0\0").decode()},
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(Path(self.storage_dir, "demo", "keep.bin").read_bytes(), b"original")
|
||||
self.assertEqual(list(Path(self.storage_dir, ".tmp").iterdir()), [])
|
||||
|
||||
def test_unsigned_content_hash_rejected(self):
|
||||
from botocore.auth import S3SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
|
||||
creds = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
request = AWSRequest(method="PUT", url="http://testserver/s3/demo/x.bin", data=b"signed")
|
||||
S3SigV4Auth(Credentials(creds["access_key"], creds["secret_key"]), "s3", "us-east-1").add_auth(request)
|
||||
headers = {"Authorization": request.headers["Authorization"], "X-Amz-Date": request.headers["X-Amz-Date"]}
|
||||
# Signed, but the body hash header is removed: the payload would be unprotected.
|
||||
response = self.client.put("/s3/demo/x.bin", data=b"signed", content_type="", headers=headers)
|
||||
self.assertEqual(response.status_code, 401)
|
||||
# Signed with the hash, but a different body is sent.
|
||||
headers["X-Amz-Content-Sha256"] = request.headers["X-Amz-Content-Sha256"]
|
||||
response = self.client.put("/s3/demo/x.bin", data=b"tampered", content_type="", headers=headers)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertFalse(Path(self.storage_dir, "demo", "x.bin").exists())
|
||||
|
||||
def test_complete_xml_with_entities_rejected(self):
|
||||
upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"]
|
||||
body = b'<?xml version="1.0"?><!DOCTYPE x [<!ENTITY a "b">]><CompleteMultipartUpload/>'
|
||||
response = self.client.post(f"/s3/demo/v.bin?uploadId={upload_id}", data=body,
|
||||
content_type="application/xml", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn(b"MalformedXML", response.content)
|
||||
|
||||
def test_key_conflicting_with_folder(self):
|
||||
self.client.put("/s3/demo/a/b.bin", data=b"x", content_type="", headers=self.auth())
|
||||
response = self.client.put("/s3/demo/a", data=b"x", content_type="", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 400)
|
||||
response = self.client.put("/s3/demo/a/b.bin/c", data=b"x", content_type="", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
|
||||
@override_settings(PRIVATESTUDIO_UPLOAD_PART_SIZE=4)
|
||||
class BrowserUploadTests(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.client = Client(enforce_csrf_checks=True)
|
||||
self.client.force_login(self.user)
|
||||
self.client.get("/studio/demo/")
|
||||
self.csrf = self.client.cookies["csrftoken"].value
|
||||
self.base = "/studio/demo/uploads/"
|
||||
|
||||
def call(self, method, url, data=b"", content_type="application/octet-stream", client=None, csrf=True):
|
||||
if isinstance(data, dict):
|
||||
data, content_type = json.dumps(data), "application/json"
|
||||
headers = {"X-CSRFToken": self.csrf} if csrf else {}
|
||||
return (client or self.client).generic(method, url, data=data, content_type=content_type, headers=headers)
|
||||
|
||||
def create(self, size, filename="movie.mp4", folder="raw", **extra):
|
||||
response = self.call("POST", self.base, {"filename": filename, "folder": folder, "size": size, **extra})
|
||||
self.assertEqual(response.status_code, 201, response.content)
|
||||
return response.json()
|
||||
|
||||
def test_resumable_upload(self):
|
||||
data = b"0123456789"
|
||||
upload = self.create(len(data))
|
||||
self.assertEqual((upload["part_size"], upload["part_count"], upload["key"]), (4, 3, "raw/movie.mp4"))
|
||||
|
||||
for n in (3, 1):
|
||||
chunk = data[(n - 1) * 4:n * 4]
|
||||
self.assertEqual(self.call("PUT", f"{upload['url']}parts/{n}/", chunk).status_code, 200)
|
||||
status = self.call("GET", upload["url"]).json()
|
||||
self.assertEqual(sorted(status["received"]), [1, 3])
|
||||
|
||||
response = self.call("POST", f"{upload['url']}complete/", {})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("missing", response.json()["detail"])
|
||||
|
||||
self.call("PUT", f"{upload['url']}parts/2/", data[4:8])
|
||||
response = self.call("POST", f"{upload['url']}complete/", {})
|
||||
self.assertEqual(response.json()["status"], "completed")
|
||||
self.assertEqual(Path(self.storage_dir, "demo", "raw", "movie.mp4").read_bytes(), data)
|
||||
self.assertEqual(UploadedAsset.objects.get().uploaded_by, self.user)
|
||||
self.assertEqual(self.call("POST", f"{upload['url']}complete/", {}).status_code, 200)
|
||||
|
||||
def test_part_sizes_enforced(self):
|
||||
upload = self.create(10)
|
||||
self.assertEqual(self.call("PUT", f"{upload['url']}parts/1/", b"012").status_code, 400)
|
||||
self.assertEqual(self.call("PUT", f"{upload['url']}parts/1/", b"01234").status_code, 413)
|
||||
self.assertEqual(self.call("PUT", f"{upload['url']}parts/3/", b"89").status_code, 200)
|
||||
self.assertEqual(self.call("PUT", f"{upload['url']}parts/4/", b"x").status_code, 400)
|
||||
self.assertEqual(UploadPart.objects.count(), 1)
|
||||
|
||||
def test_empty_file(self):
|
||||
upload = self.create(0)
|
||||
self.call("PUT", f"{upload['url']}parts/1/", b"")
|
||||
self.assertEqual(self.call("POST", f"{upload['url']}complete/", {}).status_code, 200)
|
||||
self.assertEqual(Path(self.storage_dir, "demo", "raw", "movie.mp4").read_bytes(), b"")
|
||||
|
||||
def test_csrf_required(self):
|
||||
response = self.call("POST", self.base, {"filename": "a", "size": 1}, csrf=False)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_existing_file_needs_overwrite(self):
|
||||
Path(self.storage_dir, "demo", "raw").mkdir(parents=True)
|
||||
Path(self.storage_dir, "demo", "raw", "movie.mp4").write_bytes(b"old")
|
||||
response = self.call("POST", self.base, {"filename": "movie.mp4", "folder": "raw", "size": 1})
|
||||
self.assertEqual((response.status_code, response.json()["code"]), (409, "ObjectExists"))
|
||||
self.create(1, overwrite=True)
|
||||
|
||||
def test_file_created_meanwhile_needs_overwrite_at_complete(self):
|
||||
upload = self.create(1)
|
||||
self.call("PUT", f"{upload['url']}parts/1/", b"n")
|
||||
Path(self.storage_dir, "demo", "raw").mkdir(parents=True)
|
||||
Path(self.storage_dir, "demo", "raw", "movie.mp4").write_bytes(b"other")
|
||||
response = self.call("POST", f"{upload['url']}complete/", {})
|
||||
self.assertEqual(response.json()["code"], "ObjectExists")
|
||||
self.assertEqual(self.call("POST", f"{upload['url']}complete/", {"overwrite": True}).status_code, 200)
|
||||
self.assertEqual(Path(self.storage_dir, "demo", "raw", "movie.mp4").read_bytes(), b"n")
|
||||
|
||||
def test_invalid_names(self):
|
||||
for body in ({"filename": "../x", "size": 1}, {"filename": "a", "folder": "../..", "size": 1},
|
||||
{"filename": "a", "folder": "x//y", "size": 1}, {"filename": "a", "size": -1},
|
||||
{"filename": "a", "size": True}, {"filename": "", "size": 1}):
|
||||
self.assertEqual(self.call("POST", self.base, body).status_code, 400, body)
|
||||
|
||||
def test_other_users_cannot_see_upload(self):
|
||||
upload = self.create(4)
|
||||
member = User.objects.create_user("member")
|
||||
member.groups.add(self.group)
|
||||
other = Client()
|
||||
other.force_login(member)
|
||||
self.assertEqual(other.get(upload["url"]).status_code, 404)
|
||||
|
||||
outsider = Client()
|
||||
outsider.force_login(User.objects.create_user("outsider"))
|
||||
response = outsider.get(upload["url"])
|
||||
self.assertEqual((response.status_code, response.json()["code"]), (403, "AccessDenied"))
|
||||
self.assertEqual(Client().get(upload["url"]).status_code, 401)
|
||||
|
||||
def test_cancel(self):
|
||||
upload = self.create(4)
|
||||
self.assertEqual(self.call("DELETE", upload["url"]).status_code, 204)
|
||||
self.assertEqual(self.call("PUT", f"{upload['url']}parts/1/", b"0123").status_code, 404)
|
||||
self.assertEqual(self.call("GET", upload["url"]).json()["status"], "aborted")
|
||||
|
||||
def test_not_enough_disk_space(self):
|
||||
with mock.patch("privatestudio.studio.storage.S3FileStorage.free_space", return_value=10):
|
||||
response = self.call("POST", self.base, {"filename": "a", "size": 6})
|
||||
self.assertEqual(response.status_code, 507)
|
||||
|
||||
def test_busy_complete(self):
|
||||
upload = self.create(4)
|
||||
self.call("PUT", f"{upload['url']}parts/1/", b"0123")
|
||||
from privatestudio.studio.storage import get_storage
|
||||
with get_storage().lock_upload(upload["id"]):
|
||||
response = self.call("POST", f"{upload['url']}complete/", {})
|
||||
self.assertEqual((response.status_code, response.json()["code"]), (409, "Busy"))
|
||||
|
||||
def test_large_files_use_bigger_parts(self):
|
||||
self.assertEqual(uploads.choose_part_size(100), 4)
|
||||
self.assertEqual(uploads.choose_part_size(50_000 * MIB), 5 * MIB)
|
||||
|
||||
|
||||
class CleanupTests(StudioTestCase):
|
||||
def test_removes_expired_and_orphaned(self):
|
||||
from datetime import timedelta
|
||||
from django.utils import timezone
|
||||
from privatestudio.studio.storage import get_storage
|
||||
|
||||
storage = get_storage()
|
||||
fresh = uploads.create(self.studio, self.user, "fresh.bin", total_size=1)
|
||||
old = uploads.create(self.studio, self.user, "old.bin", total_size=1)
|
||||
MultipartUpload.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(days=30))
|
||||
orphan = storage.multipart_path / "00000000-0000-0000-0000-000000000001"
|
||||
orphan.mkdir()
|
||||
stale_temp = storage.temp_path / "stale"
|
||||
storage.temp_path.mkdir()
|
||||
stale_temp.write_bytes(b"x")
|
||||
long_ago = time.time() - 3 * 86400
|
||||
for path in (orphan, stale_temp):
|
||||
os.utime(path, (long_ago, long_ago))
|
||||
|
||||
call_command("cleanup_uploads", "--dry-run", stdout=io.StringIO())
|
||||
self.assertTrue(orphan.exists())
|
||||
call_command("cleanup_uploads", stdout=io.StringIO())
|
||||
|
||||
self.assertEqual(list(MultipartUpload.objects.values_list("key", flat=True)), ["fresh.bin"])
|
||||
self.assertFalse((storage.multipart_path / str(old.upload_id)).exists())
|
||||
self.assertTrue((storage.multipart_path / str(fresh.upload_id)).exists())
|
||||
self.assertFalse(orphan.exists())
|
||||
self.assertFalse(stale_temp.exists())
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Multipart uploads, shared by the S3 API and the browser uploader."""
|
||||
import hashlib
|
||||
import math
|
||||
import uuid
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from privatestudio.studio.models import MultipartUpload, UploadedAsset, UploadPart, UploadStatus
|
||||
from privatestudio.studio.request_body import RequestBody
|
||||
from privatestudio.studio.storage import LockBusy, UploadGone, get_storage
|
||||
|
||||
MIB = 1024 * 1024
|
||||
MAX_PARTS = 10_000
|
||||
MAX_PART_SIZE = 5 * 1024 * MIB
|
||||
|
||||
|
||||
class UploadError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
def _no_such_upload() -> UploadError:
|
||||
return UploadError(404, "NoSuchUpload", "The upload does not exist or is no longer active")
|
||||
|
||||
|
||||
def _busy() -> UploadError:
|
||||
return UploadError(503, "SlowDown", "The upload is being completed by another request")
|
||||
|
||||
|
||||
def record_asset(studio, user, key: str, filename: str, size: int) -> UploadedAsset:
|
||||
asset, _ = UploadedAsset.objects.update_or_create(
|
||||
studio=studio,
|
||||
s3_path=key,
|
||||
defaults={
|
||||
"uploaded_by": user,
|
||||
"filename": filename,
|
||||
"size": size,
|
||||
"upload_timestamp": timezone.now(),
|
||||
},
|
||||
)
|
||||
return asset
|
||||
|
||||
|
||||
def choose_part_size(total_size: int) -> int:
|
||||
"""The configured part size, or the whole MiB size that fits into MAX_PARTS."""
|
||||
configured = settings.PRIVATESTUDIO_UPLOAD_PART_SIZE
|
||||
if total_size <= configured * MAX_PARTS:
|
||||
return configured
|
||||
return math.ceil(total_size / MAX_PARTS / MIB) * MIB
|
||||
|
||||
|
||||
def part_count(upload: MultipartUpload) -> int:
|
||||
return max(1, math.ceil(upload.total_size / upload.part_size))
|
||||
|
||||
|
||||
def expected_part_size(upload: MultipartUpload, number: int) -> int:
|
||||
if number < part_count(upload):
|
||||
return upload.part_size
|
||||
return upload.total_size - (number - 1) * upload.part_size
|
||||
|
||||
|
||||
def create(
|
||||
studio, user, key: str, total_size: Optional[int] = None,
|
||||
last_modified: Optional[int] = None, overwrite: bool = True,
|
||||
) -> MultipartUpload:
|
||||
"""Start an upload. ``total_size`` is known for browser uploads only."""
|
||||
storage = get_storage()
|
||||
storage.validate_key(studio.bucket_name, key)
|
||||
part_size = None
|
||||
if total_size is not None:
|
||||
limit = settings.PRIVATESTUDIO_UPLOAD_MAX_SIZE
|
||||
if (limit and total_size > limit) or total_size > MAX_PARTS * MAX_PART_SIZE:
|
||||
raise UploadError(413, "EntityTooLarge", "The file is larger than the allowed size")
|
||||
# The parts and the joined file exist together for a while.
|
||||
if storage.free_space() < 2 * total_size:
|
||||
raise UploadError(507, "InsufficientStorage", "There is not enough free disk space for this file")
|
||||
part_size = choose_part_size(total_size)
|
||||
if not overwrite and storage.object_exists(studio.bucket_name, key):
|
||||
raise UploadError(409, "ObjectExists", "A file with this name already exists")
|
||||
|
||||
upload_id = uuid.uuid4()
|
||||
storage.create_upload(upload_id)
|
||||
try:
|
||||
return MultipartUpload.objects.create(
|
||||
upload_id=upload_id, studio=studio, created_by=user, key=key,
|
||||
filename=key.rsplit("/", 1)[-1], total_size=total_size, part_size=part_size,
|
||||
last_modified=last_modified, overwrite=overwrite,
|
||||
)
|
||||
except BaseException:
|
||||
storage.remove_upload(upload_id)
|
||||
raise
|
||||
|
||||
|
||||
def put_part(upload: MultipartUpload, number: int, request) -> str:
|
||||
"""Stream the request body into a part and return its ETag. Sending a part again replaces it."""
|
||||
if not 1 <= number <= MAX_PARTS:
|
||||
raise UploadError(400, "InvalidArgument", f"Part number must be between 1 and {MAX_PARTS}")
|
||||
if upload.status != UploadStatus.ACTIVE:
|
||||
raise _no_such_upload()
|
||||
expected = None
|
||||
if upload.total_size is not None:
|
||||
if number > part_count(upload):
|
||||
raise UploadError(400, "InvalidArgument", "Part number is past the end of the file")
|
||||
expected = expected_part_size(upload, number)
|
||||
|
||||
storage = get_storage()
|
||||
body = RequestBody(request, max_bytes=MAX_PART_SIZE if expected is None else expected)
|
||||
try:
|
||||
staged, result = storage.stage_part(upload.upload_id, body)
|
||||
try:
|
||||
body.verify_write(result)
|
||||
if expected is not None and result.size != expected:
|
||||
raise UploadError(400, "IncompleteBody", f"Part {number} must be {expected} bytes")
|
||||
with storage.lock_upload(upload.upload_id):
|
||||
upload.refresh_from_db()
|
||||
if upload.status != UploadStatus.ACTIVE:
|
||||
raise _no_such_upload()
|
||||
storage.publish_part(upload.upload_id, number, result.md5, staged)
|
||||
# A single upsert: update_or_create's read-then-write can hit SQLite
|
||||
# lock errors when several parts arrive at once.
|
||||
UploadPart.objects.bulk_create(
|
||||
[UploadPart(upload=upload, part_number=number, size=result.size, etag=result.md5)],
|
||||
update_conflicts=True,
|
||||
unique_fields=["upload", "part_number"],
|
||||
update_fields=["size", "etag", "uploaded_at"],
|
||||
)
|
||||
storage.remove_replaced_parts(upload.upload_id, number, result.md5)
|
||||
finally:
|
||||
staged.unlink(missing_ok=True)
|
||||
except (UploadGone, MultipartUpload.DoesNotExist):
|
||||
raise _no_such_upload() from None
|
||||
except LockBusy:
|
||||
raise _busy() from None
|
||||
return result.md5
|
||||
|
||||
|
||||
def _select_parts(upload: MultipartUpload, requested: Optional[Iterable[tuple[int, str]]]) -> list[UploadPart]:
|
||||
stored = {p.part_number: p for p in upload.parts.all()}
|
||||
if upload.total_size is not None:
|
||||
missing = [n for n in range(1, part_count(upload) + 1) if n not in stored]
|
||||
if missing:
|
||||
raise UploadError(400, "InvalidPart", f"{len(missing)} parts are missing, first: {missing[0]}")
|
||||
if requested is None:
|
||||
return [stored[n] for n in sorted(stored)]
|
||||
|
||||
requested = list(requested)
|
||||
if not requested:
|
||||
raise UploadError(400, "MalformedXML", "No parts were listed")
|
||||
selected, previous = [], 0
|
||||
for number, etag in requested:
|
||||
if number <= previous:
|
||||
raise UploadError(400, "InvalidPartOrder", "Parts must be listed in ascending order")
|
||||
previous = number
|
||||
part = stored.get(number)
|
||||
if part is None or part.etag != etag.strip().strip('"').lower():
|
||||
raise UploadError(400, "InvalidPart", f"Part {number} is missing or its ETag does not match")
|
||||
selected.append(part)
|
||||
return selected
|
||||
|
||||
|
||||
def complete(
|
||||
upload: MultipartUpload, requested: Optional[Iterable[tuple[int, str]]] = None, overwrite: bool = False,
|
||||
) -> MultipartUpload:
|
||||
"""
|
||||
Join the parts into the final object. Completing a completed upload returns it again.
|
||||
|
||||
``requested`` lists ``(part_number, etag)``. None means every stored part.
|
||||
"""
|
||||
if upload.status == UploadStatus.COMPLETED:
|
||||
return upload
|
||||
storage = get_storage()
|
||||
studio = upload.studio
|
||||
try:
|
||||
# Long enough to wait out a part being published, but not another join.
|
||||
with storage.lock_upload(upload.upload_id, timeout=2):
|
||||
upload.refresh_from_db()
|
||||
if upload.status == UploadStatus.COMPLETED:
|
||||
return upload
|
||||
if upload.status != UploadStatus.ACTIVE:
|
||||
raise _no_such_upload()
|
||||
parts = _select_parts(upload, requested)
|
||||
size = sum(p.size for p in parts)
|
||||
if upload.total_size is not None and size != upload.total_size:
|
||||
raise UploadError(400, "InvalidPart", "The parts do not add up to the file size")
|
||||
limit = settings.PRIVATESTUDIO_UPLOAD_MAX_SIZE
|
||||
if limit and size > limit:
|
||||
raise UploadError(413, "EntityTooLarge", "The file is larger than the allowed size")
|
||||
if not (overwrite or upload.overwrite) and storage.object_exists(studio.bucket_name, upload.key):
|
||||
raise UploadError(409, "ObjectExists", "A file with this name already exists")
|
||||
|
||||
storage.assemble(
|
||||
upload.upload_id, [(p.part_number, p.etag, p.size) for p in parts],
|
||||
studio.bucket_name, upload.key,
|
||||
)
|
||||
digests = b"".join(bytes.fromhex(p.etag) for p in parts)
|
||||
etag = f"{hashlib.md5(digests, usedforsecurity=False).hexdigest()}-{len(parts)}"
|
||||
with transaction.atomic():
|
||||
upload.status = UploadStatus.COMPLETED
|
||||
upload.etag = etag
|
||||
upload.save(update_fields=["status", "etag"])
|
||||
record_asset(studio, upload.created_by, upload.key, upload.filename, size)
|
||||
storage.remove_upload(upload.upload_id)
|
||||
except (UploadGone, MultipartUpload.DoesNotExist):
|
||||
# Another request may have completed it between our two checks.
|
||||
current = MultipartUpload.objects.filter(pk=upload.pk).first()
|
||||
if current and current.status == UploadStatus.COMPLETED:
|
||||
return current
|
||||
raise _no_such_upload() from None
|
||||
except LockBusy:
|
||||
raise _busy() from None
|
||||
return upload
|
||||
|
||||
|
||||
def abort(upload: MultipartUpload) -> None:
|
||||
if upload.status != UploadStatus.ACTIVE:
|
||||
raise _no_such_upload()
|
||||
storage = get_storage()
|
||||
try:
|
||||
with storage.lock_upload(upload.upload_id, timeout=5):
|
||||
upload.refresh_from_db()
|
||||
if upload.status != UploadStatus.ACTIVE:
|
||||
raise _no_such_upload()
|
||||
upload.status = UploadStatus.ABORTED
|
||||
upload.save(update_fields=["status"])
|
||||
upload.parts.all().delete()
|
||||
storage.remove_upload(upload.upload_id)
|
||||
except LockBusy:
|
||||
raise _busy() from None
|
||||
except UploadGone:
|
||||
MultipartUpload.objects.filter(pk=upload.pk, status=UploadStatus.ACTIVE).update(status=UploadStatus.ABORTED)
|
||||
@@ -0,0 +1,30 @@
|
||||
from django.urls import re_path, path, include
|
||||
from django.views.generic import RedirectView
|
||||
|
||||
from privatestudio.studio import s3_views, views
|
||||
|
||||
# re_path without trailing-slash requirements so APPEND_SLASH never redirects
|
||||
# (a redirect would invalidate AWS v4 signatures).
|
||||
|
||||
studio_patterns = [
|
||||
path("", views.StudioListView.as_view(), name="list"),
|
||||
path("<slug:bucket_name>/", views.StudioDetailView.as_view(), name="detail"),
|
||||
path("<slug:bucket_name>/hx/uploaded_assets/", views.UploadedAssetsView.as_view(), name="uploaded_assets"),
|
||||
path("<slug:bucket_name>/hx/content_assets/", views.ContentAssetsView.as_view(), name="content_assets"),
|
||||
path("<slug:bucket_name>/content/create/<int:asset_id>/", views.ContentAssetCreateView.as_view(),
|
||||
name="content_asset_create"),
|
||||
path("<slug:bucket_name>/content/<int:pk>/", views.ContentAssetUpdateView.as_view(), name="content_asset"),
|
||||
path("<slug:bucket_name>/uploads/", views.UploadCreateView.as_view(), name="upload_create"),
|
||||
path("<slug:bucket_name>/uploads/<uuid:upload_id>/", views.UploadView.as_view(), name="upload"),
|
||||
path("<slug:bucket_name>/uploads/<uuid:upload_id>/parts/<int:number>/", views.UploadPartView.as_view(),
|
||||
name="upload_part"),
|
||||
path("<slug:bucket_name>/uploads/<uuid:upload_id>/complete/", views.UploadCompleteView.as_view(),
|
||||
name="upload_complete"),
|
||||
]
|
||||
|
||||
urlpatterns = [
|
||||
path("", RedirectView.as_view(url="/studio/"), name="home"),
|
||||
path("studio/", include((studio_patterns, 'studio'))),
|
||||
re_path(r"^s3/(?P<bucket>[^/]+)/?$", s3_views.BucketView.as_view(), name="s3_bucket"),
|
||||
re_path(r"^s3/(?P<bucket>[^/]+)/(?P<key>.+)$", s3_views.ObjectView.as_view(), name="s3_object"),
|
||||
]
|
||||
@@ -0,0 +1,243 @@
|
||||
import errno
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
from django.contrib import messages
|
||||
from django.db.models import OuterRef, Subquery
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse
|
||||
from django.views import View
|
||||
from django.views.generic import ListView, DetailView, UpdateView
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
|
||||
|
||||
from privatestudio.studio import uploads
|
||||
from privatestudio.studio.forms import ContentAssetForm
|
||||
from privatestudio.studio.models import ContentAsset, MultipartUpload, Studio, UploadedAsset
|
||||
from privatestudio.studio.request_body import BodyError, read_small_body
|
||||
from privatestudio.studio.storage import InvalidKey
|
||||
from privatestudio.studio.uploads import UploadError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StudioMixin(AccessMixin):
|
||||
studio_slug_url_kwarg = "bucket_name"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return self.handle_no_permission()
|
||||
|
||||
user_groups = self.request.user.groups.all()
|
||||
|
||||
studio_qs = Studio.objects.filter(bucket_name=kwargs.get(self.studio_slug_url_kwarg), group__in=user_groups)
|
||||
self.studio = studio_qs.first()
|
||||
|
||||
if not self.studio:
|
||||
return self.handle_no_permission()
|
||||
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
|
||||
class StudioListView(LoginRequiredMixin, ListView):
|
||||
model = Studio
|
||||
template_name = "privatestudio/studio_list.html"
|
||||
context_object_name = "studios"
|
||||
|
||||
def get_queryset(self):
|
||||
# Filter studios based on the user's group memberships
|
||||
user_groups = self.request.user.groups.all()
|
||||
return super().get_queryset().filter(group__in=user_groups)
|
||||
|
||||
|
||||
class StudioDetailView(StudioMixin, DetailView):
|
||||
model = Studio
|
||||
template_name = "privatestudio/studio_detail.html"
|
||||
context_object_name = "studio"
|
||||
slug_field = "bucket_name"
|
||||
slug_url_kwarg = "bucket_name"
|
||||
|
||||
def get_queryset(self):
|
||||
# Filter studios based on the user's group memberships
|
||||
user_groups = self.request.user.groups.all()
|
||||
return super().get_queryset().filter(group__in=user_groups)
|
||||
|
||||
|
||||
class UploadedAssetsView(StudioMixin, ListView):
|
||||
model = UploadedAsset
|
||||
template_name = "privatestudio/hx_uploaded_assets.html"
|
||||
context_object_name = "uploaded_assets"
|
||||
|
||||
def get_queryset(self):
|
||||
content_asset = ContentAsset.objects.filter(uploaded_asset=OuterRef("pk")).order_by("pk").values("pk")[:1]
|
||||
return (
|
||||
super().get_queryset()
|
||||
.filter(studio=self.studio)
|
||||
.annotate(content_asset_id=Subquery(content_asset))
|
||||
.order_by("s3_path")
|
||||
)
|
||||
|
||||
|
||||
class ContentAssetsView(StudioMixin, ListView):
|
||||
model = ContentAsset
|
||||
template_name = "privatestudio/hx_content_assets.html"
|
||||
context_object_name = "content_assets"
|
||||
|
||||
def get_queryset(self):
|
||||
return (
|
||||
super().get_queryset()
|
||||
.filter(studio=self.studio)
|
||||
.select_related("group", "uploaded_asset")
|
||||
)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(studio=self.studio, **kwargs)
|
||||
|
||||
|
||||
class ContentAssetCreateView(StudioMixin, View):
|
||||
"""Create content metadata for an uploaded file, then open it for editing."""
|
||||
http_method_names = ["post"]
|
||||
|
||||
def post(self, request, bucket_name, asset_id):
|
||||
asset = get_object_or_404(UploadedAsset, pk=asset_id, studio=self.studio)
|
||||
content = asset.content_assets.order_by("pk").first()
|
||||
if content is None:
|
||||
title = os.path.splitext(os.path.basename(asset.filename or asset.s3_path))[0]
|
||||
content = ContentAsset.objects.create(
|
||||
studio=self.studio, uploaded_asset=asset, title=title or asset.s3_path,
|
||||
)
|
||||
return redirect("studio:content_asset", self.studio.bucket_name, content.pk)
|
||||
|
||||
|
||||
class ContentAssetUpdateView(StudioMixin, UpdateView):
|
||||
model = ContentAsset
|
||||
form_class = ContentAssetForm
|
||||
template_name = "privatestudio/content_asset_form.html"
|
||||
context_object_name = "content_asset"
|
||||
|
||||
def get_queryset(self):
|
||||
return ContentAsset.objects.filter(studio=self.studio).select_related("uploaded_asset")
|
||||
|
||||
def get_form_kwargs(self):
|
||||
return {**super().get_form_kwargs(), "studio": self.studio}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(studio=self.studio, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
messages.success(self.request, f"Saved {form.instance.title}.")
|
||||
return super().form_valid(form)
|
||||
|
||||
def form_invalid(self, form):
|
||||
# The form has already copied the invalid values onto self.object; show the saved ones outside the form.
|
||||
self.object = self.get_object()
|
||||
return super().form_invalid(form)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse("studio:content_asset", args=[self.studio.bucket_name, self.object.pk])
|
||||
|
||||
|
||||
class UploadApiView(StudioMixin, View):
|
||||
"""JSON endpoints for the browser uploader. Uses the session, with normal CSRF protection."""
|
||||
|
||||
def handle_no_permission(self):
|
||||
if not self.request.user.is_authenticated:
|
||||
return _json_error(401, "NotAuthenticated", "Sign in again to continue")
|
||||
return _json_error(403, "AccessDenied", "You don't have access to this studio")
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
try:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
except (UploadError, BodyError) as e:
|
||||
return _json_error(e.status, e.code, e.message)
|
||||
except InvalidKey as e:
|
||||
return _json_error(400, "InvalidKey", str(e))
|
||||
except OSError as e:
|
||||
if e.errno not in (errno.ENOSPC, errno.EDQUOT):
|
||||
raise
|
||||
logger.error("Storage is full: %s", e)
|
||||
return _json_error(507, "InsufficientStorage", "The server has run out of storage")
|
||||
|
||||
def get_upload(self, upload_id) -> MultipartUpload:
|
||||
# Browser uploads only: total_size is null for those started by S3 clients.
|
||||
upload = MultipartUpload.objects.filter(
|
||||
studio=self.studio, created_by=self.request.user, upload_id=upload_id, total_size__isnull=False,
|
||||
).first()
|
||||
if upload is None:
|
||||
raise UploadError(404, "NoSuchUpload", "The upload does not exist")
|
||||
return upload
|
||||
|
||||
def get_json(self) -> dict:
|
||||
try:
|
||||
data = json.loads(read_small_body(self.request, 64 * 1024) or b"{}")
|
||||
except ValueError:
|
||||
data = None
|
||||
if not isinstance(data, dict):
|
||||
raise UploadError(400, "InvalidRequest", "The body must be a JSON object")
|
||||
return data
|
||||
|
||||
def upload_response(self, upload, status=200):
|
||||
return JsonResponse({
|
||||
"id": str(upload.upload_id),
|
||||
"url": reverse("studio:upload", args=[self.studio.bucket_name, upload.upload_id]),
|
||||
"key": upload.key,
|
||||
"status": upload.status,
|
||||
"size": upload.total_size,
|
||||
"part_size": upload.part_size,
|
||||
"part_count": uploads.part_count(upload),
|
||||
"received": list(upload.parts.values_list("part_number", flat=True)),
|
||||
"etag": upload.etag,
|
||||
}, status=status)
|
||||
|
||||
|
||||
def _json_error(status, code, message):
|
||||
return JsonResponse({"code": code, "detail": message}, status=status)
|
||||
|
||||
|
||||
def _is_size(value) -> bool:
|
||||
return isinstance(value, int) and not isinstance(value, bool) and 0 <= value < 2**63
|
||||
|
||||
|
||||
class UploadCreateView(UploadApiView):
|
||||
def post(self, request, bucket_name):
|
||||
data = self.get_json()
|
||||
filename, folder = data.get("filename"), data.get("folder", "")
|
||||
size, last_modified = data.get("size"), data.get("last_modified")
|
||||
if not isinstance(filename, str) or not filename or "/" in filename or not isinstance(folder, str):
|
||||
raise UploadError(400, "InvalidRequest", "A file name is required and the folder must be text")
|
||||
if not _is_size(size) or not (last_modified is None or _is_size(last_modified)):
|
||||
raise UploadError(400, "InvalidRequest", "The size and modification time must be whole numbers")
|
||||
folder = folder.strip().strip("/")
|
||||
upload = uploads.create(
|
||||
self.studio, request.user, f"{folder}/{filename}" if folder else filename,
|
||||
total_size=size, last_modified=last_modified, overwrite=data.get("overwrite") is True,
|
||||
)
|
||||
return self.upload_response(upload, status=201)
|
||||
|
||||
|
||||
class UploadView(UploadApiView):
|
||||
def get(self, request, bucket_name, upload_id):
|
||||
return self.upload_response(self.get_upload(upload_id))
|
||||
|
||||
def delete(self, request, bucket_name, upload_id):
|
||||
uploads.abort(self.get_upload(upload_id))
|
||||
return HttpResponse(status=204)
|
||||
|
||||
|
||||
class UploadPartView(UploadApiView):
|
||||
def put(self, request, bucket_name, upload_id, number):
|
||||
etag = uploads.put_part(self.get_upload(upload_id), number, request)
|
||||
return JsonResponse({"part": number, "etag": etag})
|
||||
|
||||
|
||||
class UploadCompleteView(UploadApiView):
|
||||
def post(self, request, bucket_name, upload_id):
|
||||
overwrite = self.get_json().get("overwrite") is True
|
||||
try:
|
||||
upload = uploads.complete(self.get_upload(upload_id), overwrite=overwrite)
|
||||
except UploadError as e:
|
||||
if e.code == "SlowDown":
|
||||
return _json_error(409, "Busy", e.message)
|
||||
raise
|
||||
return self.upload_response(upload)
|
||||
@@ -0,0 +1,19 @@
|
||||
from django.contrib import admin
|
||||
from django.http import JsonResponse
|
||||
from django.urls import include, path
|
||||
|
||||
from privatestudio.studio.api import api
|
||||
|
||||
|
||||
def health_check(request):
|
||||
"""Unauthenticated health check endpoint."""
|
||||
return JsonResponse({"status": "ok"})
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("health", health_check, name="health"),
|
||||
path("admin/", admin.site.urls),
|
||||
path("accounts/", include('allauth.urls')),
|
||||
path("api/", api.urls),
|
||||
path("", include("privatestudio.studio.urls")),
|
||||
]
|
||||
@@ -0,0 +1,8 @@
|
||||
"""WSGI config for the privatestudio project."""
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "privatestudio.settings.dev")
|
||||
|
||||
application = get_wsgi_application()
|
||||
+21
-4
@@ -1,14 +1,24 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68", "setuptools_scm[toml]>=8", "wheel"]
|
||||
requires = ["setuptools>=77", "setuptools_scm[toml]>=8", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "privatestudio"
|
||||
description = "Video transcoding tools with multi-profile H.264 encoding support"
|
||||
readme = "notes.md"
|
||||
requires-python = ">=3.8"
|
||||
license = "BSD-3-Clause"
|
||||
license-files = ["LICENSE"]
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"PyYAML>=6.0",
|
||||
"Django~=6.1.0",
|
||||
"django-ninja~=1.8",
|
||||
"django-cors-headers~=4.9",
|
||||
"dj-database-url~=3.1",
|
||||
"whitenoise~=6.11.0",
|
||||
"pytz~=2026.5",
|
||||
"django-allauth[socialaccount]~=65.0.2",
|
||||
"nh3==0.2.20",
|
||||
]
|
||||
dynamic = ["version"]
|
||||
|
||||
@@ -16,14 +26,21 @@ dynamic = ["version"]
|
||||
dev = [
|
||||
"pytest>=7.0",
|
||||
"pytest-cov>=4.0",
|
||||
"pytest-django>=4.14",
|
||||
"boto3",
|
||||
"build",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
ps-transcode = "privatestudio.transcode:main"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["privatestudio"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["privatestudio*"]
|
||||
|
||||
[tool.setuptools_scm]
|
||||
write_to = "privatestudio/_version.py"
|
||||
fallback_version = "0.1.0-dev"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
DJANGO_SETTINGS_MODULE = "privatestudio.settings.dev"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../scss/styles.scss'
|
||||
|
||||
import * as bootstrap from 'bootstrap'
|
||||
|
||||
const jquery = require('jquery')
|
||||
window.$ = jquery
|
||||
window.jQuery = jquery
|
||||
|
||||
import { initUploaders } from './uploader'
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initUploaders)
|
||||
@@ -0,0 +1,375 @@
|
||||
// Resumable chunked uploads for the studio page.
|
||||
//
|
||||
// Each file is sent in parts with File.slice(), so the browser never reads a whole
|
||||
// file into memory. Upload ids are remembered in localStorage: after a reload,
|
||||
// picking the same file again sends only the missing parts.
|
||||
|
||||
const CONCURRENCY = 3
|
||||
const MAX_ATTEMPTS = 8
|
||||
const STALL_MS = 120000
|
||||
const STORE_PREFIX = 'privatestudio.upload.'
|
||||
|
||||
class FatalError extends Error {}
|
||||
|
||||
class HttpError extends Error {
|
||||
constructor (status, data) {
|
||||
super((data && data.detail) || `The server returned HTTP ${status}`)
|
||||
this.status = status
|
||||
this.code = data && data.code
|
||||
}
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
const retryable = (error) =>
|
||||
!(error instanceof FatalError) &&
|
||||
(!(error instanceof HttpError) || [0, 408, 429, 500, 502, 503, 504].includes(error.status))
|
||||
|
||||
function store (action, key, value) {
|
||||
try {
|
||||
if (action === 'get') return JSON.parse(window.localStorage.getItem(STORE_PREFIX + key))
|
||||
if (action === 'set') window.localStorage.setItem(STORE_PREFIX + key, JSON.stringify(value))
|
||||
if (action === 'remove') window.localStorage.removeItem(STORE_PREFIX + key)
|
||||
} catch (e) {
|
||||
// Storage can be unavailable (private windows, blocked site data). Resuming then
|
||||
// starts over, which is still correct.
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function formatBytes (bytes) {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
let i = 0
|
||||
while (bytes >= 1024 && i < units.length - 1) { bytes /= 1024; i++ }
|
||||
return `${bytes.toFixed(i ? 1 : 0)} ${units[i]}`
|
||||
}
|
||||
|
||||
// One XMLHttpRequest. XHR is used because fetch() has no portable upload progress.
|
||||
function request (method, url, { body = null, csrf, onProgress, xhrs } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
let stallTimer
|
||||
const stalled = () => {
|
||||
clearTimeout(stallTimer)
|
||||
stallTimer = setTimeout(() => xhr.abort(), STALL_MS)
|
||||
}
|
||||
const finish = () => { clearTimeout(stallTimer); if (xhrs) xhrs.delete(xhr) }
|
||||
|
||||
xhr.open(method, url)
|
||||
xhr.setRequestHeader('X-CSRFToken', csrf)
|
||||
xhr.setRequestHeader('Accept', 'application/json')
|
||||
if (body !== null && !(body instanceof Blob)) xhr.setRequestHeader('Content-Type', 'application/json')
|
||||
xhr.upload.onprogress = (event) => { stalled(); if (onProgress) onProgress(event.loaded) }
|
||||
xhr.onload = () => {
|
||||
finish()
|
||||
let data = null
|
||||
try { data = xhr.responseText ? JSON.parse(xhr.responseText) : null } catch (e) { data = null }
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve(data)
|
||||
else reject(new HttpError(xhr.status, data))
|
||||
}
|
||||
xhr.onerror = xhr.onabort = () => { finish(); reject(new HttpError(0, { detail: 'The connection failed' })) }
|
||||
if (xhrs) xhrs.add(xhr)
|
||||
stalled()
|
||||
xhr.send(body === null || body instanceof Blob ? body : JSON.stringify(body))
|
||||
})
|
||||
}
|
||||
|
||||
class FileUpload {
|
||||
constructor (uploader, file, folder) {
|
||||
this.uploader = uploader
|
||||
this.file = file
|
||||
this.folder = folder
|
||||
this.cancelled = false
|
||||
this.xhrs = new Set()
|
||||
this.inFlight = new Map()
|
||||
this.done = 0
|
||||
this.storeKey = [uploader.userId, uploader.bucket, folder, file.name, file.size, file.lastModified].join('|')
|
||||
this.renderRow()
|
||||
}
|
||||
|
||||
renderRow () {
|
||||
const row = document.createElement('li')
|
||||
row.className = 'list-group-item'
|
||||
row.innerHTML = `
|
||||
<div class="d-flex justify-content-between align-items-center gap-2">
|
||||
<span class="text-truncate fw-semibold"></span>
|
||||
<span class="d-flex gap-1 flex-shrink-0">
|
||||
<button type="button" class="btn btn-sm btn-outline-primary d-none" data-action="retry">Retry</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" data-action="cancel">Cancel</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="progress my-2" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
|
||||
<div class="progress-bar" style="width: 0%"></div>
|
||||
</div>
|
||||
<small class="text-body-secondary" aria-live="polite"></small>`
|
||||
row.querySelector('.fw-semibold').textContent = this.folder ? `${this.folder}/${this.file.name}` : this.file.name
|
||||
this.row = row
|
||||
this.bar = row.querySelector('.progress-bar')
|
||||
this.status = row.querySelector('small')
|
||||
this.retryButton = row.querySelector('[data-action=retry]')
|
||||
this.cancelButton = row.querySelector('[data-action=cancel]')
|
||||
this.retryButton.addEventListener('click', () => this.uploader.enqueue(this))
|
||||
this.cancelButton.addEventListener('click', () => this.cancel())
|
||||
this.uploader.list.prepend(row)
|
||||
this.setStatus('Waiting')
|
||||
}
|
||||
|
||||
setStatus (text, style = '') {
|
||||
this.status.textContent = text
|
||||
this.status.className = style ? `text-${style}` : 'text-body-secondary'
|
||||
}
|
||||
|
||||
setProgress (bytes) {
|
||||
const percent = this.file.size ? Math.min(100, (bytes / this.file.size) * 100) : 100
|
||||
this.bar.style.width = `${percent}%`
|
||||
this.bar.parentElement.setAttribute('aria-valuenow', Math.round(percent))
|
||||
}
|
||||
|
||||
call (method, url, options = {}) {
|
||||
if (this.cancelled) return Promise.reject(new FatalError('Cancelled'))
|
||||
return request(method, url, { csrf: this.uploader.csrf, xhrs: this.xhrs, ...options })
|
||||
}
|
||||
|
||||
// Retry network failures and server errors with exponential backoff.
|
||||
async withRetry (action) {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
return await action()
|
||||
} catch (error) {
|
||||
if (this.cancelled) throw new FatalError('Cancelled')
|
||||
if (!retryable(error) || attempt >= MAX_ATTEMPTS) throw error
|
||||
await sleep(Math.min(30000, 1000 * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async run () {
|
||||
this.retryButton.classList.add('d-none')
|
||||
this.bar.classList.remove('bg-danger', 'bg-success')
|
||||
this.cancelButton.disabled = false
|
||||
this.cancelled = false
|
||||
try {
|
||||
const upload = await this.start()
|
||||
if (upload.status !== 'completed') {
|
||||
await this.sendParts(upload)
|
||||
await this.complete(upload)
|
||||
}
|
||||
store('remove', this.storeKey)
|
||||
this.setProgress(this.file.size)
|
||||
this.bar.classList.add('bg-success')
|
||||
this.setStatus(`Uploaded ${formatBytes(this.file.size)}`, 'success')
|
||||
this.cancelButton.classList.add('d-none')
|
||||
document.body.dispatchEvent(new CustomEvent('assets-changed'))
|
||||
} catch (error) {
|
||||
if (this.cancelled) return
|
||||
this.bar.classList.add('bg-danger')
|
||||
let message = error.message
|
||||
if (error instanceof HttpError && error.status === 403) {
|
||||
message += '. If you signed in again in another tab, reload this page and pick the file again to resume.'
|
||||
}
|
||||
this.setStatus(message, 'danger')
|
||||
this.retryButton.classList.remove('d-none')
|
||||
}
|
||||
}
|
||||
|
||||
// Resume a remembered upload of this file, or start a new one.
|
||||
async start () {
|
||||
const remembered = store('get', this.storeKey)
|
||||
if (remembered) {
|
||||
try {
|
||||
const upload = await this.withRetry(() => this.call('GET', remembered.url))
|
||||
if (upload.status === 'active' || upload.status === 'completed') return upload
|
||||
} catch (error) {
|
||||
if (!(error instanceof HttpError) || error.status !== 404) throw error
|
||||
}
|
||||
store('remove', this.storeKey)
|
||||
}
|
||||
|
||||
const body = {
|
||||
filename: this.file.name,
|
||||
folder: this.folder,
|
||||
size: this.file.size,
|
||||
last_modified: this.file.lastModified,
|
||||
overwrite: false
|
||||
}
|
||||
let upload
|
||||
try {
|
||||
upload = await this.withRetry(() => this.call('POST', this.uploader.createUrl, { body }))
|
||||
} catch (error) {
|
||||
if (!(error instanceof HttpError) || error.code !== 'ObjectExists') throw error
|
||||
if (!window.confirm(`${body.folder ? body.folder + '/' : ''}${this.file.name} already exists. Replace it?`)) {
|
||||
throw new FatalError('Not uploaded: a file with this name already exists')
|
||||
}
|
||||
body.overwrite = true
|
||||
upload = await this.withRetry(() => this.call('POST', this.uploader.createUrl, { body }))
|
||||
}
|
||||
store('set', this.storeKey, { url: upload.url })
|
||||
return upload
|
||||
}
|
||||
|
||||
async sendParts (upload) {
|
||||
const received = new Set(upload.received)
|
||||
const pending = []
|
||||
for (let n = 1; n <= upload.part_count; n++) {
|
||||
if (!received.has(n)) pending.push(n)
|
||||
}
|
||||
const partBytes = (n) => Math.min(upload.part_size, this.file.size - (n - 1) * upload.part_size)
|
||||
this.done = this.file.size - pending.reduce((sum, n) => sum + partBytes(n), 0)
|
||||
this.inFlight.clear()
|
||||
const started = Date.now()
|
||||
const doneAtStart = this.done
|
||||
|
||||
const showProgress = () => {
|
||||
let sending = 0
|
||||
for (const bytes of this.inFlight.values()) sending += bytes
|
||||
const sent = this.done + sending
|
||||
this.setProgress(sent)
|
||||
const seconds = (Date.now() - started) / 1000
|
||||
const rate = seconds > 1 ? (sent - doneAtStart) / seconds : 0
|
||||
const speed = rate ? `, ${formatBytes(rate)}/s` : ''
|
||||
this.setStatus(`${formatBytes(sent)} of ${formatBytes(this.file.size)}${speed}`)
|
||||
}
|
||||
showProgress()
|
||||
|
||||
const worker = async () => {
|
||||
while (pending.length) {
|
||||
const n = pending.shift()
|
||||
const start = (n - 1) * upload.part_size
|
||||
const blob = this.file.slice(start, start + partBytes(n))
|
||||
await this.withRetry(() => {
|
||||
this.inFlight.set(n, 0)
|
||||
return this.call('PUT', `${upload.url}parts/${n}/`, {
|
||||
body: blob,
|
||||
onProgress: (loaded) => { this.inFlight.set(n, loaded); showProgress() }
|
||||
})
|
||||
})
|
||||
this.inFlight.delete(n)
|
||||
this.done += blob.size
|
||||
showProgress()
|
||||
}
|
||||
}
|
||||
// If one worker fails, stop the others so the failure is reported once.
|
||||
try {
|
||||
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, pending.length) }, worker))
|
||||
} catch (error) {
|
||||
pending.length = 0
|
||||
for (const xhr of this.xhrs) xhr.abort()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Joining a large file takes time. If the request is cut off, check the
|
||||
// upload's status, then ask again.
|
||||
async complete (upload) {
|
||||
this.setStatus('Finalizing…')
|
||||
this.bar.classList.add('progress-bar-striped', 'progress-bar-animated')
|
||||
let overwrite = false
|
||||
let failures = 0
|
||||
const deadline = Date.now() + 60 * 60 * 1000
|
||||
try {
|
||||
while (true) {
|
||||
try {
|
||||
return await this.call('POST', `${upload.url}complete/`, { body: { overwrite } })
|
||||
} catch (error) {
|
||||
if (this.cancelled) throw new FatalError('Cancelled')
|
||||
if (error.code === 'ObjectExists' && !overwrite) {
|
||||
if (!window.confirm(`${upload.key} was created by someone else meanwhile. Replace it?`)) {
|
||||
throw new FatalError('Not uploaded: a file with this name already exists. Retry to choose again.')
|
||||
}
|
||||
overwrite = true
|
||||
continue
|
||||
}
|
||||
const busy = error.status === 409 && error.code === 'Busy'
|
||||
if (!busy && (!retryable(error) || ++failures >= MAX_ATTEMPTS)) throw error
|
||||
if (Date.now() > deadline) throw error
|
||||
await sleep(3000)
|
||||
try {
|
||||
const current = await this.call('GET', upload.url)
|
||||
if (current.status === 'completed') return current
|
||||
} catch (e) {
|
||||
// Try completing again below.
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.bar.classList.remove('progress-bar-striped', 'progress-bar-animated')
|
||||
}
|
||||
}
|
||||
|
||||
async cancel () {
|
||||
this.cancelled = true
|
||||
for (const xhr of this.xhrs) xhr.abort()
|
||||
this.uploader.dequeue(this)
|
||||
this.cancelButton.disabled = true
|
||||
this.retryButton.classList.add('d-none')
|
||||
this.setStatus('Cancelling…')
|
||||
const remembered = store('get', this.storeKey)
|
||||
store('remove', this.storeKey)
|
||||
if (remembered) {
|
||||
try {
|
||||
await request('DELETE', remembered.url, { csrf: this.uploader.csrf })
|
||||
} catch (error) {
|
||||
// The server removes abandoned uploads later.
|
||||
}
|
||||
}
|
||||
this.setStatus('Cancelled', 'warning')
|
||||
this.bar.classList.add('bg-secondary')
|
||||
}
|
||||
}
|
||||
|
||||
// Files upload one after another; each sends several parts at once.
|
||||
class Uploader {
|
||||
constructor (form) {
|
||||
this.form = form
|
||||
this.createUrl = form.dataset.createUrl
|
||||
this.bucket = form.dataset.bucket
|
||||
this.userId = form.dataset.userId
|
||||
this.csrf = form.querySelector('[name=csrfmiddlewaretoken]').value
|
||||
this.list = form.querySelector('[data-upload-list]')
|
||||
this.fileInput = form.querySelector('input[type=file]')
|
||||
this.folderInput = form.querySelector('[name=folder]')
|
||||
this.queue = []
|
||||
this.active = null
|
||||
form.querySelector('button[type=submit]').disabled = false
|
||||
|
||||
form.addEventListener('submit', (event) => {
|
||||
event.preventDefault()
|
||||
const folder = this.folderInput.value.trim().replace(/^\/+|\/+$/g, '')
|
||||
for (const file of this.fileInput.files) this.enqueue(new FileUpload(this, file, folder))
|
||||
this.fileInput.value = ''
|
||||
})
|
||||
window.addEventListener('beforeunload', (event) => {
|
||||
if (this.active || this.queue.length) {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
enqueue (upload) {
|
||||
if (!this.queue.includes(upload) && this.active !== upload) {
|
||||
upload.setStatus('Waiting')
|
||||
this.queue.push(upload)
|
||||
}
|
||||
this.next()
|
||||
}
|
||||
|
||||
dequeue (upload) {
|
||||
this.queue = this.queue.filter((item) => item !== upload)
|
||||
}
|
||||
|
||||
async next () {
|
||||
if (this.active || !this.queue.length) return
|
||||
this.active = this.queue.shift()
|
||||
try {
|
||||
await this.active.run()
|
||||
} finally {
|
||||
this.active = null
|
||||
this.next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function initUploaders () {
|
||||
for (const form of document.querySelectorAll('form[data-uploader]')) new Uploader(form) // eslint-disable-line no-new
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
$font-size-base: 1rem !default; // Assumes the browser default, typically `16px`
|
||||
$h1-font-size: $font-size-base * 1.75 !default;
|
||||
$h2-font-size: $font-size-base * 1.5 !default;
|
||||
$h3-font-size: $font-size-base * 1.35 !default;
|
||||
$h4-font-size: $font-size-base * 1.25 !default;
|
||||
$h5-font-size: $font-size-base * 1.15 !default;
|
||||
$h6-font-size: $font-size-base !default;
|
||||
|
||||
|
||||
$white: #ffffff;
|
||||
|
||||
$theme-colors: (
|
||||
"light": #fdc8b2,
|
||||
"dark": #e4440f,
|
||||
"primary": #18499b,
|
||||
"secondary": #a65d66,
|
||||
"info": #da9a37,
|
||||
"success": #17a762,
|
||||
"warning": #e3cc17,
|
||||
"danger": #f31b0a,
|
||||
);
|
||||
|
||||
@import "bootstrap/scss/bootstrap";
|
||||
|
||||
form.simpleform input[type=text], form.simpleform textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
form.simpleform label {
|
||||
font-weight: bold;
|
||||
font-size: 1.2em;
|
||||
}
|
||||
|
||||
div.tox-tinymce div.tox-promotion {
|
||||
display: none;
|
||||
}
|
||||
|
||||
//span.tox-statusbar__branding {
|
||||
// display: none;
|
||||
//}
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const autoprefixer = require('autoprefixer')
|
||||
const miniCssExtractPlugin = require('mini-css-extract-plugin')
|
||||
|
||||
module.exports = {
|
||||
mode: 'development',
|
||||
entry: './src/js/main.js',
|
||||
output: {
|
||||
filename: 'main.js',
|
||||
path: path.resolve(__dirname, 'privatestudio/static/bundle')
|
||||
},
|
||||
plugins: [
|
||||
new miniCssExtractPlugin()
|
||||
],
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.(scss)$/,
|
||||
use: [
|
||||
{
|
||||
// loader: 'style-loader'
|
||||
loader: miniCssExtractPlugin.loader
|
||||
},
|
||||
{
|
||||
loader: 'css-loader'
|
||||
},
|
||||
{
|
||||
loader: 'postcss-loader',
|
||||
options: {
|
||||
postcssOptions: {
|
||||
plugins: [autoprefixer]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
loader: 'sass-loader'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user