3 Commits
Author SHA1 Message Date
skruger 1e7483d9c6 Merge pull request 'Add web UI for transcode profiles and transcode/packaging jobs' (#5) from transcode_control into main
Build and publish / cleanup (push) Skipped
Build and publish / test (push) Successful in 41s
Build and publish / build (push) Successful in 3m35s
Build and publish / pypi (push) Successful in 1m7s
Reviewed-on: #5
2026-12-03 14:58:24 -07:00
Shaun KrugerandClaude Opus 5.5 de13523ffd Add web UI for transcode profiles and transcode/packaging jobs
Build and publish / test (pull_request) Skipped
Build and publish / build (pull_request) Skipped
Build and publish / pypi (pull_request) Skipped
Build and publish / cleanup (pull_request) Successful in 17s
- Profiles tab on the studio page with create/edit/delete forms. The YAML
  editor sits beside an example definition, and definitions are validated
  (structure, resolution, bitrate, fps, encoder) by a shared validator
  that the API now uses too. The create form can fill in the bundled
  default profile.
- "Transcode" button on content rows opens a job form (profile plus an
  editable YAML snapshot) with Save draft / Submit. Creating a job also
  creates its linked PackagingJob.
- Draft jobs can be edited; TranscodeJob.clean() rejects edits once a job
  leaves draft. Job detail page has Edit/Submit; packaging jobs have a
  detail page.
- Content asset page lists its transcode and packaging jobs above the form.
- Model: TranscodeJob.content_asset FK, default status draft,
  transcode_output field, TranscodedAsset.content_asset FK. API-created
  jobs start as pending.
- Move profiles/ into the package so default.yaml ships in the wheel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:52:41 -07:00
skruger b5fd00250b Merge pull request 'Add Docker image, Gitea CI, PyPI publishing and BSD-3-Clause license' (#4) from ci into main
Build and publish / build (push) Successful in 4m23s
Build and publish / pypi (push) Successful in 1m7s
Build and publish / test (push) Successful in 41s
Build and publish / cleanup (push) Skipped
Reviewed-on: #4
2026-12-03 09:54:40 -07:00
24 changed files with 1126 additions and 25 deletions
+81 -5
View File
@@ -1,10 +1,24 @@
from django import forms
from privatestudio.studio.models import ContentAsset
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 ContentAssetForm(forms.ModelForm):
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 = [
@@ -22,6 +36,68 @@ class ContentAssetForm(forms.ModelForm):
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
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,30 @@
# Generated by Django 6.1.3 on 2026-12-03 18:06
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studio', '0003_content_assets'),
]
operations = [
migrations.AddField(
model_name='transcodedasset',
name='content_asset',
field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.DO_NOTHING, related_name='transcoded_assets', to='studio.contentasset'),
preserve_default=False,
),
migrations.AddField(
model_name='transcodejob',
name='content_asset',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to='studio.contentasset'),
),
migrations.AlterField(
model_name='transcodejob',
name='status',
field=models.CharField(choices=[('draft', 'Draft'), ('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='draft', max_length=20),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 6.1.3 on 2026-12-03 21:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studio', '0004_transcode_ui'),
]
operations = [
migrations.AddField(
model_name='transcodejob',
name='transcode_output',
field=models.TextField(blank=True, default=''),
),
]
+32 -1
View File
@@ -167,18 +167,48 @@ class TranscodeJob(models.Model):
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
)
asset = models.ForeignKey(UploadedAsset, on_delete=models.CASCADE, related_name="transcode_jobs")
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.PENDING)
status = models.CharField(max_length=20, choices=JobStatus.choices, default=JobStatus.DRAFT)
requested_at = models.DateTimeField(default=timezone.now)
completed_at = models.DateTimeField(null=True, blank=True)
transcode_output = models.TextField(blank=True, default="")
def __str__(self):
return f"Transcode job {self.pk} ({self.status})"
@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)
class PackagingJob(models.Model):
"""Requested packaging operation."""
@@ -198,6 +228,7 @@ class PackagingJob(models.Model):
class TranscodedAsset(models.Model):
"""Output file from a transcode job."""
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcoded_assets")
content_asset = models.ForeignKey("ContentAsset", on_delete=models.DO_NOTHING, related_name="transcoded_assets")
transcode_job = models.ForeignKey(TranscodeJob, on_delete=models.CASCADE, related_name="transcoded_assets")
filename = models.TextField()
s3_path = models.TextField()
+83
View File
@@ -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
+11 -5
View File
@@ -1,10 +1,12 @@
"""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.routers.common import get_studio_for_user, parse_yaml_body
from privatestudio.studio.profiles import validate_profile_definition
from privatestudio.studio.routers.common import get_studio_for_user
router = Router()
@@ -33,9 +35,13 @@ def create_profile(request, bucket: str, name: str):
The request body must contain the YAML profile definition.
"""
studio = get_studio_for_user(request.auth, bucket)
profile_data = parse_yaml_body(request)
if "profiles" not in profile_data:
raise HttpError(400, "Profile definition must contain a 'profiles' section")
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")
@@ -44,7 +50,7 @@ def create_profile(request, bucket: str, name: str):
studio=studio,
created_by=request.auth,
name=name,
profile_definition=request.body.decode("utf-8"),
profile_definition=definition,
)
return _profile_response(profile)
+9 -3
View File
@@ -2,11 +2,13 @@
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 TranscodeJob, TranscodeProfile, UploadedAsset
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()
@@ -67,9 +69,11 @@ def request_transcode(request, bucket: str):
raise HttpError(404, f"Profile '{profile_ref}' not found")
profile_definition = profile.profile_definition
elif isinstance(profile_ref, dict):
if "profiles" not in profile_ref:
raise HttpError(400, "Inline profile must contain a 'profiles' section")
profile_definition = yaml.safe_dump(profile_ref)
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)")
@@ -79,6 +83,8 @@ def request_transcode(request, bucket: str):
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)
@@ -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>
@@ -10,6 +10,42 @@
<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>
<th>Packaging</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>
<td>
{% for packaging_job in job.packaging_jobs.all %}
<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 %}{% if not forloop.last %}<br>{% endif %}
{% empty %}—{% endfor %}
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p class="text-body-secondary">No transcode jobs yet.</p>
{% endif %}
</section>
<dl class="row">
<dt class="col-sm-3">File</dt>
<dd class="col-sm-9">{{ content_asset.uploaded_asset.s3_path }}</dd>
@@ -6,6 +6,7 @@
<th>Position</th>
<th>Release Date</th>
<th>File</th>
<th></th>
</tr>
{% for content in content_assets %}
<tr>
@@ -21,10 +22,15 @@
</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="6">No content yet. Use "Create content" on an uploaded file.</td>
<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,38 @@
{% 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">Completed</dt>
<dd class="col-sm-9">{{ packaging_job.completed_at|default:"—" }}</dd>
</dl>
{% endwith %}
{% endblock %}
@@ -5,29 +5,37 @@
<p>Bucket Name: {{ studio.bucket_name }}</p>
<p>Group: {{ studio.group.name }}</p>
{% with content_tab=request.GET.tab %}
{% with active=active_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>
<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 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>
<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 content_tab != 'content' %} show active{% endif %}" id="files-pane" role="tabpanel" aria-labelledby="files-tab" tabindex="0">
<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 content_tab == 'content' %} show active{% endif %}" id="content-pane" role="tabpanel" aria-labelledby="content-tab" tabindex="0">
<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 %}
@@ -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 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 %}
<div class="d-flex gap-2 mb-3">
<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>
</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">{{ job.asset.s3_path }}</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>
<h2 class="h4">Packaging jobs</h2>
<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 %}
<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 }} &middot; {{ 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 %}
+1 -1
View File
@@ -141,7 +141,7 @@ class TranscodeTests(StudioTestCase):
self.assertEqual([j["id"] for j in listing], [job_id])
def test_transcode_with_inline_profile_by_filename(self):
response = self.request_transcode("asset: video.mp4\nprofile:\n profiles:\n sd:\n bitrate: 800k\n")
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()
@@ -0,0 +1,280 @@
from pathlib import Path
from unittest import mock
from django.core.exceptions import ValidationError
from django.urls import reverse
from privatestudio.studio.models import (
ContentAsset, JobStatus, PackagingJob, TranscodeJob, TranscodeProfile,
)
from privatestudio.studio.profiles import EXAMPLE_PROFILE_YAML, load_default_profile, validate_profile_definition
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, "&#x27;profiles&#x27; 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(
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(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(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(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(studio=self.other_studio, asset=self.other_asset)
other = PackagingJob.objects.create(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 ContentPagesTests(TranscodeJobTestCase):
def test_content_asset_page_lists_jobs(self):
job = self.make_job()
packaging = PackagingJob.objects.create(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"')
+15
View File
@@ -14,6 +14,21 @@ studio_patterns = [
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>/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>/packaging/<int:pk>/", views.PackagingJobDetailView.as_view(), name="packaging_job"),
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(),
+216 -4
View File
@@ -4,17 +4,21 @@ 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 ListView, DetailView, UpdateView
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
from privatestudio.studio.models import ContentAsset, MultipartUpload, Studio, UploadedAsset
from privatestudio.studio.forms import ContentAssetForm, TranscodeJobForm, TranscodeProfileForm
from privatestudio.studio.models import (
ContentAsset, 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
from privatestudio.studio.uploads import UploadError
@@ -57,12 +61,17 @@ class StudioDetailView(StudioMixin, DetailView):
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
@@ -123,7 +132,13 @@ class ContentAssetUpdateView(StudioMixin, UpdateView):
return {**super().get_form_kwargs(), "studio": self.studio}
def get_context_data(self, **kwargs):
return super().get_context_data(studio=self.studio, **kwargs)
transcode_jobs = (
self.object.transcode_jobs
.select_related("profile")
.prefetch_related("packaging_jobs")
.order_by("-requested_at", "-pk")
)
return super().get_context_data(studio=self.studio, transcode_jobs=transcode_jobs, **kwargs)
def form_valid(self, form):
messages.success(self.request, f"Saved {form.instance.title}.")
@@ -138,6 +153,203 @@ class ContentAssetUpdateView(StudioMixin, UpdateView):
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(
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(
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 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 UploadApiView(StudioMixin, View):
"""JSON endpoints for the browser uploader. Uses the session, with normal CSRF protection."""