Compare commits
17
Commits
46adddd50a
...
v0.3.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97fba1f0eb | ||
|
|
73b549cb18 | ||
|
|
1e7483d9c6 | ||
|
|
de13523ffd | ||
|
|
b5fd00250b | ||
|
|
23218b15f5 | ||
|
|
5d7d03a0a6 | ||
|
|
38f3a0da2f | ||
|
|
ba76671795 | ||
|
|
7231f69014 | ||
|
|
e582cb9234 | ||
|
|
5bb9a70c11 | ||
|
|
3fe49b47ea | ||
|
|
d73dddc3d9 | ||
|
|
3bbb57760e | ||
|
|
af18031a14 | ||
|
|
b3b51f6cc5 |
@@ -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."
|
||||
@@ -10,3 +10,10 @@ storage/
|
||||
__pycache__/
|
||||
|
||||
*.db
|
||||
|
||||
db.sqlite3
|
||||
db.sqlite3-shm
|
||||
db.sqlite3-wal
|
||||
privatestudio/settings/local.py
|
||||
privatestudio/static/bundle/
|
||||
node_modules/
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
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 debian:trixie-slim AS bento4
|
||||
|
||||
# Bento4 tools for HLS packaging (mp4fragment, mp4hls).
|
||||
ARG BENTO4_VERSION=1-6-0-641
|
||||
ARG BENTO4_SHA256=d48dc6b164941212e5614237b4d9aeff81d4d111ee8b1508892764078a0870e8
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl unzip \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN curl -fsSLo /tmp/bento4.zip "https://www.bok.net/Bento4/binaries/Bento4-SDK-${BENTO4_VERSION}.x86_64-unknown-linux.zip" \
|
||||
&& echo "${BENTO4_SHA256} /tmp/bento4.zip" | sha256sum -c - \
|
||||
&& unzip -q /tmp/bento4.zip -d /tmp \
|
||||
&& mkdir -p /opt/bento4 \
|
||||
&& cp -r "/tmp/Bento4-SDK-${BENTO4_VERSION}.x86_64-unknown-linux/bin" "/tmp/Bento4-SDK-${BENTO4_VERSION}.x86_64-unknown-linux/utils" /opt/bento4/
|
||||
|
||||
|
||||
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 apt-get update && apt-get install -y --no-install-recommends ffmpeg \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=bento4 /opt/bento4 /opt/bento4
|
||||
ENV PATH="/opt/bento4/bin:${PATH}"
|
||||
|
||||
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"]
|
||||
|
||||
# Run the job worker from the same image with the same /data volume:
|
||||
# docker run -v privatestudio-data:/data <image> python manage.py run_worker
|
||||
# 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
|
||||
@@ -1,24 +1,17 @@
|
||||
# Private Studio - Video Transcoding Web Service
|
||||
|
||||
A FastAPI-based video transcoding management service with S3-compatible file uploads, API key authentication, and per-user resource isolation.
|
||||
A Django video transcoding management service. It provides S3-compatible file storage, API key authentication, and studio-based access control.
|
||||
|
||||
## Features
|
||||
|
||||
- **S3-Compatible Interface**: Upload, download, delete, and list files using S3-compatible HTTP endpoints
|
||||
- **API Key Authentication**: Secure bearer token authentication with per-user isolation
|
||||
- **YAML-Based Transcode API**: Request transcode jobs and manage encoding profiles via YAML
|
||||
- **SQLite Database**: Lightweight file-based database with SQLAlchemy ORM
|
||||
- **User Management**: Create users and API keys via CLI
|
||||
- **Studios**: each studio owns one S3 bucket. Members of the studio's Django group can access it.
|
||||
- **S3-compatible interface**: upload, download, delete and list objects with bearer tokens or AWS v4 signatures (works with boto3).
|
||||
- **JSON API** ([Django Ninja](https://django-ninja.dev/)): manage API keys, temporary S3 credentials, transcode profiles and transcode jobs. Interactive docs are at `/api/docs`.
|
||||
- **Django admin** for managing users, groups, studios and jobs.
|
||||
|
||||
## Installation
|
||||
|
||||
Install the package with all dependencies:
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
Or install development dependencies:
|
||||
Requires Python 3.12+.
|
||||
|
||||
```bash
|
||||
pip install -e ".[dev]"
|
||||
@@ -26,329 +19,152 @@ pip install -e ".[dev]"
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Initialize Database
|
||||
|
||||
```bash
|
||||
ps-serve init
|
||||
python manage.py migrate
|
||||
python manage.py createsuperuser
|
||||
python manage.py create_studio demo --name "Demo Studio" --group demo-team --add-user <username>
|
||||
python manage.py create_key <username>
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
This creates a `transcoding.db` file in the current directory.
|
||||
`create_key` prints the API key once. Keep it secret.
|
||||
|
||||
### 2. Create a User
|
||||
To grant someone access to a studio, add them to the studio's group, either in the admin (`/admin/`) or with `create_studio --add-user` when the studio is created.
|
||||
|
||||
```bash
|
||||
ps-serve create-user myuser
|
||||
```
|
||||
See [README_SERVE.md](README_SERVE.md) for the full command guide.
|
||||
|
||||
### 3. Create an API Key
|
||||
|
||||
```bash
|
||||
ps-serve create-key 1
|
||||
```
|
||||
|
||||
This outputs an API key that should be kept secret:
|
||||
## Project Layout
|
||||
|
||||
```
|
||||
API key created for user 1
|
||||
Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
|
||||
Keep this key safe - you won't be able to see it again!
|
||||
manage.py
|
||||
privatestudio/
|
||||
settings/base.py # shared settings
|
||||
settings/dev.py # default (DJANGO_SETTINGS_MODULE=privatestudio.settings.dev)
|
||||
settings/production.py # env-driven production settings
|
||||
urls.py, wsgi.py, asgi.py
|
||||
studio/ # Django app: models, API routers, S3 views, management commands
|
||||
transcode.py # ps-transcode CLI (ffmpeg wrapper)
|
||||
```
|
||||
|
||||
### 4. Start the Server
|
||||
|
||||
```bash
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
The server will start at `http://localhost:8000`
|
||||
|
||||
## Configuration
|
||||
|
||||
Environment variables:
|
||||
Settings live in the `privatestudio.settings` package. Choose one with `DJANGO_SETTINGS_MODULE`:
|
||||
- `privatestudio.settings.dev` is the default. You can add overrides in an optional, git-ignored `privatestudio/settings/local.py`.
|
||||
- `privatestudio.settings.production` is configured from the environment variables below.
|
||||
|
||||
- `DATABASE_URL`: SQLite database path (default: `./transcoding.db`)
|
||||
- `STORAGE_PATH`: File storage directory (default: `./storage`)
|
||||
- `SERVER_HOST`: Server host address (default: `0.0.0.0`)
|
||||
- `SERVER_PORT`: Server port (default: `8000`)
|
||||
- `SQL_ECHO`: Enable SQL query logging (default: `false`)
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="sqlite:///./my_transcoding.db"
|
||||
export STORAGE_PATH="./media"
|
||||
ps-serve serve --host 127.0.0.1 --port 8080
|
||||
```
|
||||
| Variable | Used by | Description |
|
||||
|---|---|---|
|
||||
| `STORAGE_PATH` | all | File storage root (default `<repo>/storage`) |
|
||||
| `S3_CREDENTIAL_TTL_HOURS` | all | Lifetime of `/api/s3keys` credentials (default `1`) |
|
||||
| `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`) |
|
||||
| `BENTO4_BIN` | all | Directory with the Bento4 tools used by `run_worker` (default: find them on `PATH`) |
|
||||
| `WORKER_STALE_SECONDS` | all | A running job without a worker heartbeat for this long is marked failed (default `300`) |
|
||||
| `DJANGO_TIME_ZONE` | all | Time zone (default `UTC`) |
|
||||
| `SECRET_KEY` | production | Django secret key |
|
||||
| `ALLOWED_HOSTS` | production | Comma-separated host names |
|
||||
| `DATABASE_URL` | production | Database URL parsed by `dj-database-url` (default SQLite `db.sqlite3`) |
|
||||
| `CORS_ALLOWED_ORIGINS` | production | Comma-separated allowed CORS origins |
|
||||
| `SECURE_PROXY_SSL_HEADER` | production | Set to trust `X-Forwarded-Proto` from a proxy |
|
||||
|
||||
## API Usage
|
||||
|
||||
### Authentication
|
||||
All endpoints except `/health` need `Authorization: Bearer <API_KEY>`. The S3 endpoints also accept AWS v4 signatures made with credentials from `/api/s3keys`.
|
||||
|
||||
All endpoints require an API key via Bearer token:
|
||||
### Account
|
||||
|
||||
| Method | Path | Description |
|
||||
|---|---|---|
|
||||
| GET | `/api/userinfo` | User id, username, and the studios (buckets) the user can access |
|
||||
| POST | `/api/keys` | Create an API key |
|
||||
| GET | `/api/keys` | List your API keys |
|
||||
| DELETE | `/api/keys/{id}` | Revoke an API key |
|
||||
| POST | `/api/s3keys` | Create temporary S3 access/secret keys |
|
||||
|
||||
### S3-compatible storage
|
||||
|
||||
| Method | Path | Description |
|
||||
|---|---|---|
|
||||
| PUT | `/s3/{bucket}/{key}` | Upload: either a raw body, or multipart with a `file` field |
|
||||
| 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 -H "Authorization: Bearer YOUR_API_KEY" http://localhost:8000/api/keys
|
||||
curl -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 \
|
||||
http://localhost:8000/s3/demo/videos/video.mp4
|
||||
```
|
||||
|
||||
### S3-Compatible File Operations
|
||||
With boto3 (AWS v4 signatures):
|
||||
|
||||
Upload a file:
|
||||
```python
|
||||
import boto3, requests
|
||||
from botocore.config import Config
|
||||
|
||||
```bash
|
||||
curl -X PUT \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-F "file=@video.mp4" \
|
||||
http://localhost:8000/s3/1/videos/video.mp4
|
||||
creds = requests.post("http://localhost:8000/api/s3keys",
|
||||
headers={"Authorization": f"Bearer {KEY}"}).json()
|
||||
s3 = boto3.client("s3", endpoint_url="http://localhost:8000/s3",
|
||||
aws_access_key_id=creds["access_key"],
|
||||
aws_secret_access_key=creds["secret_key"],
|
||||
region_name="us-east-1",
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}))
|
||||
s3.upload_file("video.mp4", "demo", "videos/video.mp4")
|
||||
```
|
||||
|
||||
Download a file:
|
||||
`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.
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1/videos/video.mp4 \
|
||||
-o video.mp4
|
||||
```
|
||||
### Browser uploads
|
||||
|
||||
List files:
|
||||
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:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1
|
||||
```
|
||||
| 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 |
|
||||
|
||||
Delete a file:
|
||||
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)).
|
||||
|
||||
```bash
|
||||
curl -X DELETE \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1/videos/video.mp4
|
||||
```
|
||||
### Transcode profiles and jobs (per studio)
|
||||
|
||||
### Transcode Profile Management
|
||||
| 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}` | |
|
||||
|
||||
Create a profile:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/yaml" \
|
||||
-d @profile.yaml \
|
||||
http://localhost:8000/api/profiles?name=my-profile
|
||||
```
|
||||
|
||||
Where `profile.yaml`:
|
||||
The asset in a job request can be given as its key, its filename or its ID. The profile can be a profile name or an inline definition:
|
||||
|
||||
```yaml
|
||||
profiles:
|
||||
hd:
|
||||
resolution: "1280x720"
|
||||
bitrate: "2500k"
|
||||
fps: 30
|
||||
sd:
|
||||
resolution: "854x480"
|
||||
bitrate: "1000k"
|
||||
fps: 30
|
||||
asset: videos/video.mp4
|
||||
profile: hd-profile
|
||||
```
|
||||
|
||||
List profiles:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/profiles
|
||||
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/yaml" \
|
||||
--data-binary @job.yaml http://localhost:8000/api/studios/demo/transcode
|
||||
```
|
||||
|
||||
### Transcode Job Requests
|
||||
Pending jobs are run by `python manage.py run_worker` (see [README_SERVE.md](README_SERVE.md)).
|
||||
|
||||
Request a transcode job with a stored profile:
|
||||
## Storage
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/yaml" \
|
||||
-d 'asset: video.mp4
|
||||
profile: my-profile' \
|
||||
http://localhost:8000/api/transcode
|
||||
```
|
||||
|
||||
Or with an inline profile:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/yaml" \
|
||||
-d 'asset: video.mp4
|
||||
profile:
|
||||
profiles:
|
||||
hd:
|
||||
resolution: "1280x720"
|
||||
bitrate: "2500k"' \
|
||||
http://localhost:8000/api/transcode
|
||||
```
|
||||
|
||||
Get job status:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/transcode/1
|
||||
```
|
||||
|
||||
List jobs:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/transcode
|
||||
```
|
||||
|
||||
List jobs by status:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/transcode?status=pending
|
||||
```
|
||||
|
||||
### API Key Management
|
||||
|
||||
Create an API key:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/keys
|
||||
```
|
||||
|
||||
List keys:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/keys
|
||||
```
|
||||
|
||||
Revoke a key:
|
||||
|
||||
```bash
|
||||
curl -X DELETE \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/keys/KEY_ID
|
||||
```
|
||||
Files are stored under `STORAGE_PATH/<bucket_name>/<key>`. Keys that resolve outside the bucket directory are rejected.
|
||||
|
||||
## Testing
|
||||
|
||||
Run the test suite:
|
||||
|
||||
```bash
|
||||
pytest tests/test_web.py -v
|
||||
```
|
||||
|
||||
## Database Schema
|
||||
|
||||
### Users
|
||||
|
||||
- `id`: Primary key
|
||||
- `username`: Unique username
|
||||
- `created_at`: Creation timestamp
|
||||
|
||||
### API Keys
|
||||
|
||||
- `id`: Primary key
|
||||
- `key_hash`: SHA256 hash of the API key
|
||||
- `user_id`: Foreign key to users
|
||||
- `created_at`: Creation timestamp
|
||||
- `is_active`: Whether the key is active
|
||||
|
||||
### Uploaded Assets
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `filename`: Original filename
|
||||
- `size`: File size in bytes
|
||||
- `s3_path`: Path relative to storage root
|
||||
- `upload_timestamp`: Upload time
|
||||
|
||||
### Transcode Profiles
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `name`: Profile name
|
||||
- `profile_definition`: YAML definition as string
|
||||
- `created_at`: Creation timestamp
|
||||
|
||||
### Transcode Jobs
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `asset_id`: Foreign key to uploaded_assets
|
||||
- `profile_id`: Foreign key to transcode_profiles (nullable for inline profiles)
|
||||
- `status`: Job status (pending, in_progress, completed, failed)
|
||||
- `requested_at`: Request timestamp
|
||||
- `completed_at`: Completion timestamp (nullable)
|
||||
|
||||
### Packaging Jobs
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `transcode_job_id`: Foreign key to transcode_jobs
|
||||
- `status`: Job status (pending, in_progress, completed, failed)
|
||||
- `requested_at`: Request timestamp
|
||||
- `completed_at`: Completion timestamp (nullable)
|
||||
|
||||
### Transcoded Assets
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `transcode_job_id`: Foreign key to transcode_jobs
|
||||
- `filename`: Output filename
|
||||
- `s3_path`: Path relative to storage root
|
||||
- `format`: Output format (e.g., "mp4", "audio")
|
||||
- `created_at`: Creation timestamp
|
||||
|
||||
## Architecture
|
||||
|
||||
### Authentication
|
||||
|
||||
API keys are stored as SHA256 hashes in the database and validated via FastAPI's HTTPBearer security scheme. Each authenticated endpoint receives the user context automatically.
|
||||
|
||||
### Per-User Isolation
|
||||
|
||||
All resources (assets, profiles, jobs) are scoped to the authenticated user. Users can only access their own resources, enforced at the database query level.
|
||||
|
||||
### File Storage
|
||||
|
||||
Files are stored on disk in user-specific directories under `STORAGE_PATH`:
|
||||
|
||||
```
|
||||
storage/
|
||||
├── 1/ (user 1)
|
||||
│ ├── video1.mp4
|
||||
│ └── video2.mp4
|
||||
└── 2/ (user 2)
|
||||
└── presentation.mp4
|
||||
```
|
||||
|
||||
Symlink traversal attacks are prevented by validating file paths.
|
||||
|
||||
## Development
|
||||
|
||||
### Enable Auto-Reload
|
||||
|
||||
```bash
|
||||
ps-serve serve --reload
|
||||
```
|
||||
|
||||
### View SQL Queries
|
||||
|
||||
```bash
|
||||
export SQL_ECHO=true
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
pytest tests/test_web.py -v
|
||||
```
|
||||
|
||||
With coverage:
|
||||
|
||||
```bash
|
||||
pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
|
||||
pytest
|
||||
```
|
||||
|
||||
+78
-500
@@ -1,541 +1,119 @@
|
||||
# ps-serve Command Guide
|
||||
# Running and Managing Private Studio
|
||||
|
||||
A comprehensive guide to using the `ps-serve` command-line interface for managing the Private Studio video transcoding service.
|
||||
Private Studio is a standard Django project. All administration goes through `manage.py`, which uses `privatestudio.settings.dev` unless `DJANGO_SETTINGS_MODULE` is set.
|
||||
|
||||
## Overview
|
||||
|
||||
`ps-serve` is the command-line tool for Private Studio. It provides commands to:
|
||||
- Initialize the database
|
||||
- Create and manage user accounts
|
||||
- Generate and manage API keys
|
||||
- Start the web server
|
||||
|
||||
## Installation for Testing
|
||||
|
||||
### Quick Setup in a Virtual Environment
|
||||
|
||||
If you want to test the web service locally, here's the fastest way to get started:
|
||||
|
||||
#### 1. Clone the Repository
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yourusername/privatestudio.git
|
||||
cd privatestudio
|
||||
```
|
||||
|
||||
#### 2. Create a Virtual Environment
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
```
|
||||
|
||||
#### 3. Install in Development Mode
|
||||
|
||||
```bash
|
||||
pip install -e ".[dev]"
|
||||
```
|
||||
|
||||
This installs the package in "editable" mode, which means:
|
||||
- Changes to the code are immediately reflected
|
||||
- All dependencies (FastAPI, SQLAlchemy, etc.) are installed
|
||||
- Development tools (pytest, httpx) are also installed
|
||||
|
||||
#### 4. Verify Installation
|
||||
|
||||
```bash
|
||||
ps-serve --help
|
||||
```
|
||||
|
||||
You should see the help output showing all available commands.
|
||||
|
||||
### Virtual Environment Location
|
||||
|
||||
Keep your virtual environment separate from the source code:
|
||||
|
||||
```bash
|
||||
# Recommended structure
|
||||
~/projects/privatestudio/
|
||||
├── venv/ # Virtual environment (git-ignored)
|
||||
├── privatestudio/ # Source code
|
||||
├── tests/
|
||||
├── pyproject.toml
|
||||
└── README.md
|
||||
```
|
||||
|
||||
### Updating Your Installation
|
||||
|
||||
When you pull new changes from git:
|
||||
|
||||
```bash
|
||||
# Activate your virtual environment
|
||||
source venv/bin/activate
|
||||
|
||||
# Reinstall to pick up new dependencies
|
||||
pip install -e ".[dev]"
|
||||
|
||||
# Run tests to verify everything works
|
||||
pytest tests/test_web.py -v
|
||||
python manage.py migrate
|
||||
```
|
||||
|
||||
## Commands Reference
|
||||
## Access Model
|
||||
|
||||
### ps-serve init
|
||||
- **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.
|
||||
|
||||
Initialize the database for a new installation.
|
||||
## Commands
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve init
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Creates a `transcoding.db` SQLite database file in the current directory
|
||||
- Creates all tables (users, api_keys, assets, jobs, profiles, etc.)
|
||||
- Safe to run multiple times (idempotent)
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
$ mkdir ~/transcoding-server && cd ~/transcoding-server
|
||||
$ ps-serve init
|
||||
Database initialized
|
||||
$ ls
|
||||
transcoding.db
|
||||
```
|
||||
|
||||
**Environment Variable:**
|
||||
- `DATABASE_URL`: Path to database (default: `./transcoding.db`)
|
||||
### Create users
|
||||
|
||||
```bash
|
||||
DATABASE_URL="sqlite:///var/lib/privatestudio/transcoding.db" ps-serve init
|
||||
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/`.
|
||||
|
||||
### ps-serve create-user
|
||||
|
||||
Create a new user account for API access.
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve create-user <username>
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
- `<username>`: The username for the new account (must be unique)
|
||||
|
||||
**What it does:**
|
||||
- Creates a new user in the database
|
||||
- Returns the user ID (needed for creating API keys)
|
||||
- Users can have multiple API keys
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
$ ps-serve create-user alice
|
||||
User created: alice (ID: 1)
|
||||
|
||||
$ ps-serve create-user bob
|
||||
User created: bob (ID: 2)
|
||||
```
|
||||
|
||||
**Error Handling:**
|
||||
```bash
|
||||
$ ps-serve create-user alice
|
||||
Error: User 'alice' already exists
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
The command prints the username and user ID, which you'll need for the next step.
|
||||
|
||||
---
|
||||
|
||||
### ps-serve create-key
|
||||
|
||||
Generate a new API key for a user.
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve create-key <user_name>
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
- `<user_name>`: The username of the user (obtained from `create-user` output)
|
||||
|
||||
**What it does:**
|
||||
- Generates a random 32-character API key
|
||||
- Stores the SHA256 hash in the database
|
||||
- Prints the plain key (save this somewhere safe!)
|
||||
- The key cannot be recovered later—users must create a new one if lost
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
$ ps-serve create-key alice
|
||||
API key created for user alice
|
||||
Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
|
||||
Keep this key safe - you won't be able to see it again!
|
||||
```
|
||||
|
||||
**Security Notes:**
|
||||
- The key is only displayed once
|
||||
- Store it securely (environment variable, secret manager, encrypted file)
|
||||
- Never commit it to version control
|
||||
- Users can have multiple active keys (useful for key rotation)
|
||||
|
||||
**Example Workflow:**
|
||||
```bash
|
||||
# Create two keys for the same user (one for testing, one for production)
|
||||
$ ps-serve create-key alice
|
||||
Key: test_key_abc123...
|
||||
|
||||
$ ps-serve create-key alice
|
||||
Key: prod_key_xyz789...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ps-serve serve
|
||||
|
||||
Start the FastAPI web server.
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve serve [OPTIONS]
|
||||
```
|
||||
|
||||
**Options:**
|
||||
```
|
||||
--host HOST Server host address (default: 0.0.0.0)
|
||||
--port PORT Server port (default: 8000)
|
||||
--reload Enable auto-reload on code changes (for development)
|
||||
--log-level LEVEL Log level: debug, info, warning, error (default: info)
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Starts the FastAPI server
|
||||
- Initializes the database if it doesn't exist
|
||||
- Listens for HTTP requests
|
||||
- Logs all requests and errors
|
||||
|
||||
**Examples:**
|
||||
|
||||
**Start with defaults:**
|
||||
```bash
|
||||
$ ps-serve serve
|
||||
INFO: Application startup complete
|
||||
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
**Development mode with auto-reload:**
|
||||
```bash
|
||||
ps-serve serve --reload
|
||||
```
|
||||
|
||||
Changes to Python files will automatically restart the server.
|
||||
|
||||
**Custom host and port:**
|
||||
```bash
|
||||
ps-serve serve --host 127.0.0.1 --port 5000
|
||||
```
|
||||
|
||||
Now the server is only accessible locally at `http://127.0.0.1:5000`
|
||||
|
||||
**Detailed logging:**
|
||||
```bash
|
||||
ps-serve serve --log-level debug
|
||||
```
|
||||
|
||||
**All options together:**
|
||||
```bash
|
||||
ps-serve serve --host localhost --port 8080 --reload --log-level debug
|
||||
```
|
||||
|
||||
**Environment Variables:**
|
||||
These can also be set via environment variables:
|
||||
- `SERVER_HOST`: Server host (default: `0.0.0.0`)
|
||||
- `SERVER_PORT`: Server port (default: `8000`)
|
||||
- `DATABASE_URL`: Database path (default: `./transcoding.db`)
|
||||
- `STORAGE_PATH`: File storage directory (default: `./storage`)
|
||||
- `SQL_ECHO`: Log all SQL queries (true/false)
|
||||
|
||||
Example:
|
||||
```bash
|
||||
export SERVER_HOST=localhost
|
||||
export SERVER_PORT=9000
|
||||
export STORAGE_PATH=/media/transcoding
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Complete Workflow
|
||||
|
||||
Here's a typical setup workflow from start to finish:
|
||||
|
||||
### 1. Initialize Database
|
||||
### create_studio
|
||||
|
||||
```bash
|
||||
mkdir ~/my-transcoding-server
|
||||
cd ~/my-transcoding-server
|
||||
ps-serve init
|
||||
python manage.py create_studio <bucket_name> --group <group> [--name "Display Name"] [--add-user USER ...]
|
||||
```
|
||||
|
||||
### 2. Create Users
|
||||
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
|
||||
ps-serve create-user alice
|
||||
ps-serve create-user bob
|
||||
python manage.py create_key <username>
|
||||
```
|
||||
|
||||
### 3. Create API Keys
|
||||
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
|
||||
ps-serve create-key alice # For alice
|
||||
# Save this key somewhere secure
|
||||
ps-serve create-key bob # For bob
|
||||
python manage.py runserver 0.0.0.0:8000
|
||||
```
|
||||
|
||||
### 4. Start the Server
|
||||
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
|
||||
ps-serve serve
|
||||
python manage.py cleanup_uploads [--days 7] [--dry-run]
|
||||
```
|
||||
|
||||
### 5. Use the API
|
||||
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.
|
||||
|
||||
In another terminal:
|
||||
### run_worker
|
||||
|
||||
```bash
|
||||
# Upload a video
|
||||
curl -X PUT \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-F "file=@myvideo.mp4" \
|
||||
http://localhost:8000/s3/1/videos/myvideo.mp4
|
||||
|
||||
# List uploaded files
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1
|
||||
python manage.py run_worker [--poll-interval 5] [--once]
|
||||
```
|
||||
|
||||
---
|
||||
Runs pending transcode jobs with ffmpeg, then their packaging jobs with Bento4 (`mp4fragment` and `mp4hls` on `PATH`, or in `BENTO4_BIN`). Run it as a separate long-lived process next to the web server, on the same database and `STORAGE_PATH`. `--once` runs the jobs that are pending now and exits.
|
||||
|
||||
- Transcode outputs are stored at `transcodes/<transcode job slug>/` in the studio's bucket, and HLS packages at `packages/<packaging job slug>/hls/` (playlist `master.m3u8`). Work files are kept in `STORAGE_PATH/.work/` while a job runs.
|
||||
- On `SIGTERM` or `Ctrl-C`, the worker stops the running tool and returns the interrupted job to the queue.
|
||||
- While a job runs the worker records a heartbeat. A job without one for `WORKER_STALE_SECONDS` (the worker crashed or was killed) is marked failed.
|
||||
- With SQLite, the web server and worker share the database file through WAL mode. Keep the file on a local disk (a Docker volume is fine), not a network filesystem.
|
||||
|
||||
With Docker, run a second container from the same image and volume:
|
||||
|
||||
```bash
|
||||
docker run -d --name privatestudio-worker -v privatestudio-data:/data <image> python manage.py run_worker
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
### Command not found: ps-serve
|
||||
|
||||
**Problem:** `ps-serve: command not found`
|
||||
|
||||
**Solution:** Make sure you've activated the virtual environment and installed the package:
|
||||
|
||||
```bash
|
||||
source venv/bin/activate
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
### Database locked error
|
||||
|
||||
**Problem:** `sqlite3.OperationalError: database is locked`
|
||||
|
||||
**Solution:** SQLite doesn't handle concurrent writes well. For production:
|
||||
1. Stop any running servers
|
||||
2. Use PostgreSQL instead (change `DATABASE_URL`)
|
||||
3. Reduce concurrency
|
||||
|
||||
### Port already in use
|
||||
|
||||
**Problem:** `OSError: [Errno 48] Address already in use`
|
||||
|
||||
**Solution:** Use a different port:
|
||||
|
||||
```bash
|
||||
ps-serve serve --port 8001
|
||||
```
|
||||
|
||||
Or kill the existing process:
|
||||
|
||||
```bash
|
||||
# Find the process
|
||||
lsof -i :8000
|
||||
# Kill it
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
### API key not working
|
||||
|
||||
**Problem:** `401 Unauthorized: Invalid API key`
|
||||
|
||||
**Possible causes:**
|
||||
1. Wrong API key
|
||||
2. API key was revoked
|
||||
3. Key header is malformed (must be `Authorization: Bearer KEY`)
|
||||
|
||||
**Debug:**
|
||||
```bash
|
||||
# List all keys for a user
|
||||
curl -H "Authorization: Bearer YOUR_KEY" \
|
||||
http://localhost:8000/api/keys
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Running Tests
|
||||
|
||||
After making changes, run the test suite to ensure everything works:
|
||||
|
||||
```bash
|
||||
# Activate virtual environment
|
||||
source venv/bin/activate
|
||||
|
||||
# Run all tests
|
||||
pytest tests/test_web.py -v
|
||||
|
||||
# Run a specific test
|
||||
pytest tests/test_web.py::test_upload_file -v
|
||||
|
||||
# Run with coverage
|
||||
pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
|
||||
```
|
||||
|
||||
Coverage report is generated in `htmlcov/index.html`
|
||||
|
||||
---
|
||||
|
||||
## Development Tips
|
||||
|
||||
### 1. Auto-reload During Development
|
||||
|
||||
```bash
|
||||
ps-serve serve --reload
|
||||
```
|
||||
|
||||
Every time you save a Python file, the server will restart automatically.
|
||||
|
||||
### 2. View SQL Queries
|
||||
|
||||
```bash
|
||||
export SQL_ECHO=true
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
This logs all database queries to stdout for debugging.
|
||||
|
||||
### 3. Use a Specific Database
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="sqlite:///./test_db.db"
|
||||
ps-serve init
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
Useful for keeping multiple database instances (dev, test, prod).
|
||||
|
||||
### 4. Store Configuration in .env
|
||||
|
||||
Create a `.env` file:
|
||||
|
||||
```bash
|
||||
# .env
|
||||
DATABASE_URL=sqlite:///./transcoding.db
|
||||
STORAGE_PATH=./media
|
||||
SERVER_HOST=localhost
|
||||
SERVER_PORT=8000
|
||||
SQL_ECHO=false
|
||||
```
|
||||
|
||||
Then source it before running commands:
|
||||
|
||||
```bash
|
||||
source .env
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
Or use a tool like `python-dotenv`:
|
||||
|
||||
```bash
|
||||
pip install python-dotenv
|
||||
```
|
||||
|
||||
Then in your code or shell initialization.
|
||||
|
||||
---
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Protect API Keys**
|
||||
- Never commit keys to version control
|
||||
- Store in environment variables or secure vaults
|
||||
- Rotate keys regularly
|
||||
|
||||
2. **Database Security**
|
||||
- Use PostgreSQL for production (not SQLite)
|
||||
- Enable database backups
|
||||
- Run database on a separate server
|
||||
|
||||
3. **Network Security**
|
||||
- Use HTTPS in production (behind a reverse proxy like nginx)
|
||||
- Bind to localhost if only local access is needed
|
||||
- Implement rate limiting and authentication
|
||||
|
||||
4. **File Storage**
|
||||
- Keep storage directory outside the web root
|
||||
- Use a dedicated disk or object storage (S3, MinIO) for production
|
||||
- Implement backup strategy
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
After getting `ps-serve` running:
|
||||
|
||||
1. **Upload Your First Video**
|
||||
- See DEPLOYMENT.md for S3 API examples
|
||||
|
||||
2. **Create a Transcode Profile**
|
||||
- Define encoding profiles in YAML
|
||||
- Request transcode jobs
|
||||
|
||||
3. **Integrate with Your Application**
|
||||
- Use the REST API from your application
|
||||
- Handle job status polling
|
||||
|
||||
4. **Deploy to Production**
|
||||
- Use a real database (PostgreSQL)
|
||||
- Run behind nginx or similar proxy
|
||||
- Set up monitoring and backups
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
For more detailed information:
|
||||
|
||||
- **API Documentation**: Start the server and visit `http://localhost:8000/docs`
|
||||
- **Deployment Guide**: See `README.md`
|
||||
- **Source Code**: Check `privatestudio/web/` for implementation details
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference Cheat Sheet
|
||||
|
||||
```bash
|
||||
# Setup
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -e ".[dev]"
|
||||
|
||||
# First time
|
||||
ps-serve init
|
||||
ps-serve create-user myuser
|
||||
ps-serve create-key 1
|
||||
|
||||
# Development
|
||||
ps-serve serve --reload --log-level debug
|
||||
|
||||
# Testing
|
||||
pytest tests/test_web.py -v
|
||||
|
||||
# Production
|
||||
DATABASE_URL="postgresql://user:pass@localhost/psdb" \
|
||||
SERVER_HOST=0.0.0.0 \
|
||||
SERVER_PORT=8000 \
|
||||
ps-serve serve
|
||||
```
|
||||
- **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`.
|
||||
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/privatestudio/migrations
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
prepend_sys_path = .
|
||||
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the tzdata library which can be installed by adding
|
||||
# `alembic[tz]` to the pip requirements.
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to <script_location>/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
# file.
|
||||
sqlalchemy.url = sqlite:///./transcoding.db
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||
# hooks = ruff
|
||||
# ruff.type = module
|
||||
# ruff.module = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -32,6 +32,7 @@ def upload_asset(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
file_path: str,
|
||||
bucket: str,
|
||||
key: str,
|
||||
user_name: int = 1,
|
||||
) -> dict:
|
||||
@@ -58,9 +59,9 @@ def upload_asset(
|
||||
# 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()
|
||||
# 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()
|
||||
@@ -72,7 +73,7 @@ def upload_asset(
|
||||
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: {user_data.get('bucket')}")
|
||||
print(f" Bucket: {bucket}")
|
||||
|
||||
file_path_obj = Path(file_path)
|
||||
if not file_path_obj.exists():
|
||||
@@ -100,8 +101,7 @@ def upload_asset(
|
||||
try:
|
||||
# Upload the file
|
||||
file_size = file_path_obj.stat().st_size
|
||||
bucket = user_data['bucket']
|
||||
|
||||
|
||||
# print(f"\n{'='*60}")
|
||||
# print(f"Starting upload:")
|
||||
# print(f" File: {file_path}")
|
||||
@@ -190,6 +190,11 @@ Examples:
|
||||
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()
|
||||
|
||||
@@ -200,6 +205,7 @@ Examples:
|
||||
file_path=args.file,
|
||||
key=args.key,
|
||||
user_name=args.user_id,
|
||||
bucket=args.bucket,
|
||||
)
|
||||
print(f"\nUpload completed: {result}")
|
||||
return 0
|
||||
|
||||
@@ -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
|
||||
@@ -1,86 +0,0 @@
|
||||
from logging.config import fileConfig
|
||||
import os
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# Import your models
|
||||
from privatestudio.web.models import Base
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Use DATABASE_URL from environment or alembic.ini
|
||||
target_metadata = Base.metadata
|
||||
|
||||
def get_sqlalchemy_url():
|
||||
"""Get SQLAlchemy database URL from environment or config."""
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if url:
|
||||
return url
|
||||
return config.get_main_option("sqlalchemy.url")
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = get_sqlalchemy_url()
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
def run(connection):
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
connection = config.attributes.get("connection")
|
||||
if connection is not None:
|
||||
run(connection)
|
||||
return
|
||||
|
||||
configuration = config.get_section(config.config_ini_section, {})
|
||||
configuration["sqlalchemy.url"] = get_sqlalchemy_url()
|
||||
connectable = engine_from_config(
|
||||
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool
|
||||
)
|
||||
try:
|
||||
with connectable.connect() as connection:
|
||||
run(connection)
|
||||
finally:
|
||||
connectable.dispose()
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -1,29 +0,0 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import privatestudio.web.models
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -1,147 +0,0 @@
|
||||
"""Initial schema
|
||||
|
||||
Revision ID: 25cc5ed29873
|
||||
Revises:
|
||||
Create Date: 2026-11-22 16:57:27.821705
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import privatestudio.web.models
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '25cc5ed29873'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('bucket_name', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||
op.create_table('api_keys',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('key_hash', sa.Text(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('is_active', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_api_keys_key_hash'), 'api_keys', ['key_hash'], unique=True)
|
||||
op.create_table('s3_credentials',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('access_key', sa.Text(), nullable=False),
|
||||
sa.Column('secret_key', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('expires_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('authorized_key', sa.Text(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_s3_credentials_access_key'), 's3_credentials', ['access_key'], unique=True)
|
||||
op.create_index(op.f('ix_s3_credentials_user_id'), 's3_credentials', ['user_id'], unique=False)
|
||||
op.create_table('transcode_profiles',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.Text(), nullable=False),
|
||||
sa.Column('profile_definition', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_transcode_profiles_user_id'), 'transcode_profiles', ['user_id'], unique=False)
|
||||
op.create_table('uploaded_assets',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('filename', sa.Text(), nullable=False),
|
||||
sa.Column('size', sa.Integer(), nullable=False),
|
||||
sa.Column('s3_path', sa.Text(), nullable=False),
|
||||
sa.Column('upload_timestamp', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_uploaded_assets_user_id'), 'uploaded_assets', ['user_id'], unique=False)
|
||||
op.create_table('transcode_jobs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('asset_id', sa.Integer(), nullable=False),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=True),
|
||||
sa.Column('status', sa.Text(), nullable=False),
|
||||
sa.Column('requested_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('completed_at', privatestudio.web.models.TextDateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['asset_id'], ['uploaded_assets.id'], ),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['transcode_profiles.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_transcode_jobs_user_id'), 'transcode_jobs', ['user_id'], unique=False)
|
||||
op.create_table('packaging_jobs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('transcode_job_id', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.Text(), nullable=False),
|
||||
sa.Column('requested_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('completed_at', privatestudio.web.models.TextDateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['transcode_job_id'], ['transcode_jobs.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_packaging_jobs_user_id'), 'packaging_jobs', ['user_id'], unique=False)
|
||||
op.create_table('transcoded_assets',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('transcode_job_id', sa.Integer(), nullable=False),
|
||||
sa.Column('filename', sa.Text(), nullable=False),
|
||||
sa.Column('s3_path', sa.Text(), nullable=False),
|
||||
sa.Column('format', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['transcode_job_id'], ['transcode_jobs.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_transcoded_assets_user_id'), 'transcoded_assets', ['user_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_transcoded_assets_user_id'), table_name='transcoded_assets')
|
||||
op.drop_table('transcoded_assets')
|
||||
op.drop_index(op.f('ix_packaging_jobs_user_id'), table_name='packaging_jobs')
|
||||
op.drop_table('packaging_jobs')
|
||||
op.drop_index(op.f('ix_transcode_jobs_user_id'), table_name='transcode_jobs')
|
||||
op.drop_table('transcode_jobs')
|
||||
op.drop_index(op.f('ix_uploaded_assets_user_id'), table_name='uploaded_assets')
|
||||
op.drop_table('uploaded_assets')
|
||||
op.drop_index(op.f('ix_transcode_profiles_user_id'), table_name='transcode_profiles')
|
||||
op.drop_table('transcode_profiles')
|
||||
op.drop_index(op.f('ix_s3_credentials_user_id'), table_name='s3_credentials')
|
||||
op.drop_index(op.f('ix_s3_credentials_access_key'), table_name='s3_credentials')
|
||||
op.drop_table('s3_credentials')
|
||||
op.drop_index(op.f('ix_api_keys_key_hash'), table_name='api_keys')
|
||||
op.drop_table('api_keys')
|
||||
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||
op.drop_table('users')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
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
|
||||
|
||||
# The web server and the job worker use the database at the same time. WAL lets
|
||||
# readers and the writer proceed concurrently. IMMEDIATE takes the write lock when
|
||||
# a transaction starts, so a read-then-write waits (up to "timeout" seconds)
|
||||
# instead of failing with "database is locked".
|
||||
SQLITE_OPTIONS = {
|
||||
"transaction_mode": "IMMEDIATE",
|
||||
"timeout": 20,
|
||||
"init_command": "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;",
|
||||
}
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
|
||||
"OPTIONS": SQLITE_OPTIONS,
|
||||
}
|
||||
}
|
||||
|
||||
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"))
|
||||
|
||||
# Job worker (manage.py run_worker)
|
||||
# Directory holding the Bento4 tools (mp4fragment, mp4hls). Empty means use PATH.
|
||||
PRIVATESTUDIO_BENTO4_BIN = os.environ.get("BENTO4_BIN", "")
|
||||
# A running job without a heartbeat for this long is marked failed.
|
||||
PRIVATESTUDIO_WORKER_STALE_SECONDS = int(os.environ.get("WORKER_STALE_SECONDS", "300"))
|
||||
@@ -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,59 @@
|
||||
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"),
|
||||
"OPTIONS": SQLITE_OPTIONS, # noqa: F405
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -0,0 +1,8 @@
|
||||
import base64
|
||||
import uuid
|
||||
|
||||
|
||||
def random_slug(prefix='', length_limit=26):
|
||||
assert length_limit <= 26, "length_limit must be <= 26"
|
||||
slug = base64.b32encode(uuid.uuid4().bytes).decode('utf8').rstrip('=').lower()[:length_limit]
|
||||
return "{}-{}".format(prefix, slug) if prefix else slug
|
||||
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,103 @@
|
||||
from django import forms
|
||||
|
||||
from privatestudio.studio.models import ContentAsset, TranscodeJob, TranscodeProfile
|
||||
from privatestudio.studio.profiles import validate_profile_definition
|
||||
from privatestudio.fields import HtmlTextField
|
||||
|
||||
YAML_TEXTAREA_ATTRS = {"rows": 20, "spellcheck": "false", "class": "form-control font-monospace yaml-editor"}
|
||||
|
||||
|
||||
class BootstrapFormMixin:
|
||||
"""Adds Bootstrap classes to every widget that doesn't set its own."""
|
||||
|
||||
def apply_bootstrap(self):
|
||||
for field in self.fields.values():
|
||||
if "class" in field.widget.attrs:
|
||||
continue
|
||||
css = "form-select" if isinstance(field.widget, forms.Select) else "form-control"
|
||||
field.widget.attrs["class"] = css
|
||||
|
||||
|
||||
class ContentAssetForm(BootstrapFormMixin, 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()
|
||||
self.apply_bootstrap()
|
||||
|
||||
|
||||
class TranscodeProfileForm(BootstrapFormMixin, forms.ModelForm):
|
||||
class Meta:
|
||||
model = TranscodeProfile
|
||||
fields = ["name", "profile_definition"]
|
||||
widgets = {"profile_definition": forms.Textarea(attrs=YAML_TEXTAREA_ATTRS)}
|
||||
labels = {"profile_definition": "Profile definition (YAML)"}
|
||||
|
||||
def __init__(self, *args, studio, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.studio = studio
|
||||
self.apply_bootstrap()
|
||||
|
||||
def clean_name(self):
|
||||
name = self.cleaned_data["name"].strip()
|
||||
duplicates = TranscodeProfile.objects.filter(studio=self.studio, name=name)
|
||||
if self.instance.pk:
|
||||
duplicates = duplicates.exclude(pk=self.instance.pk)
|
||||
if duplicates.exists():
|
||||
raise forms.ValidationError("A profile with this name already exists in this studio.")
|
||||
return name
|
||||
|
||||
def clean_profile_definition(self):
|
||||
text = self.cleaned_data["profile_definition"]
|
||||
validate_profile_definition(text)
|
||||
return text
|
||||
|
||||
|
||||
class TranscodeJobForm(BootstrapFormMixin, forms.ModelForm):
|
||||
class Meta:
|
||||
model = TranscodeJob
|
||||
fields = ["profile", "profile_definition"]
|
||||
widgets = {"profile_definition": forms.Textarea(attrs=YAML_TEXTAREA_ATTRS)}
|
||||
labels = {"profile_definition": "Profile definition (YAML)"}
|
||||
help_texts = {
|
||||
"profile_definition": "Copied from the selected profile. Changes here apply to this job only. "
|
||||
"Leave empty to use the profile as saved.",
|
||||
}
|
||||
|
||||
def __init__(self, *args, studio, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["profile"].queryset = studio.transcode_profiles.order_by("name")
|
||||
self.apply_bootstrap()
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
profile = cleaned.get("profile")
|
||||
text = (cleaned.get("profile_definition") or "").strip()
|
||||
if not text and profile is not None:
|
||||
text = profile.profile_definition
|
||||
if not text:
|
||||
if "profile" not in self.errors:
|
||||
self.add_error("profile", "Choose a profile or enter a profile definition.")
|
||||
return cleaned
|
||||
try:
|
||||
validate_profile_definition(text)
|
||||
except forms.ValidationError as e:
|
||||
self.add_error("profile_definition", e)
|
||||
else:
|
||||
cleaned["profile_definition"] = text
|
||||
# Keep the instance in step with the copied definition before model validation runs.
|
||||
self.instance.profile_definition = text
|
||||
return cleaned
|
||||
@@ -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,47 @@
|
||||
import signal
|
||||
import threading
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.db import close_old_connections
|
||||
|
||||
from privatestudio.studio.worker import Worker, recover_stale_jobs
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Run pending transcode and packaging jobs."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("--poll-interval", type=float, default=5.0,
|
||||
help="Seconds to wait between checks when there is no work (default %(default)s)")
|
||||
parser.add_argument("--once", action="store_true",
|
||||
help="Run the jobs that are pending now, then exit")
|
||||
|
||||
def handle(self, *args, poll_interval, once, **options):
|
||||
worker = Worker()
|
||||
wake = threading.Event()
|
||||
|
||||
def shutdown(signum, frame):
|
||||
self.stdout.write("Shutting down; an interrupted job returns to the queue.")
|
||||
worker.stop()
|
||||
wake.set()
|
||||
|
||||
previous = {}
|
||||
if threading.current_thread() is threading.main_thread():
|
||||
for signum in (signal.SIGTERM, signal.SIGINT):
|
||||
previous[signum] = signal.signal(signum, shutdown)
|
||||
|
||||
self.stdout.write("Worker started.")
|
||||
try:
|
||||
while not worker.stopping:
|
||||
close_old_connections()
|
||||
recover_stale_jobs()
|
||||
if worker.run_once():
|
||||
continue
|
||||
if once:
|
||||
break
|
||||
wake.wait(poll_interval)
|
||||
finally:
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
close_old_connections()
|
||||
self.stdout.write("Worker stopped.")
|
||||
@@ -0,0 +1,232 @@
|
||||
# Generated by Django 6.1.3 on 2026-12-03 22:46
|
||||
|
||||
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):
|
||||
|
||||
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='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='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)),
|
||||
('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')),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='content_assets', to='studio.studio')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['group__title', 'season_number', 'episode_number', 'sequence_number', 'title'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodeJob',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('slug', models.SlugField(max_length=26, unique=True)),
|
||||
('profile_definition', models.TextField(blank=True, default='')),
|
||||
('status', models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], db_index=True, default='draft', max_length=20)),
|
||||
('requested_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('started_at', models.DateTimeField(blank=True, null=True)),
|
||||
('heartbeat_at', models.DateTimeField(blank=True, null=True)),
|
||||
('worker', models.CharField(blank=True, default='', max_length=255)),
|
||||
('completed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('transcode_output', models.TextField(blank=True, default='')),
|
||||
('content_asset', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to='studio.contentasset')),
|
||||
('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)),
|
||||
('content_asset', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcoded_assets', to='studio.contentasset')),
|
||||
('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')),
|
||||
('slug', models.SlugField(max_length=26, unique=True)),
|
||||
('status', models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], db_index=True, default='pending', max_length=20)),
|
||||
('requested_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('started_at', models.DateTimeField(blank=True, null=True)),
|
||||
('heartbeat_at', models.DateTimeField(blank=True, null=True)),
|
||||
('worker', models.CharField(blank=True, default='', max_length=255)),
|
||||
('completed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('output', models.TextField(blank=True, default='')),
|
||||
('manifest_path', models.TextField(blank=True, default='')),
|
||||
('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.AddField(
|
||||
model_name='contentasset',
|
||||
name='uploaded_asset',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='content_assets', to='studio.uploadedasset'),
|
||||
),
|
||||
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'],
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='contentgroup',
|
||||
constraint=models.UniqueConstraint(fields=('studio', 'kind', 'title'), name='unique_content_group_per_studio'),
|
||||
),
|
||||
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'),
|
||||
),
|
||||
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'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='uploadpart',
|
||||
constraint=models.UniqueConstraint(fields=('upload', 'part_number'), name='unique_part_per_upload'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,19 @@
|
||||
# Generated by Django 6.1.3 on 2026-12-03 23:07
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('studio', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='transcodejob',
|
||||
name='asset',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to='studio.uploadedasset'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,425 @@
|
||||
"""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
|
||||
|
||||
from privatestudio.slugger import random_slug
|
||||
|
||||
|
||||
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}"
|
||||
|
||||
def delete_blocker(self) -> str | None:
|
||||
"""Why this file can't be deleted now, or None if it can."""
|
||||
if self.transcode_jobs.filter(status__in=[JobStatus.PENDING, JobStatus.IN_PROGRESS]).exists():
|
||||
return "A transcode job using this file is queued or running. Delete the file after it finishes."
|
||||
return None
|
||||
|
||||
|
||||
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")
|
||||
slug = models.SlugField(max_length=26, unique=True)
|
||||
requested_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
|
||||
)
|
||||
# Null once the source file is deleted; the job and its outputs are kept.
|
||||
asset = models.ForeignKey(
|
||||
UploadedAsset, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
|
||||
)
|
||||
content_asset = models.ForeignKey(
|
||||
"ContentAsset", on_delete=models.SET_NULL, null=True, blank=True, 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.DRAFT, db_index=True)
|
||||
requested_at = models.DateTimeField(default=timezone.now)
|
||||
started_at = models.DateTimeField(null=True, blank=True)
|
||||
heartbeat_at = models.DateTimeField(null=True, blank=True)
|
||||
worker = models.CharField(max_length=255, blank=True, default="")
|
||||
completed_at = models.DateTimeField(null=True, blank=True)
|
||||
transcode_output = models.TextField(blank=True, default="")
|
||||
|
||||
def __str__(self):
|
||||
return f"Transcode job {self.slug} - {self.content_asset} ({self.status})"
|
||||
|
||||
@staticmethod
|
||||
def get_random_slug():
|
||||
return random_slug('tc', 15)
|
||||
|
||||
@property
|
||||
def is_editable(self) -> bool:
|
||||
return self.status == JobStatus.DRAFT
|
||||
|
||||
def clean(self):
|
||||
if self.pk is not None:
|
||||
stored = TranscodeJob.objects.filter(pk=self.pk).values_list("status", flat=True).first()
|
||||
if stored is not None and stored != JobStatus.DRAFT:
|
||||
raise ValidationError("Only draft jobs can be edited.")
|
||||
errors = {}
|
||||
if self.studio_id:
|
||||
if self.content_asset_id and self.content_asset.studio_id != self.studio_id:
|
||||
errors["content_asset"] = "The content must belong to the same studio."
|
||||
if self.profile_id and self.profile.studio_id != self.studio_id:
|
||||
errors["profile"] = "The profile must belong to the same studio."
|
||||
if self.asset_id and self.asset.studio_id != self.studio_id:
|
||||
errors["asset"] = "The file must belong to the same studio."
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
def submit(self) -> bool:
|
||||
"""Move a draft job to pending. Returns False if it was no longer a draft."""
|
||||
changed = TranscodeJob.objects.filter(pk=self.pk, status=JobStatus.DRAFT).update(status=JobStatus.PENDING)
|
||||
self.refresh_from_db(fields=["status"])
|
||||
return bool(changed)
|
||||
|
||||
def packaging_blocker(self) -> str | None:
|
||||
"""Why a new packaging job can't be added now, or None if it can."""
|
||||
if self.status == JobStatus.DRAFT:
|
||||
return "Submit the transcode job before packaging it."
|
||||
if self.status == JobStatus.FAILED:
|
||||
return "The transcode job failed, so there is nothing to package."
|
||||
if self.packaging_jobs.filter(status__in=[JobStatus.PENDING, JobStatus.IN_PROGRESS]).exists():
|
||||
return "A packaging job for this transcode is already queued or running."
|
||||
return None
|
||||
|
||||
@property
|
||||
def can_add_packaging_job(self) -> bool:
|
||||
return self.packaging_blocker() is None
|
||||
|
||||
@property
|
||||
def output_path(self) -> str:
|
||||
"""Bucket folder holding this job's transcoded files."""
|
||||
if not self.slug:
|
||||
# Without a slug this would be the folder shared by every transcode.
|
||||
raise ValueError("Transcode job has no slug")
|
||||
return f"transcodes/{self.slug}"
|
||||
|
||||
def delete_blocker(self) -> str | None:
|
||||
"""Why this job can't be deleted now, or None if it can."""
|
||||
if self.status == JobStatus.IN_PROGRESS:
|
||||
return "This transcode job is running and can't be deleted until it finishes."
|
||||
if self.packaging_jobs.exists():
|
||||
return "Delete this transcode job's packaging jobs first."
|
||||
return None
|
||||
|
||||
@property
|
||||
def is_deletable(self) -> bool:
|
||||
return self.delete_blocker() is None
|
||||
|
||||
|
||||
class PackagingJob(models.Model):
|
||||
"""Requested packaging operation."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="packaging_jobs")
|
||||
slug = models.SlugField(max_length=26, unique=True)
|
||||
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, db_index=True)
|
||||
requested_at = models.DateTimeField(default=timezone.now)
|
||||
started_at = models.DateTimeField(null=True, blank=True)
|
||||
heartbeat_at = models.DateTimeField(null=True, blank=True)
|
||||
worker = models.CharField(max_length=255, blank=True, default="")
|
||||
completed_at = models.DateTimeField(null=True, blank=True)
|
||||
output = models.TextField(blank=True, default="")
|
||||
# Bucket key of the HLS master playlist.
|
||||
manifest_path = models.TextField(blank=True, default="")
|
||||
|
||||
def __str__(self):
|
||||
return f"Packaging job {self.slug} - {self.transcode_job} ({self.status})"
|
||||
|
||||
@staticmethod
|
||||
def get_random_slug():
|
||||
return random_slug('p', 15)
|
||||
|
||||
@property
|
||||
def package_path(self) -> str:
|
||||
"""Bucket folder holding this job's packaged output."""
|
||||
if not self.slug:
|
||||
# Without a slug this would be the folder shared by every package.
|
||||
raise ValueError("Packaging job has no slug")
|
||||
return f"packages/{self.slug}"
|
||||
|
||||
@property
|
||||
def is_deletable(self) -> bool:
|
||||
# The worker may still be writing files for a running job.
|
||||
return self.status != JobStatus.IN_PROGRESS
|
||||
|
||||
|
||||
class TranscodedAsset(models.Model):
|
||||
"""Output file from a transcode job."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcoded_assets")
|
||||
# Null for jobs submitted through the API without a content entry.
|
||||
content_asset = models.ForeignKey(
|
||||
"ContentAsset", on_delete=models.SET_NULL, null=True, blank=True, 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 referencing_models(self) -> list[str]:
|
||||
"""Names of the models with records that point at this content entry."""
|
||||
names = []
|
||||
for relation in self._meta.related_objects:
|
||||
if relation.related_model._default_manager.filter(**{relation.field.name: self}).exists():
|
||||
names.append(str(relation.related_model._meta.verbose_name_plural))
|
||||
return names
|
||||
|
||||
@property
|
||||
def can_offer_delete(self) -> bool:
|
||||
"""Whether to show the delete button: no file and no transcode jobs."""
|
||||
return self.uploaded_asset_id is None and not self.transcode_jobs.exists()
|
||||
|
||||
def delete_blocker(self) -> str | None:
|
||||
"""Why this content entry can't be deleted now, or None if it can."""
|
||||
if self.uploaded_asset_id is not None:
|
||||
return "Delete its uploaded file first."
|
||||
referencing = self.referencing_models()
|
||||
if referencing:
|
||||
return f"Other records still refer to it ({', '.join(referencing)}). Delete those first."
|
||||
return None
|
||||
|
||||
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,83 @@
|
||||
"""Validation for YAML transcode profile definitions."""
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from privatestudio.transcode import ENCODER_MAP, parse_bitrate, parse_resolution
|
||||
|
||||
# Shipped inside the package (privatestudio/profiles/) so it is included in the wheel.
|
||||
DEFAULT_PROFILE_PATH = Path(__file__).resolve().parent.parent / "profiles" / "default.yaml"
|
||||
|
||||
EXAMPLE_PROFILE_YAML = """\
|
||||
# Optional: cpu, quicksync or nvidia (default cpu)
|
||||
encoder: cpu
|
||||
|
||||
# One entry per output rendition
|
||||
profiles:
|
||||
1080p:
|
||||
name: "Full HD" # optional label
|
||||
resolution: "1920x1080" # required, WIDTHxHEIGHT
|
||||
bitrate: "5000k" # optional, in kbit/s e.g. 2500k (default 1000k)
|
||||
codec: "h264" # optional (default h264)
|
||||
fps: 30 # optional (default 30)
|
||||
720p:
|
||||
resolution: "1280x720"
|
||||
bitrate: "2500k"
|
||||
"""
|
||||
|
||||
|
||||
def load_default_profile() -> str | None:
|
||||
"""Text of the bundled default profile, or None if it can't be read."""
|
||||
try:
|
||||
return DEFAULT_PROFILE_PATH.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def validate_profile_definition(text: str) -> dict:
|
||||
"""Parse a YAML profile definition and check its structure. Raises ValidationError."""
|
||||
try:
|
||||
data = yaml.safe_load(text or "")
|
||||
except yaml.YAMLError as e:
|
||||
mark = getattr(e, "problem_mark", None)
|
||||
where = f" (line {mark.line + 1}, column {mark.column + 1})" if mark else ""
|
||||
problem = getattr(e, "problem", None) or str(e)
|
||||
raise ValidationError(f"Invalid YAML{where}: {problem}")
|
||||
if not isinstance(data, dict):
|
||||
raise ValidationError("The definition must be a YAML mapping with a 'profiles' section.")
|
||||
|
||||
errors = []
|
||||
encoder = data.get("encoder")
|
||||
if encoder is not None and str(encoder).lower() not in ENCODER_MAP:
|
||||
errors.append(f"'encoder' must be one of: {', '.join(ENCODER_MAP)}.")
|
||||
|
||||
profiles = data.get("profiles")
|
||||
if not isinstance(profiles, dict) or not profiles:
|
||||
errors.append("'profiles' must be a mapping with at least one entry.")
|
||||
raise ValidationError(errors)
|
||||
|
||||
for key, variant in profiles.items():
|
||||
if not isinstance(variant, dict):
|
||||
errors.append(f"Profile '{key}' must be a mapping.")
|
||||
continue
|
||||
try:
|
||||
width, height = parse_resolution(variant.get("resolution"))
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError
|
||||
except (ValueError, TypeError):
|
||||
errors.append(f"Profile '{key}': 'resolution' is required in WIDTHxHEIGHT form, e.g. 1280x720.")
|
||||
if "bitrate" in variant:
|
||||
try:
|
||||
parse_bitrate(variant["bitrate"])
|
||||
except ValueError:
|
||||
errors.append(f"Profile '{key}': 'bitrate' must look like 2500k.")
|
||||
if "codec" in variant and not isinstance(variant["codec"], str):
|
||||
errors.append(f"Profile '{key}': 'codec' must be text.")
|
||||
if "fps" in variant:
|
||||
fps = variant["fps"]
|
||||
if isinstance(fps, bool) or not isinstance(fps, (int, float)) or fps <= 0:
|
||||
errors.append(f"Profile '{key}': 'fps' must be a positive number.")
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
return data
|
||||
@@ -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,69 @@
|
||||
"""Transcode profile management endpoints (scoped to a studio)."""
|
||||
from django.core.exceptions import ValidationError
|
||||
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.profiles import validate_profile_definition
|
||||
from privatestudio.studio.routers.common import get_studio_for_user
|
||||
|
||||
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)
|
||||
try:
|
||||
definition = request.body.decode("utf-8")
|
||||
validate_profile_definition(definition)
|
||||
except UnicodeDecodeError:
|
||||
raise HttpError(400, "The profile definition must be UTF-8 text")
|
||||
except ValidationError as e:
|
||||
raise HttpError(400, " ".join(e.messages))
|
||||
|
||||
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=definition,
|
||||
)
|
||||
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,107 @@
|
||||
"""YAML-based transcode job request endpoints (scoped to a studio)."""
|
||||
from typing import Optional
|
||||
|
||||
import yaml
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import JobStatus, TranscodeJob, TranscodeProfile, UploadedAsset
|
||||
from privatestudio.studio.profiles import validate_profile_definition
|
||||
from privatestudio.studio.routers.common import get_studio_for_user, parse_yaml_body
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class TranscodeJobResponse(Schema):
|
||||
id: int
|
||||
asset_id: Optional[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):
|
||||
profile_definition = yaml.safe_dump(profile_ref)
|
||||
try:
|
||||
validate_profile_definition(profile_definition)
|
||||
except ValidationError as e:
|
||||
raise HttpError(400, "Invalid inline profile: " + " ".join(e.messages))
|
||||
else:
|
||||
raise HttpError(400, "Profile must be a string (name) or object (definition)")
|
||||
|
||||
job = TranscodeJob.objects.create(
|
||||
slug=TranscodeJob.get_random_slug(),
|
||||
studio=studio,
|
||||
requested_by=request.auth,
|
||||
asset=asset,
|
||||
profile=profile,
|
||||
profile_definition=profile_definition,
|
||||
# API requests are submitted directly; drafts are only made in the web UI.
|
||||
status=JobStatus.PENDING,
|
||||
)
|
||||
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)],
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
"""AWS v4 signature verification and credential management."""
|
||||
import secrets
|
||||
import hashlib
|
||||
import hmac
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from urllib.parse import quote
|
||||
|
||||
from privatestudio.web.models import S3Credential
|
||||
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:
|
||||
@@ -22,55 +28,34 @@ def generate_secret_key() -> str:
|
||||
return secrets.token_urlsafe(32).replace("-", "").replace("_", "")[:40]
|
||||
|
||||
|
||||
def create_s3_credential(db: Session, user_id: int, ttl_hours: int = 1) -> tuple[str, str]:
|
||||
def create_s3_credential(user, ttl_hours: Optional[int] = None) -> S3Credential:
|
||||
"""
|
||||
Create temporary S3 credentials for a user.
|
||||
|
||||
Returns: (access_key, secret_key)
|
||||
|
||||
The returned credential carries the secret key; it is only shown to the
|
||||
user once, at creation time.
|
||||
"""
|
||||
access_key = generate_access_key()
|
||||
secret_key = generate_secret_key()
|
||||
|
||||
now = datetime.utcnow()
|
||||
expires_at = now + timedelta(hours=ttl_hours)
|
||||
|
||||
credential = S3Credential(
|
||||
user_id=user_id,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
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=expires_at,
|
||||
expires_at=now + timedelta(hours=ttl_hours),
|
||||
)
|
||||
db.add(credential)
|
||||
db.commit()
|
||||
db.refresh(credential)
|
||||
|
||||
return access_key, secret_key
|
||||
|
||||
|
||||
def get_s3_credential(db: Session, access_key: str) -> Optional[S3Credential]:
|
||||
def get_s3_credential(access_key: str) -> Optional[S3Credential]:
|
||||
"""Retrieve a non-expired S3 credential by access key."""
|
||||
credential = db.query(S3Credential).filter(
|
||||
S3Credential.access_key == access_key
|
||||
).first()
|
||||
|
||||
if not credential:
|
||||
return None
|
||||
|
||||
# Check if expired
|
||||
if datetime.utcnow() > credential.expires_at:
|
||||
return None
|
||||
|
||||
return credential
|
||||
return S3Credential.objects.filter(access_key=access_key, expires_at__gt=timezone.now()).first()
|
||||
|
||||
|
||||
def cleanup_expired_credentials(db: Session) -> int:
|
||||
def cleanup_expired_credentials() -> int:
|
||||
"""Delete all expired S3 credentials. Returns count of deleted credentials."""
|
||||
result = db.query(S3Credential).filter(
|
||||
S3Credential.expires_at <= datetime.utcnow()
|
||||
).delete()
|
||||
db.commit()
|
||||
return result
|
||||
deleted, _ = S3Credential.objects.filter(expires_at__lte=timezone.now()).delete()
|
||||
return deleted
|
||||
|
||||
|
||||
def sign_string(key: str, msg: str) -> str:
|
||||
@@ -89,19 +74,20 @@ def verify_aws_v4_signature(
|
||||
path: str,
|
||||
query_string: str,
|
||||
headers: dict,
|
||||
body: bytes,
|
||||
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: Request path
|
||||
path: Decoded request path
|
||||
query_string: Query string
|
||||
headers: Request headers dict
|
||||
body: Request body bytes
|
||||
secret_key: The secret key to verify against
|
||||
|
||||
Returns:
|
||||
@@ -148,7 +134,6 @@ def verify_aws_v4_signature(
|
||||
query_string,
|
||||
headers,
|
||||
signed_headers_part,
|
||||
body,
|
||||
)
|
||||
|
||||
# Create string to sign with the full timestamp from X-Amz-Date
|
||||
@@ -168,9 +153,12 @@ def verify_aws_v4_signature(
|
||||
# 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:
|
||||
import logging
|
||||
logging.getLogger(__name__).exception(f"Error verifying v4 signature: {e}")
|
||||
logger.exception(f"Error verifying v4 signature: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -180,7 +168,6 @@ def _build_canonical_request(
|
||||
query_string: str,
|
||||
headers: dict,
|
||||
signed_headers: str,
|
||||
body: bytes,
|
||||
) -> str:
|
||||
"""Build the canonical request for AWS v4 signing."""
|
||||
# Canonical request format:
|
||||
@@ -201,20 +188,15 @@ def _build_canonical_request(
|
||||
# Build canonical headers
|
||||
canonical_headers = _build_canonical_headers(headers, signed_headers)
|
||||
|
||||
# Get the hashed payload from X-Amz-Content-Sha256 header
|
||||
# This header is already computed by boto3/AWS SDK and is part of SignedHeaders
|
||||
# Use it directly to avoid hashing large files in memory
|
||||
# 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 X-Amz-Content-Sha256 is not present (e.g., for small requests or backward compatibility),
|
||||
# compute it from the body
|
||||
if not body_hash:
|
||||
body_hash = hashlib.sha256(body).hexdigest()
|
||||
|
||||
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"
|
||||
@@ -234,7 +216,8 @@ def _normalize_path(path: str) -> str:
|
||||
path = "/"
|
||||
elif not path.startswith("/"):
|
||||
path = "/" + path
|
||||
return 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:
|
||||
@@ -0,0 +1,289 @@
|
||||
"""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)
|
||||
|
||||
uploads.check_upload_key(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,334 @@
|
||||
"""S3-compatible local file storage, organised per studio bucket."""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import logging
|
||||
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
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
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"
|
||||
|
||||
@property
|
||||
def work_path(self) -> Path:
|
||||
"""Scratch space for worker jobs. Not under .tmp, which cleanup_uploads prunes by age."""
|
||||
return self.base_path / ".work"
|
||||
|
||||
def object_path(self, bucket: str, key: str) -> Path:
|
||||
"""Filesystem path of an object, for tools that need to read it directly."""
|
||||
return self._get_file_path(bucket, key)
|
||||
|
||||
def publish_file(self, path: Path, bucket: str, key: str) -> None:
|
||||
"""
|
||||
Move a finished file into a bucket. ``path`` must be on the same filesystem
|
||||
as the storage (for example under work_path) so the move is atomic.
|
||||
"""
|
||||
self._publish(Path(path), bucket, key)
|
||||
|
||||
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 _folder_path(self, bucket: str, folder: str) -> Path:
|
||||
"""Path of a folder inside a bucket. Refuses the bucket root itself."""
|
||||
folder = folder.strip("/")
|
||||
path = self._get_file_path(bucket, folder) if folder else None
|
||||
if path is None or path == self._get_bucket_path(bucket).resolve():
|
||||
raise InvalidKey("A folder inside the bucket is required")
|
||||
return path
|
||||
|
||||
def delete_folder(self, bucket: str, folder: str) -> None:
|
||||
"""
|
||||
Delete every object under ``folder`` and the folder itself, as far as possible.
|
||||
Files that can't be removed are left in place; check with folder_objects().
|
||||
"""
|
||||
root = self._folder_path(bucket, folder)
|
||||
if not root.is_dir():
|
||||
return
|
||||
# Deepest paths first, so folders are empty by the time they are removed.
|
||||
for path in sorted(root.rglob("*"), key=lambda p: len(p.parts), reverse=True):
|
||||
try:
|
||||
if path.is_dir() and not path.is_symlink():
|
||||
path.rmdir()
|
||||
else:
|
||||
path.unlink()
|
||||
except OSError as e:
|
||||
logger.warning("Could not delete %s: %s", path, e)
|
||||
try:
|
||||
root.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def folder_objects(self, bucket: str, folder: str) -> list[str]:
|
||||
"""Keys of the objects remaining under ``folder``."""
|
||||
root = self._folder_path(bucket, folder)
|
||||
if not root.exists():
|
||||
return []
|
||||
bucket_path = self._get_bucket_path(bucket).resolve()
|
||||
return sorted(p.relative_to(bucket_path).as_posix() for p in root.rglob("*") if not p.is_dir())
|
||||
|
||||
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" value="videos/raw"
|
||||
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,11 @@
|
||||
{% 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 %}
|
||||
@@ -0,0 +1 @@
|
||||
<span class="badge {% if status == 'draft' %}text-bg-secondary{% elif status == 'pending' %}text-bg-info{% elif status == 'in_progress' %}text-bg-primary{% elif status == 'completed' %}text-bg-success{% elif status == 'failed' %}text-bg-danger{% else %}text-bg-light{% endif %}">{{ label }}</span>
|
||||
@@ -0,0 +1,12 @@
|
||||
<div class="card">
|
||||
<div class="card-header">Example profile definition</div>
|
||||
<div class="card-body">
|
||||
<pre class="mb-3 small"><code>{{ example_profile }}</code></pre>
|
||||
<ul class="small mb-0">
|
||||
<li><code>profiles</code> is required and needs at least one entry. Each entry produces one output rendition.</li>
|
||||
<li><code>resolution</code> is required for every entry, as <code>WIDTHxHEIGHT</code>.</li>
|
||||
<li><code>bitrate</code>, <code>codec</code>, <code>fps</code> and <code>name</code> are optional.</li>
|
||||
<li><code>encoder</code> is optional: <code>cpu</code>, <code>quicksync</code> or <code>nvidia</code>.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -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,25 @@
|
||||
{% 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"><a href="{% url 'studio:content_asset' studio.bucket_name content_asset.pk %}">{{ content_asset.title }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Delete</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Delete {{ content_asset.title }}?</h1>
|
||||
|
||||
{% if blocker %}
|
||||
<div class="alert alert-warning">{{ blocker }}</div>
|
||||
<a href="{% url 'studio:content_asset' studio.bucket_name content_asset.pk %}" class="btn btn-secondary">Back</a>
|
||||
{% else %}
|
||||
<p>This permanently deletes the content entry and its details.</p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-danger">Delete</button>
|
||||
<a href="{% url 'studio:content_asset' studio.bucket_name content_asset.pk %}" class="btn btn-secondary">Cancel</a>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,146 @@
|
||||
{% 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>
|
||||
|
||||
<section class="mb-4" aria-labelledby="transcode-jobs-heading">
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
<h2 id="transcode-jobs-heading" class="h4 mb-0">Transcode jobs</h2>
|
||||
{% if content_asset.uploaded_asset %}
|
||||
<a href="{% url 'studio:transcode_job_create' studio.bucket_name content_asset.pk %}" class="btn btn-outline-primary btn-sm">New transcode job</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if transcode_jobs %}
|
||||
<table class="table table-sm align-middle">
|
||||
<tr>
|
||||
<th>Job</th>
|
||||
<th>Profile</th>
|
||||
<th>Status</th>
|
||||
<th>Requested</th>
|
||||
</tr>
|
||||
{% for job in transcode_jobs %}
|
||||
<tr>
|
||||
<td><a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}">Transcode job {{ job.pk }}</a></td>
|
||||
<td>{{ job.profile.name|default:"Custom definition" }}</td>
|
||||
<td>{% include "privatestudio/_job_status.html" with status=job.status label=job.get_status_display %}</td>
|
||||
<td>{{ job.requested_at }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% else %}
|
||||
<p class="text-body-secondary">No transcode jobs yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="mb-4" aria-labelledby="packaging-jobs-heading">
|
||||
<h2 id="packaging-jobs-heading" class="h4 mb-2">Packages</h2>
|
||||
{% if packaging_jobs %}
|
||||
<table class="table table-sm align-middle">
|
||||
<tr>
|
||||
<th>Package</th>
|
||||
<th>Transcode job</th>
|
||||
<th>Status</th>
|
||||
<th>Completed</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
{% for packaging_job in packaging_jobs %}
|
||||
<tr>
|
||||
<td><a href="{% url 'studio:packaging_job' studio.bucket_name packaging_job.pk %}">{{ packaging_job.slug }}</a></td>
|
||||
<td><a href="{% url 'studio:transcode_job' studio.bucket_name packaging_job.transcode_job_id %}">Transcode job {{ packaging_job.transcode_job_id }}</a></td>
|
||||
<td>{% include "privatestudio/_job_status.html" with status=packaging_job.status label=packaging_job.get_status_display %}</td>
|
||||
<td>{{ packaging_job.completed_at|default:"—" }}</td>
|
||||
<td class="text-end">
|
||||
{% if packaging_job.status == 'completed' %}
|
||||
<a href="{% url 'studio:packaging_job_download' studio.bucket_name packaging_job.pk %}" class="btn btn-outline-primary btn-sm" download>Download zip</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% else %}
|
||||
<p class="text-body-secondary">No packages yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<dl class="row">
|
||||
<dt class="col-sm-3">File</dt>
|
||||
<dd class="col-sm-9">
|
||||
{% if content_asset.uploaded_asset %}
|
||||
{{ content_asset.uploaded_asset.s3_path }}
|
||||
<a href="{% url 'studio:uploaded_asset_delete' studio.bucket_name content_asset.uploaded_asset.pk %}" class="btn btn-outline-danger btn-sm ms-2">Delete file</a>
|
||||
{% else %}
|
||||
<span class="text-body-secondary">No file</span>
|
||||
{% endif %}
|
||||
</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>
|
||||
{% if content_asset.can_offer_delete %}
|
||||
<a href="{% url 'studio:content_asset_delete' studio.bucket_name content_asset.pk %}" class="btn btn-outline-danger">Delete</a>
|
||||
{% endif %}
|
||||
<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,36 @@
|
||||
<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>
|
||||
<th></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>
|
||||
<td class="text-end">
|
||||
{% if content.uploaded_asset %}
|
||||
<a href="{% url 'studio:transcode_job_create' studio.bucket_name content.pk %}" class="btn btn-outline-primary btn-sm">Transcode</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="7">No content yet. Use "Create content" on an uploaded file.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
@@ -0,0 +1,26 @@
|
||||
<div class="d-flex justify-content-end mb-2">
|
||||
<a href="{% url 'studio:transcode_profile_create' studio.bucket_name %}" class="btn btn-primary btn-sm">New profile</a>
|
||||
</div>
|
||||
<table class="table table-striped table-sm align-middle">
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Created</th>
|
||||
<th>Created by</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
{% for profile in profiles %}
|
||||
<tr>
|
||||
<td><a href="{% url 'studio:transcode_profile' studio.bucket_name profile.pk %}">{{ profile.name }}</a></td>
|
||||
<td>{{ profile.created_at }}</td>
|
||||
<td>{{ profile.created_by|default:"" }}</td>
|
||||
<td class="text-end">
|
||||
<a href="{% url 'studio:transcode_profile' studio.bucket_name profile.pk %}" class="btn btn-outline-primary btn-sm">Edit</a>
|
||||
<a href="{% url 'studio:transcode_profile_delete' studio.bucket_name profile.pk %}" class="btn btn-outline-danger btn-sm">Delete</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="4">No transcode profiles yet.</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,30 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block content %}
|
||||
{% with job=packaging_job.transcode_job %}
|
||||
<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"><a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}">Transcode job {{ job.pk }}</a></li>
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:packaging_job' studio.bucket_name packaging_job.pk %}">Packaging job {{ packaging_job.pk }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Delete</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Delete packaging job {{ packaging_job.pk }}?</h1>
|
||||
{% if packaging_job.is_deletable %}
|
||||
<p>
|
||||
This deletes {{ file_count }} file{{ file_count|pluralize }} in <code>{{ packaging_job.package_path }}/</code>.
|
||||
The packaging job is removed once all of its files are gone. The transcode job and its outputs are kept.
|
||||
</p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-danger">Delete</button>
|
||||
<a href="{% url 'studio:packaging_job' studio.bucket_name packaging_job.pk %}" class="btn btn-secondary">Cancel</a>
|
||||
</form>
|
||||
{% else %}
|
||||
<div class="alert alert-warning">This packaging job is running and can't be deleted until it finishes.</div>
|
||||
<a href="{% url 'studio:packaging_job' studio.bucket_name packaging_job.pk %}" class="btn btn-secondary">Back</a>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,58 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block content %}
|
||||
{% with job=packaging_job.transcode_job %}
|
||||
<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>
|
||||
{% if job.content_asset %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:content_asset' studio.bucket_name job.content_asset.pk %}">{{ job.content_asset.title }}</a></li>
|
||||
{% endif %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}">Transcode job {{ job.pk }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Packaging job {{ packaging_job.pk }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Packaging job {{ packaging_job.pk }} {% include "privatestudio/_job_status.html" with status=packaging_job.status label=packaging_job.get_status_display %}</h1>
|
||||
|
||||
{% if packaging_job.status == 'pending' and job.status != 'completed' %}
|
||||
<div class="alert alert-secondary">Packaging starts after transcode job {{ job.pk }} completes.</div>
|
||||
{% endif %}
|
||||
|
||||
<dl class="row">
|
||||
<dt class="col-sm-3">Transcode job</dt>
|
||||
<dd class="col-sm-9">
|
||||
<a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}">Transcode job {{ job.pk }}</a>
|
||||
{% include "privatestudio/_job_status.html" with status=job.status label=job.get_status_display %}
|
||||
</dd>
|
||||
<dt class="col-sm-3">Content</dt>
|
||||
<dd class="col-sm-9">
|
||||
{% if job.content_asset %}<a href="{% url 'studio:content_asset' studio.bucket_name job.content_asset.pk %}">{{ job.content_asset.title }}</a>{% else %}—{% endif %}
|
||||
</dd>
|
||||
<dt class="col-sm-3">Requested</dt>
|
||||
<dd class="col-sm-9">{{ packaging_job.requested_at }}{% if packaging_job.requested_by %} by {{ packaging_job.requested_by }}{% endif %}</dd>
|
||||
<dt class="col-sm-3">Started</dt>
|
||||
<dd class="col-sm-9">{{ packaging_job.started_at|default:"—" }}</dd>
|
||||
<dt class="col-sm-3">Completed</dt>
|
||||
<dd class="col-sm-9">{{ packaging_job.completed_at|default:"—" }}</dd>
|
||||
{% if packaging_job.manifest_path %}
|
||||
<dt class="col-sm-3">HLS playlist</dt>
|
||||
<dd class="col-sm-9"><code>{{ packaging_job.manifest_path }}</code></dd>
|
||||
{% endif %}
|
||||
</dl>
|
||||
{% endwith %}
|
||||
|
||||
<div class="d-flex gap-2 mb-3">
|
||||
{% if packaging_job.status == 'completed' %}
|
||||
<a href="{% url 'studio:packaging_job_download' studio.bucket_name packaging_job.pk %}" class="btn btn-primary" download>Download zip</a>
|
||||
{% endif %}
|
||||
{% if packaging_job.is_deletable %}
|
||||
<a href="{% url 'studio:packaging_job_delete' studio.bucket_name packaging_job.pk %}" class="btn btn-outline-danger">Delete</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if packaging_job.output %}
|
||||
<h2 class="h4">Output</h2>
|
||||
<pre class="border rounded p-3 small"><code>{{ packaging_job.output }}</code></pre>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,42 @@
|
||||
{% extends "privatestudio/base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<h1>{{ studio.name }}</h1>
|
||||
<p>Bucket Name: {{ studio.bucket_name }}</p>
|
||||
<p>Group: {{ studio.group.name }}</p>
|
||||
|
||||
{% with active=active_tab %}
|
||||
<ul class="nav nav-tabs mb-3" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link{% if active == 'files' %} 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 active == 'files' %}true{% else %}false{% endif %}">Uploaded files</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link{% if active == '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 active == 'content' %}true{% else %}false{% endif %}">Content</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link{% if active == 'profiles' %} active{% endif %}" id="profiles-tab" data-bs-toggle="tab" data-bs-target="#profiles-pane" type="button" role="tab" aria-controls="profiles-pane" aria-selected="{% if active == 'profiles' %}true{% else %}false{% endif %}">Profiles</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane fade{% if active == 'files' %} 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 active == '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 class="tab-pane fade{% if active == 'profiles' %} show active{% endif %}" id="profiles-pane" role="tabpanel" aria-labelledby="profiles-tab" tabindex="0">
|
||||
<div id="transcode_profiles" hx-get="{% url 'studio:transcode_profiles' studio.bucket_name %}" hx-trigger="load" hx-target="#transcode_profiles" hx-swap="innerHTML">
|
||||
<p>Loading profiles...</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,31 @@
|
||||
{% 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>
|
||||
{% if job.content_asset %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:content_asset' studio.bucket_name job.content_asset.pk %}">{{ job.content_asset.title }}</a></li>
|
||||
{% endif %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}">Transcode job {{ job.pk }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Delete</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Delete transcode job {{ job.pk }}?</h1>
|
||||
|
||||
{% if blocker %}
|
||||
<div class="alert alert-warning">{{ blocker }}</div>
|
||||
<a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}" class="btn btn-secondary">Back</a>
|
||||
{% else %}
|
||||
<p>
|
||||
This deletes {{ file_count }} output file{{ file_count|pluralize }} in <code>{{ job.output_path }}/</code>.
|
||||
The transcode job is removed once all of its outputs are gone. The source file is kept.
|
||||
</p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-danger">Delete</button>
|
||||
<a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}" class="btn btn-secondary">Cancel</a>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,90 @@
|
||||
{% 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>
|
||||
{% if job.content_asset %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:content_asset' studio.bucket_name job.content_asset.pk %}">{{ job.content_asset.title }}</a></li>
|
||||
{% endif %}
|
||||
<li class="breadcrumb-item active" aria-current="page">Transcode job {{ job.pk }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Transcode job {{ job.pk }} {% include "privatestudio/_job_status.html" with status=job.status label=job.get_status_display %}</h1>
|
||||
|
||||
{% if job.is_editable or job.is_deletable or job.status == 'completed' %}
|
||||
<div class="d-flex gap-2 mb-3">
|
||||
{% if job.status == 'completed' %}
|
||||
<a href="{% url 'studio:transcode_job_download' studio.bucket_name job.pk %}" class="btn btn-primary" download>Download zip</a>
|
||||
{% endif %}
|
||||
{% if job.is_editable %}
|
||||
<a href="{% url 'studio:transcode_job_update' studio.bucket_name job.pk %}" class="btn btn-secondary">Edit</a>
|
||||
<form method="post" action="{% url 'studio:transcode_job_submit' studio.bucket_name job.pk %}" class="m-0">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-primary">Submit</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if job.is_deletable %}
|
||||
<a href="{% url 'studio:transcode_job_delete' studio.bucket_name job.pk %}" class="btn btn-outline-danger">Delete</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<dl class="row">
|
||||
<dt class="col-sm-3">Content</dt>
|
||||
<dd class="col-sm-9">
|
||||
{% if job.content_asset %}<a href="{% url 'studio:content_asset' studio.bucket_name job.content_asset.pk %}">{{ job.content_asset.title }}</a>{% else %}—{% endif %}
|
||||
</dd>
|
||||
<dt class="col-sm-3">File</dt>
|
||||
<dd class="col-sm-9">{% if job.asset %}{{ job.asset.s3_path }}{% else %}<span class="text-body-secondary">Deleted</span>{% endif %}</dd>
|
||||
<dt class="col-sm-3">Profile</dt>
|
||||
<dd class="col-sm-9">
|
||||
{% if job.profile %}<a href="{% url 'studio:transcode_profile' studio.bucket_name job.profile.pk %}">{{ job.profile.name }}</a>{% else %}Custom definition{% endif %}
|
||||
</dd>
|
||||
<dt class="col-sm-3">Requested</dt>
|
||||
<dd class="col-sm-9">{{ job.requested_at }}{% if job.requested_by %} by {{ job.requested_by }}{% endif %}</dd>
|
||||
<dt class="col-sm-3">Completed</dt>
|
||||
<dd class="col-sm-9">{{ job.completed_at|default:"—" }}</dd>
|
||||
</dl>
|
||||
|
||||
<div class="d-flex align-items-center gap-3 mb-2">
|
||||
<h2 class="h4 m-0">Packaging jobs</h2>
|
||||
{% if job.can_add_packaging_job %}
|
||||
<form method="post" action="{% url 'studio:packaging_job_create' studio.bucket_name job.pk %}" class="m-0">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-sm btn-outline-primary">New packaging job</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
<ul>
|
||||
{% for packaging_job in job.packaging_jobs.all %}
|
||||
<li>
|
||||
<a href="{% url 'studio:packaging_job' studio.bucket_name packaging_job.pk %}">Packaging job {{ packaging_job.pk }}</a>
|
||||
{% include "privatestudio/_job_status.html" with status=packaging_job.status label=packaging_job.get_status_display %}
|
||||
</li>
|
||||
{% empty %}
|
||||
<li>None</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
{% with outputs=job.transcoded_assets.all %}
|
||||
{% if outputs %}
|
||||
<h2 class="h4">Outputs</h2>
|
||||
<table class="table table-striped table-sm">
|
||||
<tr><th>File</th><th>Format</th><th>Created</th></tr>
|
||||
{% for output in outputs %}
|
||||
<tr><td>{{ output.s3_path }}</td><td>{{ output.format }}</td><td>{{ output.created_at }}</td></tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
{% if job.transcode_output %}
|
||||
<h2 class="h4">Output</h2>
|
||||
<pre class="border rounded p-3 small" style="max-height: 30rem; overflow: auto;"><code>{{ job.transcode_output }}</code></pre>
|
||||
{% endif %}
|
||||
|
||||
<h2 class="h4">Profile definition</h2>
|
||||
<pre class="border rounded p-3 small"><code>{{ job.profile_definition }}</code></pre>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,69 @@
|
||||
{% 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>
|
||||
{% if content_asset %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:content_asset' studio.bucket_name content_asset.pk %}">{{ content_asset.title }}</a></li>
|
||||
{% endif %}
|
||||
{% if job %}
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}">Transcode job {{ job.pk }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Edit</li>
|
||||
{% else %}
|
||||
<li class="breadcrumb-item active" aria-current="page">New transcode job</li>
|
||||
{% endif %}
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>{% if job %}Edit transcode job {{ job.pk }}{% else %}New transcode job{% endif %}</h1>
|
||||
{% if content_asset %}<p class="text-body-secondary">{{ content_asset.title }} · {{ content_asset.uploaded_asset.s3_path }}</p>{% endif %}
|
||||
|
||||
<div class="row">
|
||||
<div class="col-lg-7">
|
||||
<form method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% include "privatestudio/_form_fields.html" %}
|
||||
{% if not form.fields.profile.queryset.exists %}
|
||||
<div class="alert alert-secondary">
|
||||
This studio has no saved profiles. You can enter a definition here, or
|
||||
<a href="{% url 'studio:transcode_profile_create' studio.bucket_name %}">create a profile</a> first.
|
||||
</div>
|
||||
{% endif %}
|
||||
<button type="submit" name="save" class="btn btn-secondary">Save draft</button>
|
||||
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
|
||||
{% if job %}
|
||||
<a href="{% url 'studio:transcode_job' studio.bucket_name job.pk %}" class="btn btn-link">Cancel</a>
|
||||
{% elif content_asset %}
|
||||
<a href="{% url 'studio:content_asset' studio.bucket_name content_asset.pk %}" class="btn btn-link">Cancel</a>
|
||||
{% endif %}
|
||||
<div class="form-text">A submitted job is queued for transcoding and can no longer be edited.</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="col-lg-5 mt-4 mt-lg-0">
|
||||
{% include "privatestudio/_profile_example.html" %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{ profile_definitions|json_script:"profile-definitions" }}
|
||||
<script>
|
||||
(function () {
|
||||
const definitions = JSON.parse(document.getElementById("profile-definitions").textContent);
|
||||
const select = document.getElementById("{{ form.profile.id_for_label }}");
|
||||
const editor = document.getElementById("{{ form.profile_definition.id_for_label }}");
|
||||
if (!select || !editor) return;
|
||||
// Replace the text only while it is empty or still matches a saved profile, so edits aren't lost.
|
||||
const untouched = () => editor.value.trim() === "" ||
|
||||
Object.values(definitions).some((text) => text.trim() === editor.value.trim());
|
||||
select.addEventListener("change", () => {
|
||||
const text = definitions[select.value];
|
||||
if (text !== undefined && (untouched() || confirm("Replace your edits with the selected profile?"))) {
|
||||
editor.value = text;
|
||||
}
|
||||
});
|
||||
if (editor.value.trim() === "" && definitions[select.value] !== undefined) {
|
||||
editor.value = definitions[select.value];
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,19 @@
|
||||
{% 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=profiles">{{ studio.name }}</a></li>
|
||||
<li class="breadcrumb-item"><a href="{% url 'studio:transcode_profile' studio.bucket_name profile.pk %}">{{ profile.name }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Delete</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Delete profile {{ profile.name }}?</h1>
|
||||
<p>Transcode jobs that used this profile keep their own copy of its definition.</p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-danger">Delete</button>
|
||||
<a href="{% url 'studio:detail' studio.bucket_name %}?tab=profiles" class="btn btn-secondary">Cancel</a>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
{% 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=profiles">{{ studio.name }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">{% if profile %}{{ profile.name }}{% else %}New profile{% endif %}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>{% if profile %}Edit profile {{ profile.name }}{% else %}New transcode profile{% endif %}</h1>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-lg-7">
|
||||
<form method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% include "privatestudio/_form_fields.html" %}
|
||||
<button type="submit" class="btn btn-primary">Save</button>
|
||||
<a href="{% url 'studio:detail' studio.bucket_name %}?tab=profiles" class="btn btn-secondary">Cancel</a>
|
||||
{% if default_profile %}
|
||||
<button type="button" id="fill-default-profile" class="btn btn-outline-secondary">Fill with default profile</button>
|
||||
{% endif %}
|
||||
{% if profile %}
|
||||
<a href="{% url 'studio:transcode_profile_delete' studio.bucket_name profile.pk %}" class="btn btn-outline-danger float-end">Delete</a>
|
||||
{% endif %}
|
||||
</form>
|
||||
</div>
|
||||
<div class="col-lg-5 mt-4 mt-lg-0">
|
||||
{% include "privatestudio/_profile_example.html" %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if default_profile %}
|
||||
{{ default_profile|json_script:"default-profile" }}
|
||||
<script>
|
||||
(function () {
|
||||
const text = JSON.parse(document.getElementById("default-profile").textContent);
|
||||
const editor = document.getElementById("{{ form.profile_definition.id_for_label }}");
|
||||
document.getElementById("fill-default-profile").addEventListener("click", () => {
|
||||
const current = editor.value.trim();
|
||||
if (current === "" || current === text.trim() || confirm("Replace the current definition with the default profile?")) {
|
||||
editor.value = text;
|
||||
editor.focus();
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,35 @@
|
||||
{% 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=files">{{ studio.name }}</a></li>
|
||||
<li class="breadcrumb-item active" aria-current="page">Delete {{ asset.filename }}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<h1>Delete {{ asset.filename }}?</h1>
|
||||
|
||||
{% if blocker %}
|
||||
<div class="alert alert-warning">{{ blocker }}</div>
|
||||
<a href="{{ cancel_url }}" class="btn btn-secondary">Back</a>
|
||||
{% else %}
|
||||
<p>This permanently deletes <code>{{ asset.s3_path }}</code> from storage.</p>
|
||||
<ul>
|
||||
{% if content_assets %}
|
||||
<li>
|
||||
Content entries that use it are kept without a file:
|
||||
{% for content in content_assets %}<a href="{% url 'studio:content_asset' studio.bucket_name content.pk %}">{{ content.title }}</a>{% if not forloop.last %}, {% endif %}{% endfor %}.
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if transcode_job_count %}
|
||||
<li>{{ transcode_job_count }} transcode job{{ transcode_job_count|pluralize }} and {{ transcode_job_count|pluralize:"its,their" }} outputs are kept, but can't be run again.</li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-danger">Delete file</button>
|
||||
<a href="{{ cancel_url }}" class="btn btn-secondary">Cancel</a>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% 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 resolution: 640x360\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,135 @@
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from django.test import AsyncClient
|
||||
from django.urls import reverse
|
||||
|
||||
from privatestudio.studio.models import JobStatus, PackagingJob, TranscodeJob, UploadedAsset
|
||||
from privatestudio.studio.storage import get_storage
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
from privatestudio.studio.zipstream import iter_zip
|
||||
|
||||
FILES = {
|
||||
"hls/master.m3u8": b"#EXTM3U\n",
|
||||
"hls/media-1/stream.m3u8": b"#EXTM3U\n#EXTINF\n",
|
||||
"hls/media-1/segment-0.ts": bytes(range(256)) * 400,
|
||||
"hls/audio/aac/en/segment-0.ts": b"audio" * 1000,
|
||||
}
|
||||
|
||||
|
||||
class ZipStreamTests(StudioTestCase):
|
||||
def test_blocks_form_valid_zip(self):
|
||||
base = Path(self.storage_dir)
|
||||
big = base / "big.bin"
|
||||
big.write_bytes(b"x" * 10_000)
|
||||
small = base / "small.txt"
|
||||
small.write_bytes(b"hello")
|
||||
blocks = list(iter_zip([(big, "root/a/big.bin"), (small, "root/small.txt"),
|
||||
(base / "gone.txt", "root/gone.txt")], block_size=1000))
|
||||
self.assertGreater(len(blocks), 5) # streamed, not built at once
|
||||
with zipfile.ZipFile(io.BytesIO(b"".join(blocks))) as archive:
|
||||
self.assertIsNone(archive.testzip())
|
||||
self.assertEqual(archive.namelist(), ["root/a/big.bin", "root/small.txt"])
|
||||
self.assertEqual(archive.read("root/a/big.bin"), b"x" * 10_000)
|
||||
self.assertEqual(archive.getinfo("root/small.txt").compress_type, zipfile.ZIP_STORED)
|
||||
|
||||
|
||||
class PackageDownloadTests(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.client.force_login(self.user)
|
||||
asset = UploadedAsset.objects.create(studio=self.studio, filename="a.mov", size=1, s3_path="a.mov")
|
||||
transcode = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.studio,
|
||||
asset=asset, status=JobStatus.COMPLETED)
|
||||
self.job = PackagingJob.objects.create(slug="p-delgyy45ovalfef", studio=self.studio,
|
||||
transcode_job=transcode, status=JobStatus.COMPLETED)
|
||||
storage = get_storage()
|
||||
for key, data in FILES.items():
|
||||
storage.put_stream("demo", f"{self.job.package_path}/{key}", [data])
|
||||
storage.put_stream("demo", "packages/p-other/hls/master.m3u8", [b"other"])
|
||||
self.url = reverse("studio:packaging_job_download", args=["demo", self.job.pk])
|
||||
self.detail = reverse("studio:packaging_job", args=["demo", self.job.pk])
|
||||
|
||||
def check_zip(self, data):
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
self.assertIsNone(archive.testzip())
|
||||
self.assertEqual(sorted(archive.namelist()), sorted(f"p-delgyy45ovalfef/{k}" for k in FILES))
|
||||
for key, content in FILES.items():
|
||||
self.assertEqual(archive.read(f"p-delgyy45ovalfef/{key}"), content)
|
||||
|
||||
def test_download(self):
|
||||
self.assertContains(self.client.get(self.detail), self.url)
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.streaming)
|
||||
self.assertEqual(response["Content-Type"], "application/zip")
|
||||
self.assertEqual(response["Content-Disposition"], 'attachment; filename="p-delgyy45ovalfef.zip"')
|
||||
self.check_zip(b"".join(response.streaming_content))
|
||||
|
||||
async def test_download_asgi(self):
|
||||
client = AsyncClient()
|
||||
await client.aforce_login(self.user)
|
||||
response = await client.get(self.url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.check_zip(b"".join([block async for block in response.streaming_content]))
|
||||
|
||||
def test_not_completed(self):
|
||||
for status in (JobStatus.PENDING, JobStatus.IN_PROGRESS, JobStatus.FAILED):
|
||||
PackagingJob.objects.filter(pk=self.job.pk).update(status=status)
|
||||
self.assertNotContains(self.client.get(self.detail), self.url)
|
||||
self.assertRedirects(self.client.get(self.url), self.detail, fetch_redirect_response=False)
|
||||
|
||||
def test_no_files(self):
|
||||
get_storage().delete_folder("demo", self.job.package_path)
|
||||
self.assertRedirects(self.client.get(self.url), self.detail, fetch_redirect_response=False)
|
||||
|
||||
def test_access(self):
|
||||
self.client.logout()
|
||||
self.assertEqual(self.client.get(self.url).status_code, 302) # to sign-in
|
||||
other_url = reverse("studio:packaging_job_download", args=["other", self.job.pk])
|
||||
self.client.force_login(self.user)
|
||||
self.assertIn(self.client.get(other_url).status_code, (403, 404))
|
||||
|
||||
|
||||
OUTPUTS = {
|
||||
"output_720p.mp4": bytes(range(256)) * 300,
|
||||
"output_audio.mp4": b"audio" * 500,
|
||||
}
|
||||
|
||||
|
||||
class TranscodeDownloadTests(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.client.force_login(self.user)
|
||||
asset = UploadedAsset.objects.create(studio=self.studio, filename="a.mov", size=1, s3_path="a.mov")
|
||||
self.job = TranscodeJob.objects.create(slug="tc-cox2gpoijvefrnc", studio=self.studio, asset=asset,
|
||||
status=JobStatus.COMPLETED)
|
||||
storage = get_storage()
|
||||
for name, data in OUTPUTS.items():
|
||||
storage.put_stream("demo", f"{self.job.output_path}/{name}", [data])
|
||||
storage.put_stream("demo", "transcodes/tc-other/output_720p.mp4", [b"other"])
|
||||
self.url = reverse("studio:transcode_job_download", args=["demo", self.job.pk])
|
||||
self.detail = reverse("studio:transcode_job", args=["demo", self.job.pk])
|
||||
|
||||
def test_download(self):
|
||||
self.assertContains(self.client.get(self.detail), self.url)
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.streaming)
|
||||
self.assertEqual(response["Content-Disposition"], 'attachment; filename="tc-cox2gpoijvefrnc.zip"')
|
||||
with zipfile.ZipFile(io.BytesIO(b"".join(response.streaming_content))) as archive:
|
||||
self.assertIsNone(archive.testzip())
|
||||
self.assertEqual(sorted(archive.namelist()), sorted(f"tc-cox2gpoijvefrnc/{n}" for n in OUTPUTS))
|
||||
for name, content in OUTPUTS.items():
|
||||
self.assertEqual(archive.read(f"tc-cox2gpoijvefrnc/{name}"), content)
|
||||
|
||||
def test_not_completed(self):
|
||||
for status in (JobStatus.DRAFT, JobStatus.PENDING, JobStatus.IN_PROGRESS, JobStatus.FAILED):
|
||||
TranscodeJob.objects.filter(pk=self.job.pk).update(status=status)
|
||||
self.assertNotContains(self.client.get(self.detail), self.url)
|
||||
self.assertRedirects(self.client.get(self.url), self.detail, fetch_redirect_response=False)
|
||||
|
||||
def test_no_files(self):
|
||||
get_storage().delete_folder("demo", self.job.output_path)
|
||||
self.assertRedirects(self.client.get(self.url), self.detail, fetch_redirect_response=False)
|
||||
@@ -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,702 @@
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from django.contrib.messages import get_messages
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db.models.query import QuerySet
|
||||
from django.urls import reverse
|
||||
|
||||
from privatestudio.studio.models import (
|
||||
ContentAsset, JobStatus, PackagingJob, TranscodedAsset, TranscodeJob, TranscodeProfile, UploadedAsset,
|
||||
)
|
||||
from privatestudio.studio.profiles import EXAMPLE_PROFILE_YAML, load_default_profile, validate_profile_definition
|
||||
from privatestudio.studio.storage import InvalidKey, S3FileStorage, get_storage
|
||||
from privatestudio.studio.tests.test_content import ContentTestCase
|
||||
|
||||
PROFILE_YAML = "profiles:\n hd:\n resolution: 1280x720\n bitrate: 2500k\n"
|
||||
OTHER_YAML = "profiles:\n sd:\n resolution: 640x360\n"
|
||||
|
||||
|
||||
class ValidateProfileDefinitionTests(ContentTestCase):
|
||||
def assert_invalid(self, text, fragment):
|
||||
with self.assertRaises(ValidationError) as ctx:
|
||||
validate_profile_definition(text)
|
||||
self.assertIn(fragment, " ".join(ctx.exception.messages))
|
||||
|
||||
def test_valid(self):
|
||||
self.assertIn("1080p", validate_profile_definition(EXAMPLE_PROFILE_YAML)["profiles"])
|
||||
validate_profile_definition(PROFILE_YAML)
|
||||
|
||||
def test_invalid(self):
|
||||
self.assert_invalid("profiles: [oops", "Invalid YAML (line")
|
||||
self.assert_invalid("- a\n- b\n", "YAML mapping")
|
||||
self.assert_invalid("", "YAML mapping")
|
||||
self.assert_invalid("encoder: cpu\n", "'profiles' must be a mapping")
|
||||
self.assert_invalid("profiles: {}\n", "'profiles' must be a mapping")
|
||||
self.assert_invalid("profiles:\n hd: 720\n", "Profile 'hd' must be a mapping")
|
||||
self.assert_invalid("profiles:\n hd:\n bitrate: 1000k\n", "'resolution' is required")
|
||||
self.assert_invalid("profiles:\n hd:\n resolution: big\n", "'resolution' is required")
|
||||
self.assert_invalid("profiles:\n hd:\n resolution: 10x10\n bitrate: fast\n", "'bitrate'")
|
||||
self.assert_invalid("profiles:\n hd:\n resolution: 10x10\n fps: -1\n", "'fps'")
|
||||
self.assert_invalid("encoder: gpu\nprofiles:\n hd:\n resolution: 10x10\n", "'encoder'")
|
||||
|
||||
|
||||
class TranscodeProfileViewTests(ContentTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.profile = TranscodeProfile.objects.create(studio=self.studio, name="hd", profile_definition=PROFILE_YAML)
|
||||
self.other_profile = TranscodeProfile.objects.create(
|
||||
studio=self.other_studio, name="secret", profile_definition=PROFILE_YAML,
|
||||
)
|
||||
|
||||
def test_list_only_studio_profiles(self):
|
||||
response = self.client.get(reverse("studio:transcode_profiles", args=["demo"]))
|
||||
self.assertContains(response, "hd")
|
||||
self.assertNotContains(response, "secret")
|
||||
|
||||
def test_create(self):
|
||||
url = reverse("studio:transcode_profile_create", args=["demo"])
|
||||
response = self.client.get(url)
|
||||
self.assertContains(response, "Example profile definition")
|
||||
response = self.client.post(url, {"name": "sd", "profile_definition": OTHER_YAML})
|
||||
self.assertRedirects(response, reverse("studio:detail", args=["demo"]) + "?tab=profiles",
|
||||
fetch_redirect_response=False)
|
||||
profile = TranscodeProfile.objects.get(studio=self.studio, name="sd")
|
||||
self.assertEqual(profile.created_by, self.user)
|
||||
|
||||
def test_create_default_profile_button(self):
|
||||
url = reverse("studio:transcode_profile_create", args=["demo"])
|
||||
response = self.client.get(url)
|
||||
self.assertContains(response, 'id="fill-default-profile"')
|
||||
self.assertContains(response, 'id="default-profile"')
|
||||
validate_profile_definition(load_default_profile()) # The shipped default must be a valid profile.
|
||||
# Not offered when editing, or when the file isn't available.
|
||||
edit = self.client.get(reverse("studio:transcode_profile", args=["demo", self.profile.pk]))
|
||||
self.assertNotContains(edit, 'id="fill-default-profile"')
|
||||
with mock.patch("privatestudio.studio.profiles.DEFAULT_PROFILE_PATH", Path(self.storage_dir) / "missing.yaml"):
|
||||
self.assertNotContains(self.client.get(url), 'id="fill-default-profile"')
|
||||
|
||||
def test_create_invalid_yaml(self):
|
||||
url = reverse("studio:transcode_profile_create", args=["demo"])
|
||||
response = self.client.post(url, {"name": "bad", "profile_definition": "profiles: {}"})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "'profiles' must be a mapping")
|
||||
self.assertContains(response, "Example profile definition")
|
||||
self.assertFalse(TranscodeProfile.objects.filter(name="bad").exists())
|
||||
|
||||
def test_duplicate_name(self):
|
||||
url = reverse("studio:transcode_profile_create", args=["demo"])
|
||||
response = self.client.post(url, {"name": "hd", "profile_definition": PROFILE_YAML})
|
||||
self.assertContains(response, "already exists")
|
||||
# The same name in another studio is fine, and an edit may keep its own name.
|
||||
url = reverse("studio:transcode_profile_create", args=["demo"])
|
||||
self.assertEqual(self.client.post(url, {"name": "secret", "profile_definition": PROFILE_YAML}).status_code, 302)
|
||||
url = reverse("studio:transcode_profile", args=["demo", self.profile.pk])
|
||||
self.assertEqual(self.client.post(url, {"name": "hd", "profile_definition": OTHER_YAML}).status_code, 302)
|
||||
|
||||
def test_update(self):
|
||||
url = reverse("studio:transcode_profile", args=["demo", self.profile.pk])
|
||||
self.assertContains(self.client.get(url), "1280x720")
|
||||
self.client.post(url, {"name": "hd2", "profile_definition": OTHER_YAML})
|
||||
self.profile.refresh_from_db()
|
||||
self.assertEqual((self.profile.name, self.profile.profile_definition), ("hd2", OTHER_YAML.strip()))
|
||||
|
||||
def test_delete(self):
|
||||
url = reverse("studio:transcode_profile_delete", args=["demo", self.profile.pk])
|
||||
self.assertContains(self.client.get(url), "Delete profile hd?")
|
||||
self.client.post(url)
|
||||
self.assertFalse(TranscodeProfile.objects.filter(pk=self.profile.pk).exists())
|
||||
|
||||
def test_other_studio_profile_inaccessible(self):
|
||||
for name in ("transcode_profile", "transcode_profile_delete"):
|
||||
response = self.client.get(reverse(f"studio:{name}", args=["demo", self.other_profile.pk]))
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
|
||||
class TranscodeJobTestCase(ContentTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.profile = TranscodeProfile.objects.create(studio=self.studio, name="hd", profile_definition=PROFILE_YAML)
|
||||
self.content_asset = self.content(title="Pilot")
|
||||
|
||||
def make_job(self, **fields):
|
||||
return TranscodeJob.objects.create(
|
||||
slug=TranscodeJob.get_random_slug(),
|
||||
studio=self.studio, asset=self.asset, content_asset=self.content_asset, profile=self.profile,
|
||||
profile_definition=PROFILE_YAML, **fields,
|
||||
)
|
||||
|
||||
|
||||
class TranscodeJobCreateTests(TranscodeJobTestCase):
|
||||
def url(self, content=None):
|
||||
return reverse("studio:transcode_job_create", args=["demo", (content or self.content_asset).pk])
|
||||
|
||||
def test_get(self):
|
||||
response = self.client.get(self.url())
|
||||
self.assertContains(response, "Save draft")
|
||||
self.assertContains(response, 'id="profile-definitions"')
|
||||
|
||||
def test_save_draft_creates_packaging_job(self):
|
||||
response = self.client.post(self.url(), {
|
||||
"profile": self.profile.pk, "profile_definition": OTHER_YAML, "save": "",
|
||||
})
|
||||
job = TranscodeJob.objects.get()
|
||||
self.assertRedirects(response, reverse("studio:transcode_job", args=["demo", job.pk]),
|
||||
fetch_redirect_response=False)
|
||||
self.assertEqual(job.status, JobStatus.DRAFT)
|
||||
self.assertEqual((job.content_asset, job.asset, job.profile), (self.content_asset, self.asset, self.profile))
|
||||
self.assertEqual(job.profile_definition, OTHER_YAML.strip())
|
||||
self.assertEqual(job.requested_by, self.user)
|
||||
packaging = PackagingJob.objects.get()
|
||||
self.assertEqual((packaging.transcode_job, packaging.status), (job, JobStatus.PENDING))
|
||||
|
||||
def test_submit(self):
|
||||
self.client.post(self.url(), {"profile": self.profile.pk, "profile_definition": "", "submit": ""})
|
||||
job = TranscodeJob.objects.get()
|
||||
self.assertEqual(job.status, JobStatus.PENDING)
|
||||
self.assertEqual(job.profile_definition, PROFILE_YAML) # Copied from the profile when left empty.
|
||||
|
||||
def test_requires_profile_or_definition(self):
|
||||
response = self.client.post(self.url(), {"profile": "", "profile_definition": "", "save": ""})
|
||||
self.assertContains(response, "Choose a profile or enter a profile definition.")
|
||||
response = self.client.post(self.url(), {"profile": "", "profile_definition": "profiles: {}", "save": ""})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertFalse(TranscodeJob.objects.exists())
|
||||
self.assertFalse(PackagingJob.objects.exists())
|
||||
|
||||
def test_definition_without_profile(self):
|
||||
self.client.post(self.url(), {"profile": "", "profile_definition": OTHER_YAML, "save": ""})
|
||||
self.assertIsNone(TranscodeJob.objects.get().profile)
|
||||
|
||||
def test_other_studio_profile_rejected(self):
|
||||
other = TranscodeProfile.objects.create(studio=self.other_studio, name="x", profile_definition=PROFILE_YAML)
|
||||
response = self.client.post(self.url(), {"profile": other.pk, "profile_definition": "", "save": ""})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertFalse(TranscodeJob.objects.exists())
|
||||
|
||||
def test_content_without_file(self):
|
||||
content = ContentAsset.objects.create(studio=self.studio, title="No file")
|
||||
response = self.client.get(self.url(content))
|
||||
self.assertRedirects(response, reverse("studio:content_asset", args=["demo", content.pk]),
|
||||
fetch_redirect_response=False)
|
||||
|
||||
def test_other_studio_content(self):
|
||||
content = self.content(asset=self.other_asset)
|
||||
self.assertEqual(self.client.get(self.url(content)).status_code, 404)
|
||||
|
||||
|
||||
class TranscodeJobUpdateTests(TranscodeJobTestCase):
|
||||
def test_edit_draft(self):
|
||||
job = self.make_job()
|
||||
url = reverse("studio:transcode_job_update", args=["demo", job.pk])
|
||||
self.assertContains(self.client.get(url), "Edit transcode job")
|
||||
self.client.post(url, {"profile": self.profile.pk, "profile_definition": OTHER_YAML, "save": ""})
|
||||
job.refresh_from_db()
|
||||
self.assertEqual((job.profile_definition, job.status), (OTHER_YAML.strip(), JobStatus.DRAFT))
|
||||
|
||||
def test_edit_and_submit(self):
|
||||
job = self.make_job()
|
||||
url = reverse("studio:transcode_job_update", args=["demo", job.pk])
|
||||
self.client.post(url, {"profile": self.profile.pk, "profile_definition": OTHER_YAML, "submit": ""})
|
||||
job.refresh_from_db()
|
||||
self.assertEqual((job.profile_definition, job.status), (OTHER_YAML.strip(), JobStatus.PENDING))
|
||||
|
||||
def test_non_draft_not_editable(self):
|
||||
job = self.make_job(status=JobStatus.PENDING)
|
||||
url = reverse("studio:transcode_job_update", args=["demo", job.pk])
|
||||
detail = reverse("studio:transcode_job", args=["demo", job.pk])
|
||||
self.assertRedirects(self.client.get(url), detail, fetch_redirect_response=False)
|
||||
response = self.client.post(url, {"profile": self.profile.pk, "profile_definition": OTHER_YAML})
|
||||
self.assertRedirects(response, detail, fetch_redirect_response=False)
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.profile_definition, PROFILE_YAML)
|
||||
|
||||
def test_model_clean_blocks_non_draft_edits(self):
|
||||
job = self.make_job()
|
||||
job.status = JobStatus.PENDING
|
||||
job.full_clean() # The draft -> pending change itself is allowed.
|
||||
job.save()
|
||||
job.profile_definition = OTHER_YAML
|
||||
with self.assertRaisesMessage(ValidationError, "Only draft jobs can be edited."):
|
||||
job.full_clean()
|
||||
|
||||
def test_other_studio_job(self):
|
||||
job = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.other_studio, asset=self.other_asset)
|
||||
for name in ("transcode_job", "transcode_job_update"):
|
||||
self.assertEqual(self.client.get(reverse(f"studio:{name}", args=["demo", job.pk])).status_code, 404)
|
||||
|
||||
|
||||
class TranscodeJobSubmitAndDetailTests(TranscodeJobTestCase):
|
||||
def test_submit(self):
|
||||
job = self.make_job()
|
||||
url = reverse("studio:transcode_job_submit", args=["demo", job.pk])
|
||||
self.assertEqual(self.client.get(url).status_code, 405)
|
||||
self.client.post(url)
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.PENDING)
|
||||
job.status = JobStatus.IN_PROGRESS
|
||||
job.save()
|
||||
self.client.post(url) # A second submit changes nothing.
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.IN_PROGRESS)
|
||||
|
||||
def test_detail_buttons_only_for_drafts(self):
|
||||
job = self.make_job()
|
||||
packaging = PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.studio, transcode_job=job)
|
||||
url = reverse("studio:transcode_job", args=["demo", job.pk])
|
||||
response = self.client.get(url)
|
||||
self.assertContains(response, reverse("studio:transcode_job_submit", args=["demo", job.pk]))
|
||||
self.assertContains(response, reverse("studio:packaging_job", args=["demo", packaging.pk]))
|
||||
job.submit()
|
||||
self.assertNotContains(self.client.get(url), reverse("studio:transcode_job_submit", args=["demo", job.pk]))
|
||||
|
||||
def test_packaging_detail(self):
|
||||
job = self.make_job()
|
||||
packaging = PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.studio, transcode_job=job)
|
||||
response = self.client.get(reverse("studio:packaging_job", args=["demo", packaging.pk]))
|
||||
self.assertContains(response, "Packaging starts after transcode job")
|
||||
other_job = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.other_studio, asset=self.other_asset)
|
||||
other = PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.other_studio, transcode_job=other_job)
|
||||
self.assertEqual(self.client.get(reverse("studio:packaging_job", args=["demo", other.pk])).status_code, 404)
|
||||
|
||||
|
||||
class PackagingJobDeleteTests(TranscodeJobTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.storage = get_storage()
|
||||
self.job = self.make_job(status=JobStatus.COMPLETED)
|
||||
self.packaging = PackagingJob.objects.create(
|
||||
slug=PackagingJob.get_random_slug(), studio=self.studio, transcode_job=self.job,
|
||||
status=JobStatus.COMPLETED,
|
||||
)
|
||||
self.package = self.packaging.package_path
|
||||
for key in ("hls/master.m3u8", "hls/media-1/stream.m3u8", "hls/media-1/segment-0.ts"):
|
||||
self.storage.put_stream("demo", f"{self.package}/{key}", [b"x"])
|
||||
self.storage.put_stream("demo", "packages/other/hls/master.m3u8", [b"keep"])
|
||||
self.url = reverse("studio:packaging_job_delete", args=["demo", self.packaging.pk])
|
||||
|
||||
def test_detail_links_to_delete(self):
|
||||
response = self.client.get(reverse("studio:packaging_job", args=["demo", self.packaging.pk]))
|
||||
self.assertContains(response, self.url)
|
||||
|
||||
def test_confirm_page(self):
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, "This deletes 3 files in")
|
||||
self.assertContains(response, f"{self.package}/")
|
||||
|
||||
def test_delete_removes_files_then_job(self):
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, reverse("studio:transcode_job", args=["demo", self.job.pk]),
|
||||
fetch_redirect_response=False)
|
||||
self.assertFalse(PackagingJob.objects.filter(pk=self.packaging.pk).exists())
|
||||
self.assertFalse(self.storage.object_path("demo", self.package).exists())
|
||||
self.assertTrue(self.storage.object_exists("demo", "packages/other/hls/master.m3u8"))
|
||||
self.assertTrue(TranscodeJob.objects.filter(pk=self.job.pk).exists())
|
||||
|
||||
def test_job_kept_when_files_remain(self):
|
||||
with mock.patch.object(S3FileStorage, "delete_folder"):
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, reverse("studio:packaging_job", args=["demo", self.packaging.pk]),
|
||||
fetch_redirect_response=False)
|
||||
self.assertTrue(PackagingJob.objects.filter(pk=self.packaging.pk).exists())
|
||||
messages = [str(m) for m in get_messages(response.wsgi_request)]
|
||||
self.assertIn("3 file(s)", messages[0])
|
||||
|
||||
def test_running_job_not_deleted(self):
|
||||
PackagingJob.objects.filter(pk=self.packaging.pk).update(status=JobStatus.IN_PROGRESS)
|
||||
self.assertNotContains(self.client.get(reverse("studio:packaging_job", args=["demo", self.packaging.pk])),
|
||||
self.url)
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(PackagingJob.objects.filter(pk=self.packaging.pk).exists())
|
||||
self.assertTrue(self.storage.object_exists("demo", f"{self.package}/hls/master.m3u8"))
|
||||
|
||||
def test_job_without_files(self):
|
||||
self.storage.delete_folder("demo", self.package)
|
||||
self.client.post(self.url)
|
||||
self.assertFalse(PackagingJob.objects.filter(pk=self.packaging.pk).exists())
|
||||
|
||||
def test_other_studio(self):
|
||||
other_job = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.other_studio,
|
||||
asset=self.other_asset)
|
||||
other = PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.other_studio,
|
||||
transcode_job=other_job)
|
||||
url = reverse("studio:packaging_job_delete", args=["demo", other.pk])
|
||||
self.assertEqual(self.client.post(url).status_code, 404)
|
||||
self.assertTrue(PackagingJob.objects.filter(pk=other.pk).exists())
|
||||
|
||||
def test_folder_must_be_inside_bucket(self):
|
||||
for folder in ("", "/", "."):
|
||||
with self.assertRaises(InvalidKey):
|
||||
self.storage.delete_folder("demo", folder)
|
||||
with self.assertRaises(ValueError):
|
||||
PackagingJob(slug="").package_path
|
||||
|
||||
|
||||
class ContentPagesTests(TranscodeJobTestCase):
|
||||
def test_content_asset_page_lists_jobs(self):
|
||||
job = self.make_job()
|
||||
packaging = PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.studio, transcode_job=job)
|
||||
response = self.client.get(reverse("studio:content_asset", args=["demo", self.content_asset.pk]))
|
||||
content = response.content.decode()
|
||||
jobs_at = content.index("Transcode jobs")
|
||||
self.assertLess(jobs_at, content.index('id="content-form"'))
|
||||
self.assertContains(response, reverse("studio:transcode_job", args=["demo", job.pk]))
|
||||
self.assertContains(response, reverse("studio:packaging_job", args=["demo", packaging.pk]))
|
||||
self.assertContains(response, reverse("studio:transcode_job_create", args=["demo", self.content_asset.pk]))
|
||||
|
||||
def test_content_list_has_transcode_button(self):
|
||||
ContentAsset.objects.create(studio=self.studio, title="No file")
|
||||
response = self.client.get(reverse("studio:content_assets", args=["demo"]))
|
||||
self.assertContains(response, reverse("studio:transcode_job_create", args=["demo", self.content_asset.pk]),
|
||||
count=1)
|
||||
|
||||
def test_profiles_tab(self):
|
||||
url = reverse("studio:detail", args=["demo"])
|
||||
self.assertContains(self.client.get(url + "?tab=profiles"), 'class="nav-link active" id="profiles-tab"')
|
||||
self.assertContains(self.client.get(url + "?tab=bogus"), 'class="nav-link active" id="files-tab"')
|
||||
|
||||
|
||||
class PackagingJobCreateTests(TranscodeJobTestCase):
|
||||
def url(self, job):
|
||||
return reverse("studio:packaging_job_create", args=["demo", job.pk])
|
||||
|
||||
def detail(self, job):
|
||||
return self.client.get(reverse("studio:transcode_job", args=["demo", job.pk]))
|
||||
|
||||
def test_create(self):
|
||||
job = self.make_job(status=JobStatus.COMPLETED)
|
||||
self.assertContains(self.detail(job), self.url(job))
|
||||
response = self.client.post(self.url(job))
|
||||
packaging = PackagingJob.objects.get(transcode_job=job)
|
||||
self.assertRedirects(response, reverse("studio:packaging_job", args=["demo", packaging.pk]),
|
||||
fetch_redirect_response=False)
|
||||
self.assertEqual(packaging.status, JobStatus.PENDING)
|
||||
self.assertEqual(packaging.studio, self.studio)
|
||||
self.assertEqual(packaging.requested_by, self.user)
|
||||
self.assertTrue(packaging.slug.startswith("p-"))
|
||||
|
||||
def test_pending_transcode_allowed(self):
|
||||
job = self.make_job(status=JobStatus.PENDING)
|
||||
self.client.post(self.url(job))
|
||||
self.assertEqual(job.packaging_jobs.count(), 1)
|
||||
|
||||
def test_no_duplicate_while_queued_or_running(self):
|
||||
job = self.make_job(status=JobStatus.COMPLETED)
|
||||
self.client.post(self.url(job))
|
||||
self.assertNotContains(self.detail(job), self.url(job))
|
||||
response = self.client.post(self.url(job))
|
||||
self.assertRedirects(response, reverse("studio:transcode_job", args=["demo", job.pk]),
|
||||
fetch_redirect_response=False)
|
||||
self.assertEqual(job.packaging_jobs.count(), 1)
|
||||
job.packaging_jobs.update(status=JobStatus.IN_PROGRESS)
|
||||
self.client.post(self.url(job))
|
||||
self.assertEqual(job.packaging_jobs.count(), 1)
|
||||
job.packaging_jobs.update(status=JobStatus.COMPLETED)
|
||||
self.assertContains(self.detail(job), self.url(job))
|
||||
self.client.post(self.url(job))
|
||||
self.assertEqual(job.packaging_jobs.count(), 2)
|
||||
|
||||
def test_not_for_draft_or_failed(self):
|
||||
for status in (JobStatus.DRAFT, JobStatus.FAILED):
|
||||
job = self.make_job(status=status)
|
||||
self.assertNotContains(self.detail(job), self.url(job))
|
||||
self.client.post(self.url(job))
|
||||
self.assertFalse(job.packaging_jobs.exists(), status)
|
||||
|
||||
def test_get_not_allowed_and_other_studio(self):
|
||||
job = self.make_job(status=JobStatus.COMPLETED)
|
||||
self.assertEqual(self.client.get(self.url(job)).status_code, 405)
|
||||
other = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.other_studio,
|
||||
asset=self.other_asset, status=JobStatus.COMPLETED)
|
||||
self.assertEqual(self.client.post(self.url(other)).status_code, 404)
|
||||
self.assertFalse(other.packaging_jobs.exists())
|
||||
|
||||
|
||||
class UploadedAssetDeleteTests(TranscodeJobTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.storage = get_storage()
|
||||
self.storage.put_stream("demo", self.asset.s3_path, [b"video"])
|
||||
self.url = reverse("studio:uploaded_asset_delete", args=["demo", self.asset.pk])
|
||||
self.content_url = reverse("studio:content_asset", args=["demo", self.content_asset.pk])
|
||||
|
||||
def test_content_page_links_to_delete(self):
|
||||
self.assertContains(self.client.get(self.content_url), self.url)
|
||||
|
||||
def test_confirm_page(self):
|
||||
self.make_job(status=JobStatus.COMPLETED)
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, "Delete pilot.mp4?")
|
||||
self.assertContains(response, "shows/pilot.mp4")
|
||||
self.assertContains(response, "1 transcode job and its outputs are kept")
|
||||
self.assertContains(response, "Pilot")
|
||||
|
||||
def test_delete_keeps_jobs_and_content(self):
|
||||
job = self.make_job(status=JobStatus.COMPLETED)
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, self.content_url, fetch_redirect_response=False)
|
||||
self.assertFalse(self.storage.object_exists("demo", "shows/pilot.mp4"))
|
||||
self.assertFalse(UploadedAsset.objects.filter(pk=self.asset.pk).exists())
|
||||
job.refresh_from_db()
|
||||
self.assertIsNone(job.asset)
|
||||
self.content_asset.refresh_from_db()
|
||||
self.assertIsNone(self.content_asset.uploaded_asset)
|
||||
self.assertContains(self.client.get(reverse("studio:transcode_job", args=["demo", job.pk])), "Deleted")
|
||||
self.assertContains(self.client.get(self.content_url), "No file")
|
||||
|
||||
def test_delete_without_content_goes_to_files(self):
|
||||
self.content_asset.delete()
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, reverse("studio:detail", args=["demo"]) + "?tab=files",
|
||||
fetch_redirect_response=False)
|
||||
self.assertFalse(UploadedAsset.objects.filter(pk=self.asset.pk).exists())
|
||||
|
||||
def test_missing_file_still_deletes_record(self):
|
||||
self.storage.delete_object("demo", self.asset.s3_path)
|
||||
self.client.post(self.url)
|
||||
self.assertFalse(UploadedAsset.objects.filter(pk=self.asset.pk).exists())
|
||||
|
||||
def test_record_kept_when_file_remains(self):
|
||||
with mock.patch.object(S3FileStorage, "delete_object", side_effect=PermissionError("denied")):
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(UploadedAsset.objects.filter(pk=self.asset.pk).exists())
|
||||
self.assertTrue(self.storage.object_exists("demo", "shows/pilot.mp4"))
|
||||
|
||||
def test_blocked_by_active_transcode(self):
|
||||
for status in (JobStatus.PENDING, JobStatus.IN_PROGRESS):
|
||||
job = self.make_job(status=status)
|
||||
self.assertContains(self.client.get(self.url), "queued or running")
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(UploadedAsset.objects.filter(pk=self.asset.pk).exists(), status)
|
||||
self.assertTrue(self.storage.object_exists("demo", "shows/pilot.mp4"))
|
||||
job.delete()
|
||||
|
||||
def test_other_studio(self):
|
||||
url = reverse("studio:uploaded_asset_delete", args=["demo", self.other_asset.pk])
|
||||
self.assertEqual(self.client.post(url).status_code, 404)
|
||||
self.assertTrue(UploadedAsset.objects.filter(pk=self.other_asset.pk).exists())
|
||||
|
||||
|
||||
class TranscodeJobDeleteTests(TranscodeJobTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.storage = get_storage()
|
||||
self.job = self.make_job(status=JobStatus.COMPLETED)
|
||||
for name in ("output_720p.mp4", "output_audio.mp4"):
|
||||
key = f"{self.job.output_path}/{name}"
|
||||
self.storage.put_stream("demo", key, [b"x"])
|
||||
TranscodedAsset.objects.create(studio=self.studio, content_asset=self.content_asset,
|
||||
transcode_job=self.job, filename=name, s3_path=key, format="mp4")
|
||||
self.storage.put_stream("demo", "transcodes/other/output_720p.mp4", [b"keep"])
|
||||
self.url = reverse("studio:transcode_job_delete", args=["demo", self.job.pk])
|
||||
self.detail_url = reverse("studio:transcode_job", args=["demo", self.job.pk])
|
||||
|
||||
def exists(self):
|
||||
return TranscodeJob.objects.filter(pk=self.job.pk).exists()
|
||||
|
||||
def add_packaging(self):
|
||||
return PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.studio,
|
||||
transcode_job=self.job, status=JobStatus.COMPLETED)
|
||||
|
||||
def test_detail_links_to_delete(self):
|
||||
self.assertContains(self.client.get(self.detail_url), self.url)
|
||||
|
||||
def test_confirm_page(self):
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, "This deletes 2 output files in")
|
||||
self.assertContains(response, f"{self.job.output_path}/")
|
||||
|
||||
def test_delete_removes_outputs_then_job(self):
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, reverse("studio:content_asset", args=["demo", self.content_asset.pk]),
|
||||
fetch_redirect_response=False)
|
||||
self.assertFalse(self.exists())
|
||||
self.assertFalse(TranscodedAsset.objects.exists())
|
||||
self.assertFalse(self.storage.object_path("demo", self.job.output_path).exists())
|
||||
self.assertTrue(self.storage.object_exists("demo", "transcodes/other/output_720p.mp4"))
|
||||
self.assertTrue(UploadedAsset.objects.filter(pk=self.asset.pk).exists())
|
||||
|
||||
def test_outputs_removed_before_record(self):
|
||||
order = []
|
||||
real_delete_folder = S3FileStorage.delete_folder
|
||||
real_qs_delete = QuerySet.delete
|
||||
|
||||
def tracking_delete_folder(storage, *args):
|
||||
order.append("files")
|
||||
return real_delete_folder(storage, *args)
|
||||
|
||||
def tracking_qs_delete(qs):
|
||||
if qs.model is TranscodeJob:
|
||||
# The outputs must already be gone when the record is deleted.
|
||||
self.assertEqual(self.storage.folder_objects("demo", self.job.output_path), [])
|
||||
order.append("record")
|
||||
return real_qs_delete(qs)
|
||||
|
||||
with mock.patch.object(S3FileStorage, "delete_folder", tracking_delete_folder), \
|
||||
mock.patch.object(QuerySet, "delete", tracking_qs_delete):
|
||||
self.client.post(self.url)
|
||||
self.assertEqual(order, ["files", "record"])
|
||||
self.assertFalse(self.exists())
|
||||
|
||||
def test_blocked_by_packaging_job(self):
|
||||
self.add_packaging()
|
||||
self.assertNotContains(self.client.get(self.detail_url), self.url)
|
||||
self.assertContains(self.client.get(self.url), "packaging jobs first")
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(self.exists())
|
||||
self.assertTrue(self.storage.object_exists("demo", f"{self.job.output_path}/output_720p.mp4"))
|
||||
|
||||
def test_blocked_while_running(self):
|
||||
TranscodeJob.objects.filter(pk=self.job.pk).update(status=JobStatus.IN_PROGRESS)
|
||||
self.assertNotContains(self.client.get(self.detail_url), self.url)
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(self.exists())
|
||||
self.assertTrue(self.storage.object_exists("demo", f"{self.job.output_path}/output_720p.mp4"))
|
||||
|
||||
def test_packaging_job_added_during_delete_keeps_job(self):
|
||||
real_delete_folder = S3FileStorage.delete_folder
|
||||
|
||||
def add_packaging_meanwhile(storage, *args):
|
||||
self.add_packaging()
|
||||
return real_delete_folder(storage, *args)
|
||||
|
||||
with mock.patch.object(S3FileStorage, "delete_folder", add_packaging_meanwhile):
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(self.exists())
|
||||
self.assertEqual(self.job.packaging_jobs.count(), 1)
|
||||
|
||||
def test_job_kept_when_outputs_remain(self):
|
||||
with mock.patch.object(S3FileStorage, "delete_folder"), \
|
||||
mock.patch.object(S3FileStorage, "delete_object", return_value=False):
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, self.detail_url, fetch_redirect_response=False)
|
||||
self.assertTrue(self.exists())
|
||||
self.assertIn("2 output file(s)", [str(m) for m in get_messages(response.wsgi_request)][0])
|
||||
|
||||
def test_output_outside_folder_is_removed(self):
|
||||
TranscodedAsset.objects.create(studio=self.studio, transcode_job=self.job, filename="old.mp4",
|
||||
s3_path="legacy/old.mp4", format="mp4")
|
||||
self.storage.put_stream("demo", "legacy/old.mp4", [b"x"])
|
||||
self.client.post(self.url)
|
||||
self.assertFalse(self.exists())
|
||||
self.assertFalse(self.storage.object_exists("demo", "legacy/old.mp4"))
|
||||
|
||||
def test_draft_without_outputs(self):
|
||||
draft = self.make_job()
|
||||
url = reverse("studio:transcode_job_delete", args=["demo", draft.pk])
|
||||
self.assertContains(self.client.get(reverse("studio:transcode_job", args=["demo", draft.pk])), url)
|
||||
response = self.client.post(url)
|
||||
self.assertFalse(TranscodeJob.objects.filter(pk=draft.pk).exists())
|
||||
self.assertEqual(response.status_code, 302)
|
||||
|
||||
def test_without_content_goes_to_content_tab(self):
|
||||
TranscodeJob.objects.filter(pk=self.job.pk).update(content_asset=None)
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, reverse("studio:detail", args=["demo"]) + "?tab=content",
|
||||
fetch_redirect_response=False)
|
||||
|
||||
def test_other_studio(self):
|
||||
other = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.other_studio,
|
||||
asset=self.other_asset, status=JobStatus.COMPLETED)
|
||||
url = reverse("studio:transcode_job_delete", args=["demo", other.pk])
|
||||
self.assertEqual(self.client.post(url).status_code, 404)
|
||||
self.assertTrue(TranscodeJob.objects.filter(pk=other.pk).exists())
|
||||
|
||||
|
||||
class ContentAssetDeleteTests(TranscodeJobTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.content_asset.uploaded_asset = None
|
||||
self.content_asset.save()
|
||||
self.url = reverse("studio:content_asset_delete", args=["demo", self.content_asset.pk])
|
||||
self.page = reverse("studio:content_asset", args=["demo", self.content_asset.pk])
|
||||
|
||||
def exists(self):
|
||||
return ContentAsset.objects.filter(pk=self.content_asset.pk).exists()
|
||||
|
||||
def test_delete(self):
|
||||
self.assertContains(self.client.get(self.page), self.url)
|
||||
self.assertContains(self.client.get(self.url), "Delete Pilot?")
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, reverse("studio:detail", args=["demo"]) + "?tab=content",
|
||||
fetch_redirect_response=False)
|
||||
self.assertFalse(self.exists())
|
||||
|
||||
def test_hidden_and_refused_with_file(self):
|
||||
self.content_asset.uploaded_asset = self.asset
|
||||
self.content_asset.save()
|
||||
self.assertNotContains(self.client.get(self.page), self.url)
|
||||
self.assertContains(self.client.get(self.url), "Delete its uploaded file first.")
|
||||
response = self.client.post(self.url)
|
||||
self.assertRedirects(response, self.page, fetch_redirect_response=False)
|
||||
self.assertTrue(self.exists())
|
||||
|
||||
def test_hidden_and_refused_with_transcode_job(self):
|
||||
job = self.make_job()
|
||||
self.assertNotContains(self.client.get(self.page), self.url)
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(self.exists())
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.content_asset, self.content_asset)
|
||||
|
||||
def test_refused_with_transcoded_asset(self):
|
||||
# Shown (no file, no jobs) but refused: another record still refers to it.
|
||||
job = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.studio,
|
||||
asset=self.asset, profile_definition=PROFILE_YAML)
|
||||
TranscodedAsset.objects.create(studio=self.studio, content_asset=self.content_asset, transcode_job=job,
|
||||
filename="a.mp4", s3_path="transcodes/x/a.mp4", format="mp4")
|
||||
self.assertContains(self.client.get(self.page), self.url)
|
||||
self.assertContains(self.client.get(self.url), "transcoded assets")
|
||||
response = self.client.post(self.url)
|
||||
self.assertTrue(self.exists())
|
||||
self.assertIn("was not deleted", [str(m) for m in get_messages(response.wsgi_request)][0])
|
||||
|
||||
def test_reference_added_before_confirm(self):
|
||||
real_delete_blocker = ContentAsset.delete_blocker
|
||||
calls = []
|
||||
|
||||
def attach_job_first(content):
|
||||
if not calls:
|
||||
self.make_job()
|
||||
calls.append(1)
|
||||
return real_delete_blocker(content)
|
||||
|
||||
with mock.patch.object(ContentAsset, "delete_blocker", attach_job_first):
|
||||
self.client.post(self.url)
|
||||
self.assertTrue(self.exists())
|
||||
|
||||
def test_other_studio(self):
|
||||
other = ContentAsset.objects.create(studio=self.other_studio, title="Secret")
|
||||
url = reverse("studio:content_asset_delete", args=["demo", other.pk])
|
||||
self.assertEqual(self.client.post(url).status_code, 404)
|
||||
self.assertTrue(ContentAsset.objects.filter(pk=other.pk).exists())
|
||||
|
||||
def test_referencing_models_covers_all_relations(self):
|
||||
names = {r.related_model for r in ContentAsset._meta.related_objects}
|
||||
self.assertEqual(names, {TranscodeJob, TranscodedAsset})
|
||||
|
||||
|
||||
class ContentPagePackagesTests(TranscodeJobTestCase):
|
||||
def test_lists_packages_with_downloads(self):
|
||||
page = reverse("studio:content_asset", args=["demo", self.content_asset.pk])
|
||||
self.assertContains(self.client.get(page), "No packages yet.")
|
||||
|
||||
job = self.make_job(status=JobStatus.COMPLETED)
|
||||
done = PackagingJob.objects.create(slug="p-done", studio=self.studio, transcode_job=job,
|
||||
status=JobStatus.COMPLETED)
|
||||
queued = PackagingJob.objects.create(slug="p-queued", studio=self.studio, transcode_job=job)
|
||||
other_content = self.content(title="Other")
|
||||
other_job = TranscodeJob.objects.create(slug=TranscodeJob.get_random_slug(), studio=self.studio,
|
||||
asset=self.asset, content_asset=other_content,
|
||||
status=JobStatus.COMPLETED)
|
||||
PackagingJob.objects.create(slug="p-elsewhere", studio=self.studio, transcode_job=other_job,
|
||||
status=JobStatus.COMPLETED)
|
||||
|
||||
response = self.client.get(page)
|
||||
content = response.content.decode()
|
||||
self.assertLess(content.index("Transcode jobs"), content.index("Packages"))
|
||||
self.assertContains(response, "p-done")
|
||||
self.assertContains(response, "p-queued")
|
||||
self.assertNotContains(response, "p-elsewhere")
|
||||
self.assertContains(response, reverse("studio:packaging_job_download", args=["demo", done.pk]))
|
||||
self.assertNotContains(response, reverse("studio:packaging_job_download", args=["demo", queued.pk]))
|
||||
@@ -0,0 +1,438 @@
|
||||
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)
|
||||
|
||||
def test_reserved_folders(self):
|
||||
for key in ("transcodes/x.mp4", "packages/1/hls/master.m3u8", "packages"):
|
||||
response = self.client.put(f"/s3/demo/{key}", data=b"x", content_type="", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 400, key)
|
||||
response = self.client.post(f"/s3/demo/{key}?uploads", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 400, key)
|
||||
self.assertFalse(Path(self.storage_dir, "demo", "transcodes").exists())
|
||||
|
||||
|
||||
@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_reserved_folders(self):
|
||||
for folder in ("transcodes", "packages/hls", "packages"):
|
||||
response = self.call("POST", self.base, {"filename": "a.mp4", "folder": folder, "size": 1})
|
||||
self.assertEqual((response.status_code, response.json()["code"]), (400, "InvalidKey"), folder)
|
||||
response = self.call("POST", self.base, {"filename": "transcodes", "size": 1})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
response = self.call("POST", self.base, {"filename": "a.mp4", "folder": "videos/transcodes", "size": 1})
|
||||
self.assertEqual(response.status_code, 201)
|
||||
|
||||
def test_default_folder(self):
|
||||
response = self.client.get("/studio/demo/")
|
||||
self.assertContains(response, 'value="videos/raw"')
|
||||
|
||||
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,286 @@
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import timedelta
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from django.core.management import call_command
|
||||
from django.utils import timezone
|
||||
|
||||
from privatestudio import transcode as transcoder
|
||||
from privatestudio.studio import worker as worker_module
|
||||
from privatestudio.studio.models import (
|
||||
ContentAsset, JobStatus, PackagingJob, TranscodedAsset, TranscodeJob, UploadedAsset,
|
||||
)
|
||||
from privatestudio.studio.storage import get_storage
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
from privatestudio.studio.worker import (
|
||||
JobLog, Worker, claim_packaging_job, claim_transcode_job, fail_orphaned_packaging_jobs, recover_stale_jobs,
|
||||
)
|
||||
|
||||
PROFILE_YAML = "profiles:\n hd:\n resolution: 1280x720\n bitrate: 2500k\n"
|
||||
OUTPUTS = ["output_720p.mp4", "output_audio.mp4"]
|
||||
|
||||
|
||||
def fake_transcode(input_asset, profile_config, output_dir, encoder=None, on_line=None, on_start=None, log=None,
|
||||
return_code=0):
|
||||
output_dir = Path(output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
for name in OUTPUTS:
|
||||
(output_dir / name).write_bytes(b"video:" + name.encode())
|
||||
on_line("ffmpeg version x\n")
|
||||
on_line("frame=1 size=1\n")
|
||||
on_line("frame=2 size=2\n")
|
||||
return transcoder.TranscodeResult(return_code, list(OUTPUTS), ["ffmpeg"], "", "cpu")
|
||||
|
||||
|
||||
def fake_bento4(self, command, log):
|
||||
tool = Path(str(command[0])).name
|
||||
log(f"$ {tool}\n")
|
||||
if tool == "mp4fragment":
|
||||
Path(command[2]).write_bytes(Path(command[1]).read_bytes())
|
||||
elif tool == "mp4hls":
|
||||
out = Path(command[2])
|
||||
(out / "media-1").mkdir(parents=True)
|
||||
(out / "master.m3u8").write_text("#EXTM3U\n")
|
||||
(out / "media-1" / "stream.m3u8").write_text("#EXTM3U\n")
|
||||
(out / "media-1" / "segment-0.ts").write_bytes(b"ts")
|
||||
|
||||
|
||||
@mock.patch.object(worker_module, "HEARTBEAT_SECONDS", 3600)
|
||||
class WorkerTestCase(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.storage = get_storage()
|
||||
self.storage.put_stream("demo", "uploads/source.mov", [b"source"])
|
||||
self.asset = UploadedAsset.objects.create(
|
||||
studio=self.studio, filename="source.mov", size=6, s3_path="uploads/source.mov",
|
||||
)
|
||||
self.content = ContentAsset.objects.create(studio=self.studio, title="Movie", uploaded_asset=self.asset)
|
||||
|
||||
def make_job(self, status=JobStatus.PENDING, content=True, **kwargs):
|
||||
return TranscodeJob.objects.create(
|
||||
slug=TranscodeJob.get_random_slug(),
|
||||
studio=self.studio, asset=self.asset, content_asset=self.content if content else None,
|
||||
profile_definition=PROFILE_YAML, status=status, **kwargs,
|
||||
)
|
||||
|
||||
def make_packaging(self, job):
|
||||
return PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.studio, transcode_job=job)
|
||||
|
||||
|
||||
class ClaimTests(WorkerTestCase):
|
||||
def test_claims_oldest_pending_once(self):
|
||||
self.make_job(status=JobStatus.DRAFT)
|
||||
first = self.make_job(requested_at=timezone.now() - timedelta(minutes=5))
|
||||
second = self.make_job()
|
||||
claimed = claim_transcode_job()
|
||||
self.assertEqual(claimed.pk, first.pk)
|
||||
self.assertEqual(claimed.status, JobStatus.IN_PROGRESS)
|
||||
self.assertIsNotNone(claimed.started_at)
|
||||
self.assertTrue(claimed.worker)
|
||||
self.assertEqual(claim_transcode_job().pk, second.pk)
|
||||
self.assertIsNone(claim_transcode_job())
|
||||
|
||||
def test_packaging_waits_for_transcode(self):
|
||||
job = self.make_job()
|
||||
packaging = self.make_packaging(job)
|
||||
self.assertIsNone(claim_packaging_job())
|
||||
TranscodeJob.objects.filter(pk=job.pk).update(status=JobStatus.COMPLETED)
|
||||
self.assertEqual(claim_packaging_job().pk, packaging.pk)
|
||||
|
||||
def test_packaging_fails_with_transcode(self):
|
||||
job = self.make_job(status=JobStatus.FAILED)
|
||||
packaging = self.make_packaging(job)
|
||||
self.assertEqual(fail_orphaned_packaging_jobs(), 1)
|
||||
packaging.refresh_from_db()
|
||||
self.assertEqual(packaging.status, JobStatus.FAILED)
|
||||
self.assertIn("transcode job failed", packaging.output)
|
||||
|
||||
def test_recover_stale(self):
|
||||
old = timezone.now() - timedelta(hours=1)
|
||||
stale = self.make_job(status=JobStatus.IN_PROGRESS, heartbeat_at=old, transcode_output="log")
|
||||
fresh = self.make_job(status=JobStatus.IN_PROGRESS, heartbeat_at=timezone.now())
|
||||
self.assertEqual(recover_stale_jobs(), 1)
|
||||
stale.refresh_from_db()
|
||||
fresh.refresh_from_db()
|
||||
self.assertEqual(stale.status, JobStatus.FAILED)
|
||||
self.assertTrue(stale.transcode_output.startswith("log"))
|
||||
self.assertIn("stopped responding", stale.transcode_output)
|
||||
self.assertEqual(fresh.status, JobStatus.IN_PROGRESS)
|
||||
|
||||
|
||||
class JobLogTests(StudioTestCase):
|
||||
def test_keeps_last_progress_line(self):
|
||||
log = JobLog()
|
||||
for line in ["start\n", "frame=1\n", "frame=2\n", "end\n", "frame=3\n"]:
|
||||
log(line)
|
||||
self.assertEqual(log.text(), "start\nframe=2\nend\nframe=3\n")
|
||||
|
||||
|
||||
class TranscodeJobTests(WorkerTestCase):
|
||||
def run_job(self, job, **fake_kwargs):
|
||||
job = claim_transcode_job()
|
||||
with mock.patch.object(worker_module.transcoder, "transcode",
|
||||
side_effect=lambda *a, **k: fake_transcode(*a, **k, **fake_kwargs)) as m:
|
||||
Worker().run_transcode_job(job)
|
||||
job.refresh_from_db()
|
||||
return job, m
|
||||
|
||||
def test_success(self):
|
||||
job, m = self.run_job(self.make_job())
|
||||
self.assertEqual(m.call_args.args[0], self.storage.object_path("demo", "uploads/source.mov"))
|
||||
self.assertEqual(job.status, JobStatus.COMPLETED)
|
||||
self.assertIsNotNone(job.completed_at)
|
||||
self.assertIn("ffmpeg version", job.transcode_output)
|
||||
self.assertNotIn("frame=1", job.transcode_output)
|
||||
outputs = {a.filename: a for a in job.transcoded_assets.all()}
|
||||
self.assertEqual(set(outputs), set(OUTPUTS))
|
||||
self.assertEqual(outputs["output_audio.mp4"].format, "audio")
|
||||
self.assertEqual(outputs["output_720p.mp4"].content_asset, self.content)
|
||||
key = f"transcodes/{job.slug}/output_720p.mp4"
|
||||
self.assertEqual(outputs["output_720p.mp4"].s3_path, key)
|
||||
self.assertTrue(self.storage.object_exists("demo", key))
|
||||
self.assertEqual(list(self.storage.work_path.iterdir()), [])
|
||||
|
||||
def test_without_content_asset(self):
|
||||
job, _ = self.run_job(self.make_job(content=False))
|
||||
self.assertEqual(job.status, JobStatus.COMPLETED)
|
||||
self.assertIsNone(job.transcoded_assets.first().content_asset)
|
||||
|
||||
def test_ffmpeg_failure(self):
|
||||
job, _ = self.run_job(self.make_job(), return_code=1)
|
||||
self.assertEqual(job.status, JobStatus.FAILED)
|
||||
self.assertIn("ffmpeg exited with code 1", job.transcode_output)
|
||||
self.assertFalse(TranscodedAsset.objects.exists())
|
||||
self.assertEqual(list(self.storage.work_path.iterdir()), [])
|
||||
|
||||
def test_missing_source(self):
|
||||
self.storage.delete_object("demo", "uploads/source.mov")
|
||||
job, m = self.run_job(self.make_job())
|
||||
self.assertEqual(job.status, JobStatus.FAILED)
|
||||
self.assertIn("Source file is missing", job.transcode_output)
|
||||
m.assert_not_called()
|
||||
|
||||
def test_shutdown_requeues(self):
|
||||
job = self.make_job()
|
||||
claimed = claim_transcode_job()
|
||||
w = Worker()
|
||||
w.stop()
|
||||
with mock.patch.object(worker_module.transcoder, "transcode",
|
||||
side_effect=lambda *a, **k: fake_transcode(*a, **k, return_code=-15)):
|
||||
w.run_transcode_job(claimed)
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.PENDING)
|
||||
self.assertEqual(job.worker, "")
|
||||
|
||||
def test_stale_result_discarded(self):
|
||||
job = self.make_job()
|
||||
claimed = claim_transcode_job()
|
||||
TranscodeJob.objects.filter(pk=job.pk).update(status=JobStatus.FAILED)
|
||||
with mock.patch.object(worker_module.transcoder, "transcode", side_effect=fake_transcode):
|
||||
Worker().run_transcode_job(claimed)
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.FAILED)
|
||||
self.assertFalse(TranscodedAsset.objects.exists())
|
||||
|
||||
|
||||
@mock.patch.object(Worker, "_run_tool", fake_bento4)
|
||||
class PackagingJobTests(WorkerTestCase):
|
||||
def completed_transcode(self):
|
||||
job = self.make_job(status=JobStatus.COMPLETED)
|
||||
for name in OUTPUTS:
|
||||
key = f"transcodes/{job.slug}/{name}"
|
||||
self.storage.put_stream("demo", key, [b"data"])
|
||||
TranscodedAsset.objects.create(studio=self.studio, content_asset=self.content, transcode_job=job,
|
||||
filename=name, s3_path=key, format="mp4")
|
||||
return job
|
||||
|
||||
def test_success(self):
|
||||
packaging = self.make_packaging(self.completed_transcode())
|
||||
Worker().run_packaging_job(claim_packaging_job())
|
||||
packaging.refresh_from_db()
|
||||
self.assertEqual(packaging.status, JobStatus.COMPLETED, packaging.output)
|
||||
prefix = f"packages/{packaging.slug}/hls"
|
||||
self.assertEqual(packaging.manifest_path, f"{prefix}/master.m3u8")
|
||||
self.assertTrue(self.storage.object_exists("demo", f"{prefix}/master.m3u8"))
|
||||
self.assertTrue(self.storage.object_exists("demo", f"{prefix}/media-1/segment-0.ts"))
|
||||
self.assertIn("mp4hls", packaging.output)
|
||||
|
||||
def test_missing_outputs(self):
|
||||
packaging = self.make_packaging(self.make_job(status=JobStatus.COMPLETED))
|
||||
Worker().run_packaging_job(claim_packaging_job())
|
||||
packaging.refresh_from_db()
|
||||
self.assertEqual(packaging.status, JobStatus.FAILED)
|
||||
self.assertIn("no output files", packaging.output)
|
||||
|
||||
|
||||
class RunToolTests(StudioTestCase):
|
||||
def test_failure_and_missing_binary(self):
|
||||
log = JobLog()
|
||||
with self.assertRaisesMessage(worker_module.JobError, "exited with code 3"):
|
||||
Worker()._run_tool(["sh", "-c", "echo hi; exit 3"], log)
|
||||
self.assertIn("hi\n", log.text())
|
||||
with self.assertRaisesMessage(worker_module.JobError, "Could not run"):
|
||||
Worker()._run_tool(["/nonexistent/mp4hls"], log)
|
||||
|
||||
|
||||
@mock.patch.object(Worker, "_run_tool", fake_bento4)
|
||||
class RunWorkerCommandTests(WorkerTestCase):
|
||||
def test_once_runs_transcode_then_packaging(self):
|
||||
job = self.make_job()
|
||||
packaging = self.make_packaging(job)
|
||||
out = StringIO()
|
||||
with mock.patch.object(worker_module.transcoder, "transcode", side_effect=fake_transcode):
|
||||
call_command("run_worker", "--once", stdout=out)
|
||||
job.refresh_from_db()
|
||||
packaging.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.COMPLETED)
|
||||
self.assertEqual(packaging.status, JobStatus.COMPLETED, packaging.output)
|
||||
self.assertIn("Worker stopped.", out.getvalue())
|
||||
|
||||
|
||||
class RealTranscodeTests(WorkerTestCase):
|
||||
"""Runs ffmpeg for real when it is installed."""
|
||||
|
||||
def setUp(self):
|
||||
if not (shutil.which("ffmpeg") and shutil.which("ffprobe")):
|
||||
self.skipTest("ffmpeg is not installed")
|
||||
super().setUp()
|
||||
|
||||
def test_transcode(self):
|
||||
source = self.storage.object_path("demo", "uploads/source.mov")
|
||||
subprocess.run(
|
||||
["ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=2:size=640x360:rate=24",
|
||||
"-f", "lavfi", "-i", "sine=duration=2", "-shortest", "-f", "mp4", str(source)],
|
||||
check=True,
|
||||
)
|
||||
job = self.make_job()
|
||||
TranscodeJob.objects.filter(pk=job.pk).update(
|
||||
profile_definition="profiles:\n sd:\n resolution: 320x180\n bitrate: 300k\n",
|
||||
)
|
||||
Worker().run_transcode_job(claim_transcode_job())
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.COMPLETED, job.transcode_output)
|
||||
self.assertEqual(job.transcoded_assets.count(), 2)
|
||||
|
||||
|
||||
class MissingFfmpegTests(WorkerTestCase):
|
||||
def test_reports_missing_ffmpeg(self):
|
||||
job = self.make_job()
|
||||
with mock.patch.object(transcoder.subprocess, "Popen", side_effect=FileNotFoundError("no ffmpeg")):
|
||||
Worker().run_transcode_job(claim_transcode_job())
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.FAILED)
|
||||
self.assertIn("Could not run ffmpeg", job.transcode_output)
|
||||
|
||||
|
||||
class DeletedSourceTests(WorkerTestCase):
|
||||
def test_job_fails_when_source_deleted(self):
|
||||
job = self.make_job()
|
||||
self.asset.delete()
|
||||
Worker().run_transcode_job(claim_transcode_job())
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.status, JobStatus.FAILED)
|
||||
self.assertIn("source file was deleted", job.transcode_output)
|
||||
@@ -0,0 +1,245 @@
|
||||
"""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 InvalidKey, LockBusy, UploadGone, get_storage
|
||||
|
||||
MIB = 1024 * 1024
|
||||
MAX_PARTS = 10_000
|
||||
MAX_PART_SIZE = 5 * 1024 * MIB
|
||||
|
||||
# Top-level folders the job worker writes to (worker.py). Users can't upload into them.
|
||||
RESERVED_FOLDERS = ("transcodes", "packages")
|
||||
|
||||
|
||||
def check_upload_key(key: str) -> None:
|
||||
"""Raise InvalidKey if ``key`` is in, or would replace, a folder reserved for job output."""
|
||||
top = key.split("/", 1)[0]
|
||||
if top in RESERVED_FOLDERS:
|
||||
raise InvalidKey(f"Uploads to the '{top}/' folder are not allowed; it holds job output")
|
||||
|
||||
|
||||
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."""
|
||||
check_upload_key(key)
|
||||
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,59 @@
|
||||
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>/content/<int:pk>/delete/", views.ContentAssetDeleteView.as_view(),
|
||||
name="content_asset_delete"),
|
||||
path("<slug:bucket_name>/files/<int:pk>/delete/", views.UploadedAssetDeleteView.as_view(),
|
||||
name="uploaded_asset_delete"),
|
||||
path("<slug:bucket_name>/content/<int:pk>/transcode/new/", views.TranscodeJobCreateView.as_view(),
|
||||
name="transcode_job_create"),
|
||||
path("<slug:bucket_name>/hx/profiles/", views.TranscodeProfilesView.as_view(), name="transcode_profiles"),
|
||||
path("<slug:bucket_name>/profiles/new/", views.TranscodeProfileCreateView.as_view(),
|
||||
name="transcode_profile_create"),
|
||||
path("<slug:bucket_name>/profiles/<int:pk>/", views.TranscodeProfileUpdateView.as_view(),
|
||||
name="transcode_profile"),
|
||||
path("<slug:bucket_name>/profiles/<int:pk>/delete/", views.TranscodeProfileDeleteView.as_view(),
|
||||
name="transcode_profile_delete"),
|
||||
path("<slug:bucket_name>/transcode/<int:pk>/", views.TranscodeJobDetailView.as_view(), name="transcode_job"),
|
||||
path("<slug:bucket_name>/transcode/<int:pk>/edit/", views.TranscodeJobUpdateView.as_view(),
|
||||
name="transcode_job_update"),
|
||||
path("<slug:bucket_name>/transcode/<int:pk>/submit/", views.TranscodeJobSubmitView.as_view(),
|
||||
name="transcode_job_submit"),
|
||||
path("<slug:bucket_name>/transcode/<int:pk>/download/", views.TranscodeJobDownloadView.as_view(),
|
||||
name="transcode_job_download"),
|
||||
path("<slug:bucket_name>/transcode/<int:pk>/delete/", views.TranscodeJobDeleteView.as_view(),
|
||||
name="transcode_job_delete"),
|
||||
path("<slug:bucket_name>/transcode/<int:pk>/package/", views.PackagingJobCreateView.as_view(),
|
||||
name="packaging_job_create"),
|
||||
path("<slug:bucket_name>/packaging/<int:pk>/", views.PackagingJobDetailView.as_view(), name="packaging_job"),
|
||||
path("<slug:bucket_name>/packaging/<int:pk>/download/", views.PackagingJobDownloadView.as_view(),
|
||||
name="packaging_job_download"),
|
||||
path("<slug:bucket_name>/packaging/<int:pk>/delete/", views.PackagingJobDeleteView.as_view(),
|
||||
name="packaging_job_delete"),
|
||||
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,720 @@
|
||||
import errno
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
from django.contrib import messages
|
||||
from django.db import transaction
|
||||
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 CreateView, DeleteView, DetailView, ListView, UpdateView
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
|
||||
|
||||
from privatestudio.studio import uploads
|
||||
from privatestudio.studio.forms import ContentAssetForm, TranscodeJobForm, TranscodeProfileForm
|
||||
from privatestudio.studio.models import (
|
||||
ContentAsset, JobStatus, MultipartUpload, PackagingJob, Studio, TranscodeJob, TranscodeProfile, UploadedAsset,
|
||||
)
|
||||
from privatestudio.studio.profiles import EXAMPLE_PROFILE_YAML, load_default_profile
|
||||
from privatestudio.studio.request_body import BodyError, read_small_body
|
||||
from privatestudio.studio.storage import InvalidKey, get_storage
|
||||
from privatestudio.studio.zipstream import zip_response
|
||||
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"
|
||||
tabs = ("files", "content", "profiles")
|
||||
|
||||
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)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
tab = self.request.GET.get("tab")
|
||||
return super().get_context_data(active_tab=tab if tab in self.tabs else self.tabs[0], **kwargs)
|
||||
|
||||
|
||||
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):
|
||||
transcode_jobs = (
|
||||
self.object.transcode_jobs
|
||||
.select_related("profile")
|
||||
.order_by("-requested_at", "-pk")
|
||||
)
|
||||
packaging_jobs = (
|
||||
PackagingJob.objects.filter(studio=self.studio, transcode_job__content_asset=self.object)
|
||||
.select_related("transcode_job")
|
||||
.order_by("-requested_at", "-pk")
|
||||
)
|
||||
return super().get_context_data(
|
||||
studio=self.studio, transcode_jobs=transcode_jobs, packaging_jobs=packaging_jobs, **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 StudioContextMixin:
|
||||
"""Adds the studio to template context and forms."""
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(studio=self.studio, **kwargs)
|
||||
|
||||
|
||||
class StudioFormMixin(StudioContextMixin):
|
||||
def get_form_kwargs(self):
|
||||
return {**super().get_form_kwargs(), "studio": self.studio}
|
||||
|
||||
|
||||
def _profiles_tab_url(studio):
|
||||
return reverse("studio:detail", args=[studio.bucket_name]) + "?tab=profiles"
|
||||
|
||||
|
||||
class TranscodeProfilesView(StudioContextMixin, StudioMixin, ListView):
|
||||
model = TranscodeProfile
|
||||
template_name = "privatestudio/hx_transcode_profiles.html"
|
||||
context_object_name = "profiles"
|
||||
|
||||
def get_queryset(self):
|
||||
return super().get_queryset().filter(studio=self.studio).select_related("created_by").order_by("name")
|
||||
|
||||
|
||||
class TranscodeProfileEditMixin(StudioFormMixin):
|
||||
model = TranscodeProfile
|
||||
form_class = TranscodeProfileForm
|
||||
template_name = "privatestudio/transcode_profile_form.html"
|
||||
context_object_name = "profile"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(example_profile=EXAMPLE_PROFILE_YAML, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
response = super().form_valid(form)
|
||||
messages.success(self.request, f"Saved profile {self.object.name}.")
|
||||
return response
|
||||
|
||||
def get_success_url(self):
|
||||
return _profiles_tab_url(self.studio)
|
||||
|
||||
|
||||
class TranscodeProfileCreateView(TranscodeProfileEditMixin, StudioMixin, CreateView):
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(default_profile=load_default_profile(), **kwargs)
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs["instance"] = TranscodeProfile(studio=self.studio, created_by=self.request.user)
|
||||
return kwargs
|
||||
|
||||
|
||||
class TranscodeProfileUpdateView(TranscodeProfileEditMixin, StudioMixin, UpdateView):
|
||||
def get_queryset(self):
|
||||
return TranscodeProfile.objects.filter(studio=self.studio)
|
||||
|
||||
|
||||
class TranscodeProfileDeleteView(StudioContextMixin, StudioMixin, DeleteView):
|
||||
model = TranscodeProfile
|
||||
template_name = "privatestudio/transcode_profile_confirm_delete.html"
|
||||
context_object_name = "profile"
|
||||
|
||||
def get_queryset(self):
|
||||
return TranscodeProfile.objects.filter(studio=self.studio)
|
||||
|
||||
def form_valid(self, form):
|
||||
name = self.object.name
|
||||
response = super().form_valid(form)
|
||||
messages.success(self.request, f"Deleted profile {name}.")
|
||||
return response
|
||||
|
||||
def get_success_url(self):
|
||||
return _profiles_tab_url(self.studio)
|
||||
|
||||
|
||||
class TranscodeJobEditMixin(StudioFormMixin):
|
||||
"""Shared by the create and update views: the form has 'save' (draft) and 'submit' buttons."""
|
||||
model = TranscodeJob
|
||||
form_class = TranscodeJobForm
|
||||
template_name = "privatestudio/transcode_job_form.html"
|
||||
context_object_name = "job"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
profiles = {str(p.pk): p.profile_definition for p in self.studio.transcode_profiles.all()}
|
||||
return super().get_context_data(
|
||||
example_profile=EXAMPLE_PROFILE_YAML, profile_definitions=profiles,
|
||||
content_asset=self.content_asset, **kwargs,
|
||||
)
|
||||
|
||||
def form_valid(self, form):
|
||||
with transaction.atomic():
|
||||
self.save_job(form)
|
||||
submitted = "submit" in self.request.POST and self.object.submit()
|
||||
if submitted:
|
||||
messages.success(self.request, f"Submitted transcode job {self.object.pk}.")
|
||||
else:
|
||||
messages.success(self.request, f"Saved draft transcode job {self.object.pk}.")
|
||||
return redirect(self.get_success_url())
|
||||
|
||||
def save_job(self, form):
|
||||
self.object = form.save()
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse("studio:transcode_job", args=[self.studio.bucket_name, self.object.pk])
|
||||
|
||||
|
||||
class TranscodeJobCreateView(TranscodeJobEditMixin, StudioMixin, CreateView):
|
||||
def get(self, request, *args, **kwargs):
|
||||
return self.load_content_asset() or super().get(request, *args, **kwargs)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
return self.load_content_asset() or super().post(request, *args, **kwargs)
|
||||
|
||||
def load_content_asset(self):
|
||||
"""Sets self.content_asset; returns a redirect if it has no file to transcode."""
|
||||
self.content_asset = get_object_or_404(
|
||||
ContentAsset.objects.select_related("uploaded_asset"), pk=self.kwargs["pk"], studio=self.studio,
|
||||
)
|
||||
if self.content_asset.uploaded_asset is None:
|
||||
messages.error(self.request, "This content has no uploaded file to transcode.")
|
||||
return redirect("studio:content_asset", self.studio.bucket_name, self.content_asset.pk)
|
||||
return None
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs["instance"] = TranscodeJob(
|
||||
slug=TranscodeJob.get_random_slug(), studio=self.studio, requested_by=self.request.user,
|
||||
content_asset=self.content_asset, asset=self.content_asset.uploaded_asset,
|
||||
)
|
||||
return kwargs
|
||||
|
||||
def save_job(self, form):
|
||||
super().save_job(form)
|
||||
PackagingJob.objects.create(
|
||||
slug=PackagingJob.get_random_slug(), studio=self.studio, requested_by=self.request.user,
|
||||
transcode_job=self.object,
|
||||
)
|
||||
|
||||
|
||||
class TranscodeJobUpdateView(TranscodeJobEditMixin, StudioMixin, UpdateView):
|
||||
def get_queryset(self):
|
||||
return TranscodeJob.objects.filter(studio=self.studio).select_related("content_asset", "asset")
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
return self.check_editable() or super().get(request, *args, **kwargs)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
return self.check_editable() or super().post(request, *args, **kwargs)
|
||||
|
||||
def check_editable(self):
|
||||
"""Loads the job; returns a redirect to its detail page if it is no longer a draft."""
|
||||
job = self.get_object()
|
||||
self.content_asset = job.content_asset
|
||||
if not job.is_editable:
|
||||
messages.warning(self.request, f"Transcode job {job.pk} is {job.get_status_display().lower()} "
|
||||
"and can no longer be edited.")
|
||||
return redirect("studio:transcode_job", self.studio.bucket_name, job.pk)
|
||||
return None
|
||||
|
||||
|
||||
class TranscodeJobDetailView(StudioContextMixin, StudioMixin, DetailView):
|
||||
model = TranscodeJob
|
||||
template_name = "privatestudio/transcode_job_detail.html"
|
||||
context_object_name = "job"
|
||||
|
||||
def get_queryset(self):
|
||||
return (
|
||||
TranscodeJob.objects.filter(studio=self.studio)
|
||||
.select_related("profile", "content_asset", "asset", "requested_by")
|
||||
.prefetch_related("packaging_jobs", "transcoded_assets")
|
||||
)
|
||||
|
||||
|
||||
class TranscodeJobSubmitView(StudioMixin, View):
|
||||
http_method_names = ["post"]
|
||||
|
||||
def post(self, request, bucket_name, pk):
|
||||
job = get_object_or_404(TranscodeJob, pk=pk, studio=self.studio)
|
||||
if job.submit():
|
||||
messages.success(request, f"Submitted transcode job {job.pk}.")
|
||||
else:
|
||||
messages.warning(request, f"Transcode job {job.pk} was already submitted.")
|
||||
return redirect("studio:transcode_job", self.studio.bucket_name, job.pk)
|
||||
|
||||
|
||||
class ContentAssetDeleteView(StudioContextMixin, StudioMixin, DeleteView):
|
||||
"""Deletes a content entry that has no file and nothing else referring to it."""
|
||||
model = ContentAsset
|
||||
template_name = "privatestudio/content_asset_confirm_delete.html"
|
||||
context_object_name = "content_asset"
|
||||
|
||||
def get_queryset(self):
|
||||
return ContentAsset.objects.filter(studio=self.studio)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(blocker=self.object.delete_blocker(), **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
bucket = self.studio.bucket_name
|
||||
with transaction.atomic():
|
||||
# Re-read inside the transaction (a write lock on SQLite), so a file or job attached
|
||||
# meanwhile is seen. Deleting would otherwise silently clear their references.
|
||||
content = ContentAsset.objects.filter(pk=self.object.pk).first()
|
||||
if content is None:
|
||||
messages.warning(self.request, "This content entry was already deleted.")
|
||||
return redirect(reverse("studio:detail", args=[bucket]) + "?tab=content")
|
||||
blocker = content.delete_blocker()
|
||||
if blocker is None:
|
||||
content.delete()
|
||||
if blocker is not None:
|
||||
messages.error(self.request, f"{content.title} was not deleted. {blocker}")
|
||||
return redirect("studio:content_asset", bucket, content.pk)
|
||||
messages.success(self.request, f"Deleted {content.title}.")
|
||||
return redirect(reverse("studio:detail", args=[bucket]) + "?tab=content")
|
||||
|
||||
|
||||
class TranscodeJobDeleteView(StudioContextMixin, StudioMixin, DeleteView):
|
||||
"""Deletes a transcode job's output files, then the job. Refused while it has packaging jobs."""
|
||||
model = TranscodeJob
|
||||
template_name = "privatestudio/transcode_job_confirm_delete.html"
|
||||
context_object_name = "job"
|
||||
|
||||
def get_queryset(self):
|
||||
return TranscodeJob.objects.filter(studio=self.studio).select_related("content_asset")
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
storage = get_storage()
|
||||
files = storage.folder_objects(self.studio.bucket_name, self.object.output_path)
|
||||
return super().get_context_data(file_count=len(files), blocker=self.object.delete_blocker(), **kwargs)
|
||||
|
||||
def output_keys(self, storage, job):
|
||||
"""Output files still in storage: the job's folder plus any recorded output stored elsewhere."""
|
||||
bucket = self.studio.bucket_name
|
||||
keys = set(storage.folder_objects(bucket, job.output_path))
|
||||
for path in job.transcoded_assets.values_list("s3_path", flat=True):
|
||||
try:
|
||||
if storage.object_exists(bucket, path):
|
||||
keys.add(path)
|
||||
except InvalidKey:
|
||||
pass
|
||||
return sorted(keys)
|
||||
|
||||
def form_valid(self, form):
|
||||
job = self.object
|
||||
bucket = self.studio.bucket_name
|
||||
detail = redirect("studio:transcode_job", bucket, job.pk)
|
||||
blocker = job.delete_blocker()
|
||||
if blocker:
|
||||
messages.error(self.request, blocker)
|
||||
return detail
|
||||
|
||||
storage = get_storage()
|
||||
for path in job.transcoded_assets.values_list("s3_path", flat=True):
|
||||
try:
|
||||
storage.delete_object(bucket, path)
|
||||
except (InvalidKey, OSError) as e:
|
||||
logger.warning("Could not delete %s/%s: %s", bucket, path, e)
|
||||
storage.delete_folder(bucket, job.output_path)
|
||||
remaining = self.output_keys(storage, job)
|
||||
if remaining:
|
||||
messages.error(
|
||||
self.request,
|
||||
f"{len(remaining)} output file(s) could not be deleted, so the transcode job was kept. "
|
||||
"Try again, or check the storage permissions.",
|
||||
)
|
||||
return detail
|
||||
|
||||
# Checked again with the delete, so a packaging job added or a worker claim made meanwhile
|
||||
# isn't lost: packaging jobs would cascade, and a running job is writing new outputs.
|
||||
with transaction.atomic():
|
||||
deleted, _ = (
|
||||
TranscodeJob.objects
|
||||
.filter(pk=job.pk, packaging_jobs__isnull=True)
|
||||
.exclude(status=JobStatus.IN_PROGRESS)
|
||||
.delete()
|
||||
)
|
||||
if not deleted:
|
||||
messages.error(self.request, "The transcode job changed while it was being deleted; it was kept.")
|
||||
return detail
|
||||
|
||||
messages.success(self.request, f"Deleted transcode job {job.slug} and its outputs.")
|
||||
if job.content_asset_id:
|
||||
return redirect("studio:content_asset", bucket, job.content_asset_id)
|
||||
return redirect(reverse("studio:detail", args=[bucket]) + "?tab=content")
|
||||
|
||||
|
||||
class UploadedAssetDeleteView(StudioContextMixin, StudioMixin, DeleteView):
|
||||
"""Deletes an uploaded file from storage, then its record. Transcode jobs and content entries are kept."""
|
||||
model = UploadedAsset
|
||||
template_name = "privatestudio/uploaded_asset_confirm_delete.html"
|
||||
context_object_name = "asset"
|
||||
|
||||
def get_queryset(self):
|
||||
return UploadedAsset.objects.filter(studio=self.studio)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
content_assets=self.object.content_assets.order_by("title"),
|
||||
transcode_job_count=self.object.transcode_jobs.count(),
|
||||
blocker=self.object.delete_blocker(),
|
||||
cancel_url=self.back_url(),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def back_url(self):
|
||||
content = self.object.content_assets.order_by("pk").first()
|
||||
if content is not None:
|
||||
return reverse("studio:content_asset", args=[self.studio.bucket_name, content.pk])
|
||||
return reverse("studio:detail", args=[self.studio.bucket_name]) + "?tab=files"
|
||||
|
||||
def form_valid(self, form):
|
||||
asset = self.object
|
||||
back = self.back_url()
|
||||
blocker = asset.delete_blocker()
|
||||
if blocker:
|
||||
messages.error(self.request, blocker)
|
||||
return redirect(back)
|
||||
|
||||
storage = get_storage()
|
||||
bucket = self.studio.bucket_name
|
||||
try:
|
||||
storage.delete_object(bucket, asset.s3_path)
|
||||
except (InvalidKey, OSError) as e:
|
||||
logger.warning("Could not delete %s/%s: %s", bucket, asset.s3_path, e)
|
||||
try:
|
||||
still_there = storage.object_exists(bucket, asset.s3_path)
|
||||
except InvalidKey:
|
||||
still_there = False
|
||||
if still_there:
|
||||
messages.error(self.request, f"{asset.s3_path} could not be deleted, so its record was kept.")
|
||||
return redirect(back)
|
||||
|
||||
path = asset.s3_path
|
||||
asset.delete()
|
||||
messages.success(self.request, f"Deleted {path}.")
|
||||
return redirect(back)
|
||||
|
||||
|
||||
class PackagingJobCreateView(StudioMixin, View):
|
||||
"""Queues a new packaging job for a transcode job."""
|
||||
http_method_names = ["post"]
|
||||
|
||||
def post(self, request, bucket_name, pk):
|
||||
job = get_object_or_404(TranscodeJob, pk=pk, studio=self.studio)
|
||||
# Locked so two quick clicks can't both pass the check (IMMEDIATE on SQLite).
|
||||
with transaction.atomic():
|
||||
blocker = job.packaging_blocker()
|
||||
if blocker is None:
|
||||
packaging = PackagingJob.objects.create(
|
||||
slug=PackagingJob.get_random_slug(), studio=self.studio, requested_by=request.user,
|
||||
transcode_job=job,
|
||||
)
|
||||
if blocker is not None:
|
||||
messages.warning(request, blocker)
|
||||
return redirect("studio:transcode_job", self.studio.bucket_name, job.pk)
|
||||
messages.success(request, f"Queued packaging job {packaging.slug}.")
|
||||
return redirect("studio:packaging_job", self.studio.bucket_name, packaging.pk)
|
||||
|
||||
|
||||
class PackagingJobDetailView(StudioContextMixin, StudioMixin, DetailView):
|
||||
model = PackagingJob
|
||||
template_name = "privatestudio/packaging_job_detail.html"
|
||||
context_object_name = "packaging_job"
|
||||
|
||||
def get_queryset(self):
|
||||
return (
|
||||
PackagingJob.objects.filter(studio=self.studio)
|
||||
.select_related("transcode_job__content_asset", "transcode_job__profile", "requested_by")
|
||||
)
|
||||
|
||||
|
||||
class JobDownloadView(StudioMixin, View):
|
||||
"""
|
||||
Streams a completed job's output folder as a zip whose top folder is the job's slug,
|
||||
e.g. packages/<slug>/hls/master.m3u8 -> <slug>/hls/master.m3u8.
|
||||
"""
|
||||
http_method_names = ["get"]
|
||||
model = None
|
||||
detail_url_name = None
|
||||
folder_attr = None
|
||||
noun = None
|
||||
|
||||
def get(self, request, bucket_name, pk):
|
||||
job = get_object_or_404(self.model, pk=pk, studio=self.studio)
|
||||
bucket = self.studio.bucket_name
|
||||
if job.status != JobStatus.COMPLETED:
|
||||
messages.error(request, f"Only a completed {self.noun} can be downloaded.")
|
||||
return redirect(self.detail_url_name, bucket, job.pk)
|
||||
|
||||
storage = get_storage()
|
||||
folder = getattr(job, self.folder_attr)
|
||||
keys = storage.folder_objects(bucket, folder)
|
||||
if not keys:
|
||||
messages.error(request, f"This {self.noun} has no files to download.")
|
||||
return redirect(self.detail_url_name, bucket, job.pk)
|
||||
|
||||
prefix = folder + "/"
|
||||
entries = [(storage.object_path(bucket, key), f"{job.slug}/{key.removeprefix(prefix)}") for key in keys]
|
||||
return zip_response(request, entries, f"{job.slug}.zip")
|
||||
|
||||
|
||||
class PackagingJobDownloadView(JobDownloadView):
|
||||
model = PackagingJob
|
||||
detail_url_name = "studio:packaging_job"
|
||||
folder_attr = "package_path"
|
||||
noun = "package"
|
||||
|
||||
|
||||
class TranscodeJobDownloadView(JobDownloadView):
|
||||
model = TranscodeJob
|
||||
detail_url_name = "studio:transcode_job"
|
||||
folder_attr = "output_path"
|
||||
noun = "transcode job"
|
||||
|
||||
|
||||
class PackagingJobDeleteView(StudioContextMixin, StudioMixin, DeleteView):
|
||||
"""Deletes a package's files, then the job record once none are left."""
|
||||
model = PackagingJob
|
||||
template_name = "privatestudio/packaging_job_confirm_delete.html"
|
||||
context_object_name = "packaging_job"
|
||||
|
||||
def get_queryset(self):
|
||||
return PackagingJob.objects.filter(studio=self.studio).select_related("transcode_job")
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
storage = get_storage()
|
||||
files = storage.folder_objects(self.studio.bucket_name, self.object.package_path)
|
||||
return super().get_context_data(file_count=len(files), **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
job = self.object
|
||||
detail = redirect("studio:packaging_job", self.studio.bucket_name, job.pk)
|
||||
if not job.is_deletable:
|
||||
messages.error(self.request, "This packaging job is running and can't be deleted until it finishes.")
|
||||
return detail
|
||||
|
||||
storage = get_storage()
|
||||
bucket = self.studio.bucket_name
|
||||
storage.delete_folder(bucket, job.package_path)
|
||||
remaining = storage.folder_objects(bucket, job.package_path)
|
||||
if remaining:
|
||||
messages.error(
|
||||
self.request,
|
||||
f"{len(remaining)} file(s) in {job.package_path}/ could not be deleted, "
|
||||
"so the packaging job was kept. Try again, or check the storage permissions.",
|
||||
)
|
||||
return detail
|
||||
|
||||
transcode_job_pk = job.transcode_job_id
|
||||
job.delete()
|
||||
messages.success(self.request, f"Deleted packaging job {job.slug} and its files.")
|
||||
return redirect("studio:transcode_job", bucket, transcode_job_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,349 @@
|
||||
"""
|
||||
Runs transcode and packaging jobs. Started by ``manage.py run_worker``.
|
||||
|
||||
Jobs are claimed from the database with a conditional UPDATE, so several workers
|
||||
can poll the same tables. No transaction is held while ffmpeg or Bento4 runs: a
|
||||
job is claimed in one short transaction, and its result is written in another.
|
||||
While a job runs, a background thread updates ``heartbeat_at``; jobs whose
|
||||
heartbeat stops (the worker crashed or was killed) are marked failed.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import connections, transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from privatestudio import transcode as transcoder
|
||||
from privatestudio.studio.models import JobStatus, PackagingJob, TranscodedAsset, TranscodeJob
|
||||
from privatestudio.studio.profiles import validate_profile_definition
|
||||
from privatestudio.studio.storage import get_storage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
HEARTBEAT_SECONDS = 10
|
||||
# ffmpeg rewrites its progress line constantly. Only the last one is kept in the job log.
|
||||
PROGRESS_PREFIXES = ("frame=", "size=")
|
||||
|
||||
|
||||
class JobError(Exception):
|
||||
"""A job failed for a reason worth showing to the user."""
|
||||
|
||||
|
||||
def worker_id() -> str:
|
||||
return f"{socket.gethostname()}:{os.getpid()}"
|
||||
|
||||
|
||||
# Claiming
|
||||
|
||||
def _claim(queryset):
|
||||
"""Move the oldest job in ``queryset`` to in progress. Returns it, or None."""
|
||||
model = queryset.model
|
||||
with transaction.atomic():
|
||||
job = queryset.order_by("requested_at", "pk").select_for_update(skip_locked=True).first()
|
||||
if job is None:
|
||||
return None
|
||||
now = timezone.now()
|
||||
# Conditional, so two workers racing for the same job can't both get it.
|
||||
claimed = model.objects.filter(pk=job.pk, status=JobStatus.PENDING).update(
|
||||
status=JobStatus.IN_PROGRESS, started_at=now, heartbeat_at=now, worker=worker_id(),
|
||||
)
|
||||
if not claimed:
|
||||
return None
|
||||
job.refresh_from_db()
|
||||
return job
|
||||
|
||||
|
||||
def claim_transcode_job():
|
||||
return _claim(TranscodeJob.objects.filter(status=JobStatus.PENDING))
|
||||
|
||||
|
||||
def claim_packaging_job():
|
||||
"""Claim a pending packaging job whose transcode job has completed."""
|
||||
return _claim(PackagingJob.objects.filter(
|
||||
status=JobStatus.PENDING, transcode_job__status=JobStatus.COMPLETED,
|
||||
))
|
||||
|
||||
|
||||
def fail_orphaned_packaging_jobs() -> int:
|
||||
"""Fail pending packaging jobs whose transcode job failed. Returns how many."""
|
||||
return PackagingJob.objects.filter(
|
||||
status=JobStatus.PENDING, transcode_job__status=JobStatus.FAILED,
|
||||
).update(status=JobStatus.FAILED, completed_at=timezone.now(), output="The transcode job failed.")
|
||||
|
||||
|
||||
def recover_stale_jobs() -> int:
|
||||
"""Fail in-progress jobs whose worker stopped sending heartbeats. Returns how many."""
|
||||
cutoff = timezone.now() - timedelta(seconds=settings.PRIVATESTUDIO_WORKER_STALE_SECONDS)
|
||||
message = "\n\nThe worker stopped responding while running this job."
|
||||
count = 0
|
||||
for model, log_field in ((TranscodeJob, "transcode_output"), (PackagingJob, "output")):
|
||||
for job in model.objects.filter(status=JobStatus.IN_PROGRESS, heartbeat_at__lt=cutoff):
|
||||
count += model.objects.filter(pk=job.pk, status=JobStatus.IN_PROGRESS, heartbeat_at__lt=cutoff).update(
|
||||
status=JobStatus.FAILED, completed_at=timezone.now(),
|
||||
**{log_field: getattr(job, log_field) + message},
|
||||
)
|
||||
if count:
|
||||
logger.warning("Marked %d stale job(s) as failed", count)
|
||||
return count
|
||||
|
||||
|
||||
# Running
|
||||
|
||||
class Heartbeat:
|
||||
"""Context manager that updates a job's heartbeat_at from a background thread."""
|
||||
|
||||
def __init__(self, job, interval=None):
|
||||
self.model = type(job)
|
||||
self.pk = job.pk
|
||||
self.interval = interval if interval is not None else HEARTBEAT_SECONDS
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._run, name=f"heartbeat-{self.pk}", daemon=True)
|
||||
|
||||
def _run(self):
|
||||
try:
|
||||
while not self._stop.wait(self.interval):
|
||||
try:
|
||||
self.model.objects.filter(pk=self.pk, status=JobStatus.IN_PROGRESS).update(
|
||||
heartbeat_at=timezone.now(),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Heartbeat update failed for %s %s", self.model.__name__, self.pk)
|
||||
finally:
|
||||
connections.close_all()
|
||||
|
||||
def __enter__(self):
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self._stop.set()
|
||||
self._thread.join()
|
||||
|
||||
|
||||
class JobLog:
|
||||
"""Collects tool output for the job record, keeping only ffmpeg's last progress line."""
|
||||
|
||||
def __init__(self):
|
||||
self.lines = []
|
||||
self.progress = None
|
||||
|
||||
def __call__(self, line):
|
||||
if line.startswith(PROGRESS_PREFIXES):
|
||||
self.progress = line
|
||||
return
|
||||
if self.progress is not None:
|
||||
self.lines.append(self.progress)
|
||||
self.progress = None
|
||||
self.lines.append(line if line.endswith("\n") else line + "\n")
|
||||
|
||||
def text(self):
|
||||
return "".join(self.lines + ([self.progress] if self.progress else []))
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self):
|
||||
self.stopping = False
|
||||
self._process = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# Process control, so a shutdown can stop the running tool.
|
||||
|
||||
def _started(self, process):
|
||||
with self._lock:
|
||||
self._process = process
|
||||
if self.stopping:
|
||||
process.terminate()
|
||||
|
||||
def stop(self):
|
||||
"""Ask the worker to stop. A running job is interrupted and put back in the queue."""
|
||||
with self._lock:
|
||||
self.stopping = True
|
||||
if self._process is not None and self._process.poll() is None:
|
||||
self._process.terminate()
|
||||
|
||||
def _run_tool(self, command, log):
|
||||
"""Run a command, logging its output. Raises JobError if it fails."""
|
||||
log(f"$ {' '.join(str(c) for c in command)}")
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
[str(c) for c in command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
|
||||
)
|
||||
except OSError as e:
|
||||
raise JobError(f"Could not run {command[0]}: {e}") from e
|
||||
self._started(process)
|
||||
for line in process.stdout:
|
||||
log(line)
|
||||
if process.wait() != 0:
|
||||
raise JobError(f"{Path(str(command[0])).name} exited with code {process.returncode}")
|
||||
|
||||
# Job lifecycle
|
||||
|
||||
def run_once(self) -> bool:
|
||||
"""Run one available job. Returns False if there was nothing to do."""
|
||||
fail_orphaned_packaging_jobs()
|
||||
job = claim_transcode_job()
|
||||
if job is not None:
|
||||
self.run_transcode_job(job)
|
||||
return True
|
||||
job = claim_packaging_job()
|
||||
if job is not None:
|
||||
self.run_packaging_job(job)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _finish(self, job, status, **fields):
|
||||
"""Record a job's result, unless it was taken from this worker (marked stale)."""
|
||||
updated = type(job).objects.filter(pk=job.pk, status=JobStatus.IN_PROGRESS, worker=job.worker).update(
|
||||
status=status, completed_at=timezone.now() if status != JobStatus.PENDING else None, **fields,
|
||||
)
|
||||
if not updated:
|
||||
logger.warning("%s was no longer assigned to this worker; result discarded", job)
|
||||
return bool(updated)
|
||||
|
||||
def _requeue(self, job):
|
||||
"""Put an interrupted job back in the queue."""
|
||||
type(job).objects.filter(pk=job.pk, status=JobStatus.IN_PROGRESS, worker=job.worker).update(
|
||||
status=JobStatus.PENDING, started_at=None, heartbeat_at=None, worker="",
|
||||
)
|
||||
logger.info("%s interrupted by shutdown; returned to the queue", job)
|
||||
|
||||
def _work_dir(self, storage) -> Path:
|
||||
path = storage.work_path / uuid.uuid4().hex
|
||||
path.mkdir(parents=True)
|
||||
return path
|
||||
|
||||
def run_transcode_job(self, job: TranscodeJob):
|
||||
logger.info("Starting %s", job)
|
||||
storage = get_storage()
|
||||
bucket = job.studio.bucket_name
|
||||
log = JobLog()
|
||||
work_dir = self._work_dir(storage)
|
||||
try:
|
||||
with Heartbeat(job):
|
||||
try:
|
||||
published = self._transcode(job, storage, bucket, work_dir, log)
|
||||
except JobError as e:
|
||||
if self.stopping:
|
||||
return self._requeue(job)
|
||||
log(f"\nError: {e}")
|
||||
self._finish(job, JobStatus.FAILED, transcode_output=log.text())
|
||||
logger.warning("%s failed: %s", job, e)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.exception("%s failed", job)
|
||||
log(f"\nInternal error: {e}")
|
||||
self._finish(job, JobStatus.FAILED, transcode_output=log.text())
|
||||
return
|
||||
with transaction.atomic():
|
||||
if self._finish(job, JobStatus.COMPLETED, transcode_output=log.text()):
|
||||
TranscodedAsset.objects.bulk_create([
|
||||
TranscodedAsset(
|
||||
studio_id=job.studio_id, content_asset_id=job.content_asset_id, transcode_job=job,
|
||||
filename=name, s3_path=key, format="audio" if name == "output_audio.mp4" else "mp4",
|
||||
)
|
||||
for name, key in published
|
||||
])
|
||||
logger.info("Completed %s", job)
|
||||
finally:
|
||||
shutil.rmtree(work_dir, ignore_errors=True)
|
||||
|
||||
def _transcode(self, job, storage, bucket, work_dir, log):
|
||||
"""Run ffmpeg and publish its outputs. Returns [(filename, key)]."""
|
||||
try:
|
||||
profile_config = validate_profile_definition(job.profile_definition)
|
||||
except ValidationError as e:
|
||||
raise JobError("Invalid profile definition: " + " ".join(e.messages)) from e
|
||||
if job.asset is None:
|
||||
raise JobError("The source file was deleted.")
|
||||
input_path = storage.object_path(bucket, job.asset.s3_path)
|
||||
if not input_path.is_file():
|
||||
raise JobError(f"Source file is missing: {job.asset.s3_path}")
|
||||
|
||||
output_dir = work_dir / "output"
|
||||
try:
|
||||
result = transcoder.transcode(
|
||||
input_path, profile_config, output_dir, on_line=log, on_start=self._started, log=log,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise JobError(str(e)) from e
|
||||
except OSError as e:
|
||||
raise JobError(f"Could not run ffmpeg: {e}") from e
|
||||
if result.return_code != 0:
|
||||
raise JobError(f"ffmpeg exited with code {result.return_code}")
|
||||
|
||||
published = []
|
||||
for name in result.files:
|
||||
path = output_dir / name
|
||||
if not path.is_file():
|
||||
raise JobError(f"ffmpeg did not produce {name}")
|
||||
key = f"{job.output_path}/{name}"
|
||||
storage.publish_file(path, bucket, key)
|
||||
published.append((name, key))
|
||||
return published
|
||||
|
||||
def run_packaging_job(self, job: PackagingJob):
|
||||
logger.info("Starting %s", job)
|
||||
storage = get_storage()
|
||||
bucket = job.studio.bucket_name
|
||||
log = JobLog()
|
||||
work_dir = self._work_dir(storage)
|
||||
try:
|
||||
with Heartbeat(job):
|
||||
try:
|
||||
manifest_key = self._package(job, storage, bucket, work_dir, log)
|
||||
except JobError as e:
|
||||
if self.stopping:
|
||||
return self._requeue(job)
|
||||
log(f"\nError: {e}")
|
||||
self._finish(job, JobStatus.FAILED, output=log.text())
|
||||
logger.warning("%s failed: %s", job, e)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.exception("%s failed", job)
|
||||
log(f"\nInternal error: {e}")
|
||||
self._finish(job, JobStatus.FAILED, output=log.text())
|
||||
return
|
||||
self._finish(job, JobStatus.COMPLETED, output=log.text(), manifest_path=manifest_key)
|
||||
logger.info("Completed %s", job)
|
||||
finally:
|
||||
shutil.rmtree(work_dir, ignore_errors=True)
|
||||
|
||||
@staticmethod
|
||||
def _bento4(tool):
|
||||
directory = settings.PRIVATESTUDIO_BENTO4_BIN
|
||||
return str(Path(directory) / tool) if directory else tool
|
||||
|
||||
def _package(self, job, storage, bucket, work_dir, log):
|
||||
"""Fragment the transcoded files, package them as HLS and publish. Returns the master playlist key."""
|
||||
sources = list(job.transcode_job.transcoded_assets.order_by("pk"))
|
||||
if not sources:
|
||||
raise JobError("The transcode job has no output files.")
|
||||
|
||||
fragmented = []
|
||||
for source in sources:
|
||||
path = storage.object_path(bucket, source.s3_path)
|
||||
if not path.is_file():
|
||||
raise JobError(f"Transcoded file is missing: {source.s3_path}")
|
||||
target = work_dir / f"frag_{source.pk}_{Path(source.filename).name}"
|
||||
self._run_tool([self._bento4("mp4fragment"), path, target], log)
|
||||
fragmented.append(target)
|
||||
|
||||
hls_dir = work_dir / "hls"
|
||||
self._run_tool([self._bento4("mp4hls"), "--output-dir", hls_dir, *fragmented], log)
|
||||
|
||||
master = hls_dir / "master.m3u8"
|
||||
if not master.is_file():
|
||||
raise JobError("mp4hls did not produce master.m3u8")
|
||||
prefix = f"{job.package_path}/hls"
|
||||
for path in sorted(p for p in hls_dir.rglob("*") if p.is_file()):
|
||||
storage.publish_file(path, bucket, f"{prefix}/{path.relative_to(hls_dir).as_posix()}")
|
||||
return f"{prefix}/master.m3u8"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user