9 Commits
Author SHA1 Message Date
Shaun Kruger 23218b15f5 Replace readme
Build and publish / cleanup (pull_request) Successful in 1m4s
Build and publish / test (pull_request) Skipped
Build and publish / build (pull_request) Skipped
Build and publish / pypi (pull_request) Skipped
2026-12-03 09:48:36 -07:00
Shaun KrugerandClaude Opus 5.5 5d7d03a0a6 Use setup-uv instead of setup-python in CI
Build and publish / test (pull_request) Successful in 36s
Build and publish / cleanup (pull_request) Skipped
Build and publish / build (pull_request) Successful in 3m32s
Build and publish / pypi (pull_request) Skipped
actions/setup-python only ships binaries for Ubuntu releases, so it fails
on the Debian-based Gitea act_runner image. setup-uv installs portable
Python builds that work on any glibc Linux.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:11:03 -07:00
Shaun KrugerandClaude Opus 5.5 38f3a0da2f Add Docker image, Gitea CI, PyPI publishing and BSD-3-Clause license
Build and publish / test (pull_request) Failing after 40s
Build and publish / cleanup (pull_request) Skipped
Build and publish / build (pull_request) Skipped
Build and publish / pypi (pull_request) Skipped
- Dockerfile builds the npm bundle and serves the app with gunicorn
- Gitea workflow runs tests, tags releases on main, pushes the image to
  the Gitea registry, and publishes to PyPI when PYPI_TOKEN is set
- MANIFEST.in includes the built static bundle in distributions
- License the project under BSD-3-Clause

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:42:20 -07:00
skruger ba76671795 Merge pull request 'Add content assets for cataloging uploaded files' (#3) from asset_catalog into main
Reviewed-on: #3
2026-12-01 21:11:53 -07:00
Shaun Kruger 7231f69014 Fix italics in html editor 2026-12-01 21:00:59 -07:00
Shaun Kruger e582cb9234 Add icon config 2026-12-01 20:58:47 -07:00
Shaun KrugerandClaude Opus 5.5 5bb9a70c11 Add sanitized rich-text descriptions for content assets
Introduce HtmlTextField, which cleans submitted HTML with nh3 against a
tag/attribute allowlist, and use it for ContentAsset.description via
Meta.field_classes. Edit descriptions with TinyMCE and render the
sanitized HTML on the asset page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:57:31 -07:00
Shaun KrugerandClaude Opus 5.5 3fe49b47ea Add content assets for cataloging uploaded files
ContentAsset records metadata (kind, title, description, release date,
season/episode/sequence) for an UploadedAsset, scoped to a studio.
ContentGroup groups episodes into a series or movies into a collection.

The studio page now has tabs for uploaded files and content, both loaded
with htmx. Files without content get a "Create content" button. Content
opens read-only with an Edit button; the form shows immediately when a
save fails validation.

Also adds the draft job status to the migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:22:27 -07:00
skruger d73dddc3d9 Merge pull request 'Convert web service from FastAPI to Django 6.1' (#2) from django into main
Reviewed-on: #2
2026-12-01 17:30:32 -07:00
30 changed files with 1145 additions and 17 deletions
+21
View File
@@ -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/
+215
View File
@@ -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."
+1 -1
View File
@@ -13,5 +13,5 @@ __pycache__/
db.sqlite3
privatestudio/settings/local.py
static/
privatestudio/static/bundle/
node_modules/
+50
View File
@@ -0,0 +1,50 @@
FROM node:24 AS nodebuild
WORKDIR /build
COPY package.json package-lock.json ./
RUN npm ci
COPY webpack.config.js ./
COPY src ./src
COPY privatestudio ./privatestudio
RUN mkdir -p privatestudio/static/bundle && npm run build
FROM python:3.13-slim-trixie
# Version used by setuptools_scm, since .git is not copied into the image.
ARG VERSION=0.0.0
RUN useradd --create-home privatestudio
EXPOSE 8000
ENV PYTHONUNBUFFERED=1 \
PORT=8000 \
DJANGO_SETTINGS_MODULE=privatestudio.settings.production \
STORAGE_PATH=/data/storage
RUN pip install --no-cache-dir "gunicorn~=23.0" "psycopg2-binary~=2.9.11"
WORKDIR /app
COPY --chown=privatestudio:privatestudio . .
COPY --from=nodebuild --chown=privatestudio:privatestudio /build/privatestudio/static/bundle ./privatestudio/static/bundle
RUN SETUPTOOLS_SCM_PRETEND_VERSION="${VERSION}" pip install --no-cache-dir . \
&& mkdir -p /data/storage && chown -R privatestudio:privatestudio /data /app
USER privatestudio
RUN python manage.py collectstatic --noinput --clear
VOLUME ["/data"]
# Migrating at startup keeps "docker run" simple. Use a release step instead if
# you run more than one container against the same database.
CMD set -xe; \
python manage.py migrate --noinput; \
exec gunicorn privatestudio.wsgi:application \
--bind 0.0.0.0:${PORT} \
-k gthread --workers 2 --threads 8 --timeout 600
+28
View File
@@ -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.
+3
View File
@@ -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 -1
View File
@@ -14,7 +14,7 @@
"build:digitalocean": "npm install --production=false && npm run build"
},
"author": "Shaun Kruger",
"license": "ISC",
"license": "BSD-3-Clause",
"private": true,
"engines": {
"node": "v24.22.x",
+44
View File
@@ -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
+7
View File
@@ -14,6 +14,13 @@ if os.environ.get("DATABASE_URL"):
DATABASES = {
"default": dj_database_url.config(),
}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join("/data", "db.sqlite3"),
}
}
CORS_ALLOWED_ORIGINS = [o for o in os.environ.get("CORS_ALLOWED_ORIGINS", "").split(",") if o]
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

+35
View File
@@ -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

+14
View File
@@ -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'
]
})
});
+15
View File
@@ -87,3 +87,18 @@ class PackagingJobAdmin(admin.ModelAdmin):
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",)
+27
View File
@@ -0,0 +1,27 @@
from django import forms
from privatestudio.studio.models import ContentAsset
from privatestudio.fields import HtmlTextField
class ContentAssetForm(forms.ModelForm):
class Meta:
model = ContentAsset
fields = [
"kind", "title", "description", "release_date",
"group", "season_number", "episode_number", "sequence_number",
]
widgets = {
"release_date": forms.DateInput(attrs={"type": "date"}, format="%Y-%m-%d"),
"description": forms.Textarea(attrs={"rows": 4}),
}
field_classes = {
"description": HtmlTextField,
}
def __init__(self, *args, studio, **kwargs):
super().__init__(*args, **kwargs)
self.fields["group"].queryset = studio.content_groups.all()
for field in self.fields.values():
css = "form-select" if isinstance(field.widget, forms.Select) else "form-control"
field.widget.attrs["class"] = css
@@ -0,0 +1,72 @@
# Generated by Django 6.1.3 on 2026-12-02 01:06
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studio', '0002_multipart_uploads'),
]
operations = [
migrations.AlterField(
model_name='packagingjob',
name='status',
field=models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20),
),
migrations.AlterField(
model_name='transcodejob',
name='status',
field=models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20),
),
migrations.CreateModel(
name='ContentGroup',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('kind', models.CharField(choices=[('series', 'Series'), ('collection', 'Movie collection')], max_length=20)),
('title', models.CharField(max_length=255)),
('description', models.TextField(blank=True)),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='content_groups', to='studio.studio')),
],
options={
'ordering': ['title'],
},
),
migrations.CreateModel(
name='ContentAsset',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('kind', models.CharField(choices=[('video', 'Video'), ('episode', 'Episode'), ('movie', 'Movie')], default='video', max_length=20)),
('title', models.CharField(max_length=255)),
('description', models.TextField(blank=True)),
('release_date', models.DateField(blank=True, null=True)),
('season_number', models.PositiveIntegerField(blank=True, null=True)),
('episode_number', models.PositiveIntegerField(blank=True, null=True)),
('sequence_number', models.PositiveIntegerField(blank=True, help_text='Order of a movie within its collection.', null=True)),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('updated_at', models.DateTimeField(auto_now=True)),
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='content_assets', to='studio.studio')),
('uploaded_asset', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, related_name='content_assets', to='studio.uploadedasset', null=True, blank=True)),
('group', models.ForeignKey(blank=True, help_text='The series an episode belongs to, or the collection a movie belongs to.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='content_assets', to='studio.contentgroup')),
],
options={
'ordering': ['group__title', 'season_number', 'episode_number', 'sequence_number', 'title'],
},
),
migrations.AddConstraint(
model_name='contentgroup',
constraint=models.UniqueConstraint(fields=('studio', 'kind', 'title'), name='unique_content_group_per_studio'),
),
migrations.AddIndex(
model_name='contentasset',
index=models.Index(fields=['kind'], name='studio_cont_kind_c87ed2_idx'),
),
migrations.AddIndex(
model_name='contentasset',
index=models.Index(fields=['release_date'], name='studio_cont_release_cc6f45_idx'),
),
]
+86
View File
@@ -3,11 +3,13 @@ import uuid
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
class JobStatus(models.TextChoices):
DRAFT = "draft", "Draft"
PENDING = "pending", "Pending"
IN_PROGRESS = "in_progress", "In progress"
COMPLETED = "completed", "Completed"
@@ -204,3 +206,87 @@ class TranscodedAsset(models.Model):
def __str__(self):
return f"{self.studio.bucket_name}/{self.s3_path}"
class ContentKind(models.TextChoices):
VIDEO = "video", "Video"
EPISODE = "episode", "Episode"
MOVIE = "movie", "Movie"
class ContentGroupKind(models.TextChoices):
SERIES = "series", "Series"
COLLECTION = "collection", "Movie collection"
class ContentGroup(models.Model):
"""A series of episodes or a collection of related movies within a studio."""
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="content_groups")
kind = models.CharField(max_length=20, choices=ContentGroupKind.choices)
title = models.CharField(max_length=255)
description = models.TextField(blank=True)
created_at = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ["title"]
constraints = [
models.UniqueConstraint(fields=["studio", "kind", "title"], name="unique_content_group_per_studio"),
]
def __str__(self):
return f"{self.title} ({self.get_kind_display()})"
class ContentAsset(models.Model):
"""Catalog metadata for an uploaded file."""
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="content_assets")
uploaded_asset = models.ForeignKey(UploadedAsset, on_delete=models.SET_NULL, related_name="content_assets", null=True, blank=True)
kind = models.CharField(max_length=20, choices=ContentKind.choices, default=ContentKind.VIDEO)
title = models.CharField(max_length=255)
description = models.TextField(blank=True)
release_date = models.DateField(null=True, blank=True)
group = models.ForeignKey(
ContentGroup, on_delete=models.SET_NULL, null=True, blank=True, related_name="content_assets",
help_text="The series an episode belongs to, or the collection a movie belongs to.",
)
season_number = models.PositiveIntegerField(null=True, blank=True)
episode_number = models.PositiveIntegerField(null=True, blank=True)
sequence_number = models.PositiveIntegerField(
null=True, blank=True, help_text="Order of a movie within its collection.",
)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["group__title", "season_number", "episode_number", "sequence_number", "title"]
indexes = [
models.Index(fields=["kind"]),
models.Index(fields=["release_date"]),
]
def __str__(self):
return self.title
def clean(self):
errors = {}
group = self.group
if self.studio_id and self.uploaded_asset_id and self.uploaded_asset.studio_id != self.studio_id:
errors["uploaded_asset"] = "The file must belong to the same studio."
if group is not None and self.studio_id and group.studio_id != self.studio_id:
errors["group"] = "The group must belong to the same studio."
if self.kind == ContentKind.EPISODE:
if group is None or group.kind != ContentGroupKind.SERIES:
errors.setdefault("group", "An episode must belong to a series.")
else:
for field in ("season_number", "episode_number"):
if getattr(self, field) is not None:
errors[field] = "Only episodes have season and episode numbers."
if group is not None:
if self.kind != ContentKind.MOVIE:
errors.setdefault("group", "Only episodes and movies can belong to a group.")
elif group.kind != ContentGroupKind.COLLECTION:
errors.setdefault("group", "A movie can only belong to a movie collection.")
if self.sequence_number is not None and (self.kind != ContentKind.MOVIE or group is None):
errors["sequence_number"] = "Only movies in a collection have a sequence number."
if errors:
raise ValidationError(errors)
+3
View File
@@ -14,6 +14,9 @@
{# <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 %}
@@ -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,77 @@
{% extends "privatestudio/base.html" %}
{% block content %}
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{% url 'studio:detail' studio.bucket_name %}?tab=content">{{ studio.name }}</a></li>
<li class="breadcrumb-item active" aria-current="page">{{ content_asset.title }}</li>
</ol>
</nav>
<h1>{{ content_asset.title }}</h1>
<dl class="row">
<dt class="col-sm-3">File</dt>
<dd class="col-sm-9">{{ content_asset.uploaded_asset.s3_path }}</dd>
<dt class="col-sm-3">Size (bytes)</dt>
<dd class="col-sm-9">{{ content_asset.uploaded_asset.size }}</dd>
<dt class="col-sm-3">Uploaded</dt>
<dd class="col-sm-9">{{ content_asset.uploaded_asset.upload_timestamp }}</dd>
<dt class="col-sm-3">Last updated</dt>
<dd class="col-sm-9">{{ content_asset.updated_at }}</dd>
</dl>
{% with editing=form.errors %}
{% if not editing %}
<div id="content-details" class="collapse show content-edit-toggle">
<dl class="row">
<dt class="col-sm-3">Kind</dt>
<dd class="col-sm-9">{{ content_asset.get_kind_display }}</dd>
<dt class="col-sm-3">Title</dt>
<dd class="col-sm-9">{{ content_asset.title }}</dd>
<dt class="col-sm-3">Description</dt>
<dd class="col-sm-9">{{ content_asset.description|default:"—"|safe }}</dd>
<dt class="col-sm-3">Release date</dt>
<dd class="col-sm-9">{{ content_asset.release_date|default:"—" }}</dd>
<dt class="col-sm-3">Series / Collection</dt>
<dd class="col-sm-9">{{ content_asset.group|default:"—" }}</dd>
{% if content_asset.season_number is not None or content_asset.episode_number is not None %}
<dt class="col-sm-3">Season</dt>
<dd class="col-sm-9">{{ content_asset.season_number|default:"—" }}</dd>
<dt class="col-sm-3">Episode</dt>
<dd class="col-sm-9">{{ content_asset.episode_number|default:"—" }}</dd>
{% endif %}
{% if content_asset.sequence_number is not None %}
<dt class="col-sm-3">Sequence</dt>
<dd class="col-sm-9">{{ content_asset.sequence_number }}</dd>
{% endif %}
</dl>
<button type="button" class="btn btn-primary" data-bs-toggle="collapse" data-bs-target=".content-edit-toggle" aria-controls="content-details content-form">Edit</button>
<a href="{% url 'studio:detail' studio.bucket_name %}?tab=content" class="btn btn-link">Back to content</a>
</div>
{% endif %}
<form id="content-form" method="post" novalidate{% if not editing %} class="collapse content-edit-toggle"{% endif %}>
{% csrf_token %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% for field in form %}
<div class="mb-3">
<label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}</label>
{{ field }}
{% if field.help_text %}<div class="form-text">{{ field.help_text }}</div>{% endif %}
{% for error in field.errors %}<div class="invalid-feedback d-block">{{ error }}</div>{% endfor %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Save</button>
{% if editing %}
<a href="{{ request.path }}" class="btn btn-secondary">Cancel</a>
{% else %}
<button type="button" class="btn btn-secondary" data-bs-toggle="collapse" data-bs-target=".content-edit-toggle" aria-controls="content-details content-form">Cancel</button>
{% endif %}
</form>
{% endwith %}
{% include 'includes/_tinymce.html' with selector="textarea#id_description" %}
{% endblock %}
@@ -0,0 +1,30 @@
<table class="table table-striped table-sm align-middle">
<tr>
<th>Title</th>
<th>Kind</th>
<th>Series / Collection</th>
<th>Position</th>
<th>Release Date</th>
<th>File</th>
</tr>
{% for content in content_assets %}
<tr>
<td><a href="{% url 'studio:content_asset' studio.bucket_name content.pk %}">{{ content.title }}</a></td>
<td>{{ content.get_kind_display }}</td>
<td>{{ content.group.title|default:"" }}</td>
<td>
{% if content.season_number or content.episode_number %}
{% if content.season_number %}S{{ content.season_number }}{% endif %}{% if content.episode_number %}E{{ content.episode_number }}{% endif %}
{% elif content.sequence_number %}
#{{ content.sequence_number }}
{% endif %}
</td>
<td>{{ content.release_date|default:"" }}</td>
<td>{{ content.uploaded_asset.s3_path }}</td>
</tr>
{% empty %}
<tr>
<td colspan="6">No content yet. Use "Create content" on an uploaded file.</td>
</tr>
{% endfor %}
</table>
@@ -1,21 +1,32 @@
<table class="table table-striped table-sm">
<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="3">Click to refresh</td>
<td colspan="4">Click to refresh</td>
</tr>
{% empty %}
<tr>
<td colspan="3">No uploaded assets found.</td>
<td colspan="4">No uploaded assets found.</td>
</tr>
{% endfor %}
</table>
</table>
@@ -1,4 +1,4 @@
<nav class="studio-navbar navbar navbar-expand-lg navbar-dark bg-dark navbar-fixed-top justify-content-between">
<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">
@@ -5,10 +5,30 @@
<p>Bucket Name: {{ studio.bucket_name }}</p>
<p>Group: {{ studio.group.name }}</p>
<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>
{% with content_tab=request.GET.tab %}
<ul class="nav nav-tabs mb-3" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link{% if content_tab != 'content' %} active{% endif %}" id="files-tab" data-bs-toggle="tab" data-bs-target="#files-pane" type="button" role="tab" aria-controls="files-pane" aria-selected="{% if content_tab != 'content' %}true{% else %}false{% endif %}">Uploaded files</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link{% if content_tab == 'content' %} active{% endif %}" id="content-tab" data-bs-toggle="tab" data-bs-target="#content-pane" type="button" role="tab" aria-controls="content-pane" aria-selected="{% if content_tab == 'content' %}true{% else %}false{% endif %}">Content</button>
</li>
</ul>
{% include "privatestudio/_file_uploader.html" %}
<div class="tab-content">
<div class="tab-pane fade{% if content_tab != 'content' %} show active{% endif %}" id="files-pane" role="tabpanel" aria-labelledby="files-tab" tabindex="0">
<div id="uploaded_assets" hx-get="{% url 'studio:uploaded_assets' studio.bucket_name %}" hx-trigger="load, assets-changed from:body" hx-target="#uploaded_assets" hx-swap="innerHTML">
<p>Loading uploaded assets...</p>
</div>
{% include "privatestudio/_file_uploader.html" %}
</div>
<div class="tab-pane fade{% if content_tab == 'content' %} show active{% endif %}" id="content-pane" role="tabpanel" aria-labelledby="content-tab" tabindex="0">
<div id="content_assets" hx-get="{% url 'studio:content_assets' studio.bucket_name %}" hx-trigger="load, assets-changed from:body" hx-target="#content_assets" hx-swap="innerHTML">
<p>Loading content...</p>
</div>
</div>
</div>
{% endwith %}
{% endblock %}
+64
View File
@@ -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)
+191
View File
@@ -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"')
+4
View File
@@ -10,6 +10,10 @@ studio_patterns = [
path("", views.StudioListView.as_view(), name="list"),
path("<slug:bucket_name>/", views.StudioDetailView.as_view(), name="detail"),
path("<slug:bucket_name>/hx/uploaded_assets/", views.UploadedAssetsView.as_view(), name="uploaded_assets"),
path("<slug:bucket_name>/hx/content_assets/", views.ContentAssetsView.as_view(), name="content_assets"),
path("<slug:bucket_name>/content/create/<int:asset_id>/", views.ContentAssetCreateView.as_view(),
name="content_asset_create"),
path("<slug:bucket_name>/content/<int:pk>/", views.ContentAssetUpdateView.as_view(), name="content_asset"),
path("<slug:bucket_name>/uploads/", views.UploadCreateView.as_view(), name="upload_create"),
path("<slug:bucket_name>/uploads/<uuid:upload_id>/", views.UploadView.as_view(), name="upload"),
path("<slug:bucket_name>/uploads/<uuid:upload_id>/parts/<int:number>/", views.UploadPartView.as_view(),
+73 -4
View File
@@ -1,15 +1,20 @@
import errno
import json
import logging
import os
from django.contrib import messages
from django.db.models import OuterRef, Subquery
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.views import View
from django.views.generic import ListView, DetailView
from django.views.generic import ListView, DetailView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
from privatestudio.studio import uploads
from privatestudio.studio.models import MultipartUpload, Studio, UploadedAsset
from privatestudio.studio.forms import ContentAssetForm
from privatestudio.studio.models import ContentAsset, MultipartUpload, Studio, UploadedAsset
from privatestudio.studio.request_body import BodyError, read_small_body
from privatestudio.studio.storage import InvalidKey
from privatestudio.studio.uploads import UploadError
@@ -65,8 +70,72 @@ class UploadedAssetsView(StudioMixin, ListView):
context_object_name = "uploaded_assets"
def get_queryset(self):
# Filter uploaded assets based on the user's group memberships
return super().get_queryset().filter(studio=self.studio)
content_asset = ContentAsset.objects.filter(uploaded_asset=OuterRef("pk")).order_by("pk").values("pk")[:1]
return (
super().get_queryset()
.filter(studio=self.studio)
.annotate(content_asset_id=Subquery(content_asset))
.order_by("s3_path")
)
class ContentAssetsView(StudioMixin, ListView):
model = ContentAsset
template_name = "privatestudio/hx_content_assets.html"
context_object_name = "content_assets"
def get_queryset(self):
return (
super().get_queryset()
.filter(studio=self.studio)
.select_related("group", "uploaded_asset")
)
def get_context_data(self, **kwargs):
return super().get_context_data(studio=self.studio, **kwargs)
class ContentAssetCreateView(StudioMixin, View):
"""Create content metadata for an uploaded file, then open it for editing."""
http_method_names = ["post"]
def post(self, request, bucket_name, asset_id):
asset = get_object_or_404(UploadedAsset, pk=asset_id, studio=self.studio)
content = asset.content_assets.order_by("pk").first()
if content is None:
title = os.path.splitext(os.path.basename(asset.filename or asset.s3_path))[0]
content = ContentAsset.objects.create(
studio=self.studio, uploaded_asset=asset, title=title or asset.s3_path,
)
return redirect("studio:content_asset", self.studio.bucket_name, content.pk)
class ContentAssetUpdateView(StudioMixin, UpdateView):
model = ContentAsset
form_class = ContentAssetForm
template_name = "privatestudio/content_asset_form.html"
context_object_name = "content_asset"
def get_queryset(self):
return ContentAsset.objects.filter(studio=self.studio).select_related("uploaded_asset")
def get_form_kwargs(self):
return {**super().get_form_kwargs(), "studio": self.studio}
def get_context_data(self, **kwargs):
return super().get_context_data(studio=self.studio, **kwargs)
def form_valid(self, form):
messages.success(self.request, f"Saved {form.instance.title}.")
return super().form_valid(form)
def form_invalid(self, form):
# The form has already copied the invalid values onto self.object; show the saved ones outside the form.
self.object = self.get_object()
return super().form_invalid(form)
def get_success_url(self):
return reverse("studio:content_asset", args=[self.studio.bucket_name, self.object.pk])
class UploadApiView(StudioMixin, View):
+6 -2
View File
@@ -1,11 +1,13 @@
[build-system]
requires = ["setuptools>=68", "setuptools_scm[toml]>=8", "wheel"]
requires = ["setuptools>=77", "setuptools_scm[toml]>=8", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "privatestudio"
description = "Video transcoding tools with multi-profile H.264 encoding support"
readme = "notes.md"
readme = "README.md"
license = "BSD-3-Clause"
license-files = ["LICENSE"]
requires-python = ">=3.12"
dependencies = [
"PyYAML>=6.0",
@@ -16,6 +18,7 @@ dependencies = [
"whitenoise~=6.11.0",
"pytz~=2026.5",
"django-allauth[socialaccount]~=65.0.2",
"nh3==0.2.20",
]
dynamic = ["version"]
@@ -25,6 +28,7 @@ dev = [
"pytest-cov>=4.0",
"pytest-django>=4.14",
"boto3",
"build",
]
[project.scripts]
+22
View File
@@ -6,6 +6,20 @@ $h4-font-size: $font-size-base * 1.25 !default;
$h5-font-size: $font-size-base * 1.15 !default;
$h6-font-size: $font-size-base !default;
$white: #ffffff;
$theme-colors: (
"light": #fdc8b2,
"dark": #e4440f,
"primary": #18499b,
"secondary": #a65d66,
"info": #da9a37,
"success": #17a762,
"warning": #e3cc17,
"danger": #f31b0a,
);
@import "bootstrap/scss/bootstrap";
form.simpleform input[type=text], form.simpleform textarea {
@@ -16,3 +30,11 @@ form.simpleform label {
font-weight: bold;
font-size: 1.2em;
}
div.tox-tinymce div.tox-promotion {
display: none;
}
//span.tox-statusbar__branding {
// display: none;
//}