Pushing up video playback control stuff
This commit is contained in:
1 parent
92d6473e1d
commit
4e2520ee76
10 files changed
+509
-10
No files matched your search
+2
-1
@@ -1,4 +1,5 @@
|
|||||||
*__pycache__*
|
*__pycache__*
|
||||||
/Videos/
|
/Videos/
|
||||||
/Images/
|
/Images/
|
||||||
/ffplay.log
|
/ffplay.log
|
||||||
|
/.thumbnails/
|
||||||
@@ -47,8 +47,9 @@ Ctrl+C or SIGTERM stops the child process; a child that ignores termination is
|
|||||||
killed after two seconds. The player does not modify the database and currently
|
killed after two seconds. The player does not modify the database and currently
|
||||||
does not apply `media_playback_option` records.
|
does not apply `media_playback_option` records.
|
||||||
|
|
||||||
Until playback buttons are wired up, set selection flags directly in SQLite.
|
Use **Play Media** from the home page to select an item in the unified library.
|
||||||
For example, select media ID 3 without temporarily leaving several active rows:
|
Alternatively, set selection flags directly in SQLite. For example, select media
|
||||||
|
ID 3 without temporarily leaving several active rows:
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
BEGIN;
|
BEGIN;
|
||||||
@@ -62,6 +63,39 @@ Flask and the player run separately; starting the web app alone does not start
|
|||||||
playback. The player requires a working graphical display/audio session, not
|
playback. The player requires a working graphical display/audio session, not
|
||||||
just an SSH shell without display access.
|
just an SSH shell without display access.
|
||||||
|
|
||||||
|
## Media library and playback selection
|
||||||
|
|
||||||
|
Open **Play Media** from the homepage, or visit `/media`. All media types share
|
||||||
|
one page, with a **Play** button per item and image/video/stream icons. Clicking
|
||||||
|
Play clears the previous active selection and activates the new item in a single
|
||||||
|
database transaction; default flags are preserved. The separate player picks up
|
||||||
|
the change on its next two-second check.
|
||||||
|
|
||||||
|
A green border and **Selected** badge show the item selected for playback,
|
||||||
|
including the default when no active item exists. The selection banner and badges
|
||||||
|
refresh every two seconds. These indicators reflect the database's requested
|
||||||
|
selection, not proof that FFplay is running or that a stream is healthy. Refresh
|
||||||
|
the page to load newly added media or edited names/sources. Empty sources cannot
|
||||||
|
be selected using the Play button.
|
||||||
|
|
||||||
|
Local images and videos receive lazy-loaded, cached PNG thumbnails generated by
|
||||||
|
FFmpeg (the first video frame, scaled to at most 240×135). Cache files live in
|
||||||
|
`.thumbnails/` beside `config.json` and are excluded from Git. Source path, size,
|
||||||
|
and modification time determine the cache key; deleting this folder is safe and
|
||||||
|
causes previews to regenerate. Streams use an icon without opening a network
|
||||||
|
connection. Missing FFmpeg, unsupported files, or generation failures also fall
|
||||||
|
back to the type icon. Thumbnail generation has a ten-second timeout.
|
||||||
|
|
||||||
|
Previews are restricted to files inside configured image, video, and legacy
|
||||||
|
upload storage folders, including custom storage locations. Symlinks outside
|
||||||
|
those folders are rejected, and FFmpeg's preview input is restricted to local
|
||||||
|
file/pipe protocols. A local file outside those folders can still be selected
|
||||||
|
for playback but has no preview. Media types are inferred from local filename
|
||||||
|
extensions or URL schemes; no schema changes are required.
|
||||||
|
|
||||||
|
As with uploads, keep this interface on a trusted network until authentication
|
||||||
|
and broader access controls are implemented.
|
||||||
|
|
||||||
## Uploading local videos
|
## Uploading local videos
|
||||||
|
|
||||||
Use **Upload a Video** on the home page, or visit `/upload/video`. Enter a display
|
Use **Upload a Video** on the home page, or visit `/upload/video`. Enter a display
|
||||||
@@ -204,5 +238,5 @@ WHERE youtube_download_job_id = 123
|
|||||||
Run the database and worker tests without downloading any videos:
|
Run the database and worker tests without downloading any videos:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test -v
|
python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test test.media_library_test -v
|
||||||
```
|
```
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
Sanctuary Commander is the planned successor to Video Commander: a simple,
|
Sanctuary Commander is the planned successor to Video Commander: a simple,
|
||||||
web-based interface for managing sanctuary TVs and displaying dynamically added
|
web-based interface for managing sanctuary TVs and displaying dynamically added
|
||||||
media. The current implementation provides the web interface, media storage, and
|
media. The current implementation provides the web interface, media storage, and
|
||||||
an FFplay-based player; playback UI controls and device control are still future work.
|
an FFplay-based player with unified playback selection; device control is still future work.
|
||||||
|
|
||||||
## Completed foundations
|
## Completed foundations
|
||||||
|
|
||||||
@@ -27,7 +27,8 @@ an FFplay-based player; playback UI controls and device control are still future
|
|||||||
|
|
||||||
## Finish the current workflows
|
## Finish the current workflows
|
||||||
|
|
||||||
- [ ] Populate the home page with saved media and actionable playback buttons.
|
- [x] Link the home page to a unified media library with Play buttons, live selection
|
||||||
|
indicators, media-type icons, and cached local image/video thumbnails.
|
||||||
- [ ] Connect the existing placeholder controls to backend actions.
|
- [ ] Connect the existing placeholder controls to backend actions.
|
||||||
- [ ] Add input validation for media names, duplicate names, stream URLs, and
|
- [ ] Add input validation for media names, duplicate names, stream URLs, and
|
||||||
uploaded files.
|
uploaded files.
|
||||||
@@ -65,7 +66,9 @@ an FFplay-based player; playback UI controls and device control are still future
|
|||||||
- [ ] Surface preparation status in the web interface.
|
- [ ] Surface preparation status in the web interface.
|
||||||
- [x] Poll active/default media every two seconds, prioritizing active media and
|
- [x] Poll active/default media every two seconds, prioritizing active media and
|
||||||
falling back to default media or a fullscreen black screen.
|
falling back to default media or a fullscreen black screen.
|
||||||
- [ ] Add web controls for changing active and default media.
|
- [x] Add web controls for changing active media atomically, with status matching
|
||||||
|
the player's active/default priority.
|
||||||
|
- [ ] Add web controls for changing default media.
|
||||||
- [ ] Implement the Disable Video and Blackout Screen controls.
|
- [ ] Implement the Disable Video and Blackout Screen controls.
|
||||||
- [ ] Detect USB media and make it available for playback.
|
- [ ] Detect USB media and make it available for playback.
|
||||||
|
|
||||||
|
|||||||
@@ -20,9 +20,7 @@
|
|||||||
<hr>
|
<hr>
|
||||||
<h3 class="text-center">Play Something</h3>
|
<h3 class="text-center">Play Something</h3>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<button class="col-sm-4 btn btn-secondary p-3 my-1">Show Static Image</button>
|
<a class="col-sm-4 btn btn-primary p-3 my-1" href="{{ url_for('media_library.media_list') }}">Play Media</a>
|
||||||
<button class="col-sm-4 btn btn-secondary p-3 my-1">Play a Stream</button>
|
|
||||||
<button class="col-sm-4 btn btn-secondary p-3 my-1">Play a Video</button>
|
|
||||||
</div>
|
</div>
|
||||||
<hr>
|
<hr>
|
||||||
<h3 class="text-center">Add Something</h3>
|
<h3 class="text-center">Add Something</h3>
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
{% macro media_icon(kind) -%}
|
||||||
|
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true" focusable="false">
|
||||||
|
{% if kind == 'image' %}
|
||||||
|
<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="2"/><path d="m3 18 6-6 4 4 3-3 5 5"/>
|
||||||
|
{% elif kind == 'video' %}
|
||||||
|
<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M6 4v16M18 4v16M2 9h4M2 15h4M18 9h4M18 15h4m-9-7 4 4-4 4z"/>
|
||||||
|
{% elif kind == 'stream' %}
|
||||||
|
<circle cx="12" cy="12" r="2"/><path d="M8 8a6 6 0 0 0 0 8m8-8a6 6 0 0 1 0 8M5 5a10 10 0 0 0 0 14M19 5a10 10 0 0 1 0 14"/>
|
||||||
|
{% else %}
|
||||||
|
<rect x="3" y="3" width="18" height="18" rx="2"/><path d="m10 8 6 4-6 4z"/>
|
||||||
|
{% endif %}
|
||||||
|
</svg>
|
||||||
|
{%- endmacro %}
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Play Media - Sanctuary Commander</title>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||||
|
<script src="{{ url_for('static', filename='media_library.js') }}" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="container py-3" id="mediaLibrary" data-status-url="{{ url_for('media_library.playback_status') }}">
|
||||||
|
<h1 class="text-center">Play Media</h1>
|
||||||
|
<hr>
|
||||||
|
<a class="btn btn-secondary mb-3" href="{{ url_for('home.root_route') }}">Home</a>
|
||||||
|
<div class="alert alert-info" role="status" aria-live="polite">
|
||||||
|
<strong id="playbackSelection">{% if state.blank %}Blank screen selected{% else %}Selected for playback: {{ state.selected_name }}{% if state.using_default %} (default){% endif %}{% endif %}</strong>
|
||||||
|
<p class="mb-0 mt-1">This shows the database selection, not player health. Run <code>player.py</code> on the display computer; it picks up changes within about two seconds.</p>
|
||||||
|
</div>
|
||||||
|
<p id="statusError" class="text-danger" role="status" hidden>Unable to refresh playback status. The indicator may be out of date.</p>
|
||||||
|
{% if items %}
|
||||||
|
<div class="row g-3">
|
||||||
|
{% for item in items %}
|
||||||
|
<div class="col-12 col-md-6 col-xl-4">
|
||||||
|
<article class="card h-100 {% if state.selected_id == item.media_id %}border-success border-3{% endif %}"
|
||||||
|
data-media-id="{{ item.media_id }}">
|
||||||
|
<div class="media-preview bg-light text-secondary position-relative d-flex align-items-center justify-content-center">
|
||||||
|
{{ media_icon(item.kind) }}
|
||||||
|
{% if item.preview %}
|
||||||
|
<img class="media-thumbnail" src="{{ url_for('media_library.thumbnail', media_id=item.media_id) }}"
|
||||||
|
alt="Preview of {{ item.media_name }}" loading="lazy" decoding="async">
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="card-body d-flex flex-column">
|
||||||
|
<h2 class="h5 text-break">{{ item.media_name }}</h2>
|
||||||
|
<p class="text-capitalize">{{ media_icon(item.kind) }} <span>{{ item.kind }}</span></p>
|
||||||
|
<div class="mb-3">
|
||||||
|
<span class="badge bg-success" data-selected-badge {% if state.selected_id != item.media_id %}hidden{% endif %}>Selected</span>
|
||||||
|
<span class="badge bg-secondary" data-default-badge {% if item.media_default != 1 %}hidden{% endif %}>Default</span>
|
||||||
|
</div>
|
||||||
|
<form class="mt-auto" method="POST" action="{{ url_for('media_library.play_media', media_id=item.media_id) }}">
|
||||||
|
<button class="btn btn-primary w-100" type="submit" {% if not (item.media_uri or '').strip() %}disabled{% endif %}>
|
||||||
|
<span aria-hidden="true">▶</span> Play <span class="visually-hidden">{{ item.media_name }}</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p role="status">No media yet. Upload an image or video, configure a stream, or download a YouTube video from the home page.</p>
|
||||||
|
{% endif %}
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import hashlib
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
from tempfile import NamedTemporaryFile
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
from flask import Blueprint, abort, current_app, jsonify, redirect, render_template, send_file, url_for
|
||||||
|
|
||||||
|
from utilities.tools import get_db
|
||||||
|
|
||||||
|
|
||||||
|
media_library_bp = Blueprint('media_library', __name__, url_prefix='/media', template_folder='.')
|
||||||
|
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tif', '.tiff', '.gif'}
|
||||||
|
VIDEO_EXTENSIONS = {'.mp4', '.m4v', '.mkv', '.mov', '.webm', '.avi', '.wmv',
|
||||||
|
'.mpeg', '.mpg', '.ts', '.mts', '.m2ts', '.3gp', '.ogv'}
|
||||||
|
|
||||||
|
|
||||||
|
def media_kind(uri):
|
||||||
|
if not uri:
|
||||||
|
return 'unknown'
|
||||||
|
try:
|
||||||
|
if urlsplit(uri).scheme:
|
||||||
|
return 'stream'
|
||||||
|
except ValueError:
|
||||||
|
return 'unknown'
|
||||||
|
extension = Path(uri).suffix.lower()
|
||||||
|
if extension in IMAGE_EXTENSIONS:
|
||||||
|
return 'image'
|
||||||
|
if extension in VIDEO_EXTENSIONS:
|
||||||
|
return 'video'
|
||||||
|
return 'unknown'
|
||||||
|
|
||||||
|
|
||||||
|
def library_state():
|
||||||
|
columns = ['media_id', 'media_name', 'media_uri', 'media_active', 'media_default']
|
||||||
|
rows = get_db().query('SELECT ' + ', '.join(columns) + ' FROM media ORDER BY media_id')[1]
|
||||||
|
items = [dict(zip(columns, row)) for row in rows]
|
||||||
|
# Match player.select_media: active wins, then default, then lowest ID.
|
||||||
|
selected = next((item for item in items if item['media_active'] == 1), None)
|
||||||
|
if selected is None:
|
||||||
|
selected = next((item for item in items if item['media_default'] == 1), None)
|
||||||
|
state = {
|
||||||
|
'selected_id': selected['media_id'] if selected else None,
|
||||||
|
'selected_name': selected['media_name'] if selected else None,
|
||||||
|
'using_default': bool(selected and selected['media_active'] != 1),
|
||||||
|
'blank': not selected or not (selected['media_uri'] or '').strip(),
|
||||||
|
'default_ids': [item['media_id'] for item in items if item['media_default'] == 1]
|
||||||
|
}
|
||||||
|
return items, state
|
||||||
|
|
||||||
|
|
||||||
|
def local_preview_source(uri):
|
||||||
|
if media_kind(uri) not in ('image', 'video'):
|
||||||
|
return None
|
||||||
|
base = Path(current_app.config['CONFIG_DIRECTORY'])
|
||||||
|
path = (base / uri).resolve()
|
||||||
|
config = current_app.config['config']
|
||||||
|
roots = [(base / config.get(key, default)).resolve() for key, default in (
|
||||||
|
('image_upload_location', 'Images'), ('youtube_download_location', 'Videos'),
|
||||||
|
('upload_location', 'uploads')
|
||||||
|
)]
|
||||||
|
# Never expose arbitrary paths or follow a symlink out of configured media storage.
|
||||||
|
if not any(path.is_relative_to(root) for root in roots) or not path.is_file():
|
||||||
|
return None
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@media_library_bp.route('')
|
||||||
|
def media_list():
|
||||||
|
items, state = library_state()
|
||||||
|
for item in items:
|
||||||
|
item['kind'] = media_kind(item['media_uri'])
|
||||||
|
item['preview'] = local_preview_source(item['media_uri']) is not None
|
||||||
|
return render_template('media_library.html', items=items, state=state)
|
||||||
|
|
||||||
|
|
||||||
|
@media_library_bp.route('/status')
|
||||||
|
def playback_status():
|
||||||
|
_, state = library_state()
|
||||||
|
response = jsonify(state)
|
||||||
|
response.headers['Cache-Control'] = 'no-store'
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@media_library_bp.route('/<int:media_id>/play', methods=['POST'])
|
||||||
|
def play_media(media_id):
|
||||||
|
db = get_db()
|
||||||
|
db.query('BEGIN IMMEDIATE')
|
||||||
|
try:
|
||||||
|
rows = db.query('SELECT media_uri FROM media WHERE media_id = ?', [media_id])[1]
|
||||||
|
if not rows:
|
||||||
|
abort(404)
|
||||||
|
if not (rows[0][0] or '').strip():
|
||||||
|
abort(400, description='This media item has no source URI.')
|
||||||
|
# Clearing and setting flags in one transaction avoids flashing the default.
|
||||||
|
db.query('UPDATE media SET media_active = 0 WHERE media_active = 1')
|
||||||
|
db.query('UPDATE media SET media_active = 1 WHERE media_id = ?', [media_id])
|
||||||
|
db.query('COMMIT')
|
||||||
|
except Exception:
|
||||||
|
db.query('ROLLBACK')
|
||||||
|
raise
|
||||||
|
return redirect(url_for('media_library.media_list'), code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@media_library_bp.route('/<int:media_id>/thumbnail')
|
||||||
|
def thumbnail(media_id):
|
||||||
|
rows = get_db().query('SELECT media_uri FROM media WHERE media_id = ?', [media_id])[1]
|
||||||
|
if not rows:
|
||||||
|
abort(404)
|
||||||
|
try:
|
||||||
|
source = local_preview_source(rows[0][0])
|
||||||
|
if source is None:
|
||||||
|
abort(404)
|
||||||
|
stat = source.stat()
|
||||||
|
key = hashlib.sha256(f'{media_id}:{source}:{stat.st_mtime_ns}:{stat.st_size}'.encode()).hexdigest()
|
||||||
|
cache = Path(current_app.config['CONFIG_DIRECTORY']) / '.thumbnails'
|
||||||
|
cache.mkdir(parents=True, exist_ok=True)
|
||||||
|
destination = cache / f'{key}.png'
|
||||||
|
if not destination.is_file():
|
||||||
|
temporary = None
|
||||||
|
try:
|
||||||
|
with NamedTemporaryFile(dir=cache, suffix='.png', delete=False) as output:
|
||||||
|
temporary = Path(output.name)
|
||||||
|
# Read only local media. FFmpeg may not open network protocols referenced by a file.
|
||||||
|
subprocess.run([
|
||||||
|
'ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
|
||||||
|
'-protocol_whitelist', 'file,pipe', '-i', str(source),
|
||||||
|
'-frames:v', '1', '-an', '-vf', 'scale=240:135:force_original_aspect_ratio=decrease',
|
||||||
|
'-threads', '1', str(temporary)
|
||||||
|
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
|
||||||
|
if temporary.stat().st_size == 0:
|
||||||
|
abort(404)
|
||||||
|
temporary.replace(destination)
|
||||||
|
finally:
|
||||||
|
if temporary is not None:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
response = send_file(destination, mimetype='image/png', conditional=True, max_age=0)
|
||||||
|
response.headers['Cache-Control'] = 'no-cache'
|
||||||
|
return response
|
||||||
|
except (OSError, subprocess.SubprocessError):
|
||||||
|
current_app.logger.warning('Thumbnail unavailable for media %s', media_id)
|
||||||
|
abort(404)
|
||||||
@@ -4,6 +4,7 @@ from blueprints.upload_photo.upload_photo import upload_photo_bp
|
|||||||
from blueprints.upload_video.upload_video import upload_video_bp
|
from blueprints.upload_video.upload_video import upload_video_bp
|
||||||
from blueprints.configure_stream.configure_stream import configure_stream_bp
|
from blueprints.configure_stream.configure_stream import configure_stream_bp
|
||||||
from blueprints.youtube_download.youtube_download import youtube_download_bp
|
from blueprints.youtube_download.youtube_download import youtube_download_bp
|
||||||
|
from blueprints.media_library.media_library import media_library_bp
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
|
|
||||||
@@ -22,6 +23,7 @@ app.register_blueprint(upload_photo_bp)
|
|||||||
app.register_blueprint(upload_video_bp)
|
app.register_blueprint(upload_video_bp)
|
||||||
app.register_blueprint(configure_stream_bp)
|
app.register_blueprint(configure_stream_bp)
|
||||||
app.register_blueprint(youtube_download_bp)
|
app.register_blueprint(youtube_download_bp)
|
||||||
|
app.register_blueprint(media_library_bp)
|
||||||
|
|
||||||
|
|
||||||
@app.teardown_appcontext
|
@app.teardown_appcontext
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
const library = document.getElementById('mediaLibrary')
|
||||||
|
const selection = document.getElementById('playbackSelection')
|
||||||
|
const statusError = document.getElementById('statusError')
|
||||||
|
|
||||||
|
for (const image of document.querySelectorAll('.media-thumbnail')) {
|
||||||
|
image.addEventListener('error', () => { image.hidden = true })
|
||||||
|
if (image.complete && image.naturalWidth === 0) image.hidden = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshSelection() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(library.dataset.statusUrl, {cache: 'no-store'})
|
||||||
|
if (!response.ok) throw new Error('Status request failed')
|
||||||
|
const state = await response.json()
|
||||||
|
selection.textContent = state.blank ? 'Blank screen selected'
|
||||||
|
: `Selected for playback: ${state.selected_name}${state.using_default ? ' (default)' : ''}`
|
||||||
|
for (const card of library.querySelectorAll('[data-media-id]')) {
|
||||||
|
const selected = Number(card.dataset.mediaId) === state.selected_id
|
||||||
|
card.classList.toggle('border-success', selected)
|
||||||
|
card.classList.toggle('border-3', selected)
|
||||||
|
card.querySelector('[data-selected-badge]').hidden = !selected
|
||||||
|
card.querySelector('[data-default-badge]').hidden = !state.default_ids.includes(Number(card.dataset.mediaId))
|
||||||
|
}
|
||||||
|
statusError.hidden = true
|
||||||
|
} catch (error) {
|
||||||
|
statusError.hidden = false
|
||||||
|
} finally {
|
||||||
|
// Schedule after completion so slow requests never overlap.
|
||||||
|
window.setTimeout(refreshSelection, 2000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.setTimeout(refreshSelection, 2000)
|
||||||
@@ -3,4 +3,16 @@ html {
|
|||||||
}
|
}
|
||||||
body {
|
body {
|
||||||
background-color: #ebe1c7 !important;
|
background-color: #ebe1c7 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.media-preview {
|
||||||
|
aspect-ratio: 16 / 9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.media-thumbnail {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
from contextlib import closing
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import runpy
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from blueprints.media_library.media_library import media_kind
|
||||||
|
from player import select_media
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class MediaLibraryTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.directory = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.directory.cleanup)
|
||||||
|
self.workdir = Path(self.directory.name)
|
||||||
|
self.database = self.workdir / 'test.db'
|
||||||
|
(self.workdir / 'config.json').write_text(json.dumps({
|
||||||
|
'database': {'type': 'SQLite', 'name': str(self.database)},
|
||||||
|
'upload_location': str(self.workdir / 'uploads')
|
||||||
|
}))
|
||||||
|
subprocess.run([sys.executable, str(ROOT / 'sc_database_generator.py')],
|
||||||
|
cwd=self.workdir, check=True, capture_output=True)
|
||||||
|
original = Path.cwd()
|
||||||
|
try:
|
||||||
|
os.chdir(self.workdir)
|
||||||
|
self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app']
|
||||||
|
finally:
|
||||||
|
os.chdir(original)
|
||||||
|
self.app.config['TESTING'] = True
|
||||||
|
self.client = self.app.test_client()
|
||||||
|
|
||||||
|
def add_media(self, name='Video', uri='Videos/video.mp4', active=0, default=0):
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
media_id = db.execute(
|
||||||
|
'INSERT INTO media (media_name, media_uri, media_active, media_default) VALUES (?, ?, ?, ?)',
|
||||||
|
[name, uri, active, default]
|
||||||
|
).lastrowid
|
||||||
|
db.commit()
|
||||||
|
return media_id
|
||||||
|
|
||||||
|
def create_local(self, name='Images/photo.png'):
|
||||||
|
path = self.workdir / name
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(b'local media')
|
||||||
|
return path
|
||||||
|
|
||||||
|
def fake_ffmpeg(self, command, **kwargs):
|
||||||
|
Path(command[-1]).write_bytes(b'cached preview')
|
||||||
|
return subprocess.CompletedProcess(command, 0)
|
||||||
|
|
||||||
|
def assert_active(self, expected):
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
self.assertEqual(db.execute('SELECT media_id FROM media WHERE media_active = 1').fetchall(),
|
||||||
|
[(expected,)] if expected is not None else [])
|
||||||
|
|
||||||
|
def test_home_links_to_unified_library_and_empty_state(self):
|
||||||
|
home = self.client.get('/')
|
||||||
|
self.assertIn(b'href="/media"', home.data)
|
||||||
|
self.assertNotIn(b'>Show Static Image</button>', home.data)
|
||||||
|
response = self.client.get('/media')
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertIn(b'No media yet.', response.data)
|
||||||
|
self.assertIn(b'Blank screen selected', response.data)
|
||||||
|
|
||||||
|
def test_play_selects_one_media_and_preserves_defaults(self):
|
||||||
|
first = self.add_media(active=1, default=1)
|
||||||
|
second = self.add_media(uri='https://example.com/live')
|
||||||
|
response = self.client.post(f'/media/{second}/play')
|
||||||
|
self.assertEqual(response.status_code, 303)
|
||||||
|
self.assertTrue(response.location.endswith('/media'))
|
||||||
|
self.assert_active(second)
|
||||||
|
state = self.client.get('/media/status').json
|
||||||
|
self.assertEqual(state['selected_id'], second)
|
||||||
|
self.assertFalse(state['using_default'])
|
||||||
|
self.assertEqual(state['default_ids'], [first])
|
||||||
|
self.client.post(f'/media/{second}/play')
|
||||||
|
self.assert_active(second)
|
||||||
|
|
||||||
|
def test_play_requires_post(self):
|
||||||
|
media_id = self.add_media()
|
||||||
|
self.assertEqual(self.client.get(f'/media/{media_id}/play').status_code, 405)
|
||||||
|
self.assert_active(None)
|
||||||
|
|
||||||
|
def test_missing_or_empty_media_does_not_clear_active(self):
|
||||||
|
active = self.add_media(active=1)
|
||||||
|
empty = self.add_media(uri=' ')
|
||||||
|
self.assertEqual(self.client.post('/media/999/play').status_code, 404)
|
||||||
|
self.assertEqual(self.client.post(f'/media/{empty}/play').status_code, 400)
|
||||||
|
self.assert_active(active)
|
||||||
|
|
||||||
|
def test_failed_selection_transaction_restores_previous_active(self):
|
||||||
|
first = self.add_media(active=1)
|
||||||
|
second = self.add_media()
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
db.execute(f'''
|
||||||
|
CREATE TRIGGER reject_selection BEFORE UPDATE ON media
|
||||||
|
WHEN NEW.media_id = {second} AND NEW.media_active = 1
|
||||||
|
BEGIN SELECT RAISE(ABORT, 'Test failure'); END
|
||||||
|
''')
|
||||||
|
db.commit()
|
||||||
|
with self.assertRaises(sqlite3.IntegrityError):
|
||||||
|
self.client.post(f'/media/{second}/play')
|
||||||
|
self.assert_active(first)
|
||||||
|
|
||||||
|
def test_status_matches_player_priority_and_changes(self):
|
||||||
|
first = self.add_media(name='First default', default=1)
|
||||||
|
self.add_media(name='Second default', default=1)
|
||||||
|
active = self.add_media(name='Active', active=1)
|
||||||
|
self.add_media(name='Second active', active=1)
|
||||||
|
for expected, default in ((active, False), (first, True), (None, False)):
|
||||||
|
state = self.client.get('/media/status')
|
||||||
|
self.assertEqual(state.json['selected_id'], expected)
|
||||||
|
self.assertEqual(state.json['using_default'], default)
|
||||||
|
self.assertEqual(state.headers['Cache-Control'], 'no-store')
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
selected = select_media(db)
|
||||||
|
self.assertEqual(selected[0] if selected else None, expected)
|
||||||
|
if expected == active:
|
||||||
|
db.execute('UPDATE media SET media_active = 0')
|
||||||
|
else:
|
||||||
|
db.execute('UPDATE media SET media_default = 0')
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
def test_names_are_escaped_and_icons_are_present(self):
|
||||||
|
self.add_media(name='<script>alert(1)</script>', uri='Images/photo.PNG', default=1)
|
||||||
|
self.add_media(uri='Videos/local.mp4')
|
||||||
|
self.add_media(uri='https://example.com/video.mp4')
|
||||||
|
response = self.client.get('/media')
|
||||||
|
self.assertNotIn(b'<script>alert(1)</script>', response.data)
|
||||||
|
self.assertIn(b'<script>', response.data)
|
||||||
|
self.assertIn(b'<svg', response.data)
|
||||||
|
self.assertIn(b'<span>image</span>', response.data)
|
||||||
|
self.assertIn(b'<span>video</span>', response.data)
|
||||||
|
self.assertIn(b'<span>stream</span>', response.data)
|
||||||
|
self.assertIn(b'Selected', response.data)
|
||||||
|
self.assertIn(b'Default', response.data)
|
||||||
|
|
||||||
|
def test_thumbnail_generation_cache_and_file_change(self):
|
||||||
|
source = self.create_local()
|
||||||
|
media_id = self.add_media(uri=str(source))
|
||||||
|
page = self.client.get('/media')
|
||||||
|
self.assertIn(f'/media/{media_id}/thumbnail'.encode(), page.data)
|
||||||
|
with patch('blueprints.media_library.media_library.subprocess.run', side_effect=self.fake_ffmpeg) as run:
|
||||||
|
with self.client.get(f'/media/{media_id}/thumbnail') as response:
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.mimetype, 'image/png')
|
||||||
|
self.assertEqual(response.data, b'cached preview')
|
||||||
|
with self.client.get(f'/media/{media_id}/thumbnail') as response:
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(run.call_count, 1)
|
||||||
|
command = run.call_args.args[0]
|
||||||
|
self.assertIn('file,pipe', command)
|
||||||
|
self.assertIn(str(source), command)
|
||||||
|
self.assertEqual(run.call_args.kwargs['timeout'], 10)
|
||||||
|
source.write_bytes(b'changed content and size')
|
||||||
|
with self.client.get(f'/media/{media_id}/thumbnail') as response:
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(run.call_count, 2)
|
||||||
|
|
||||||
|
def test_remote_and_outside_sources_never_invoke_ffmpeg(self):
|
||||||
|
outside = self.create_local('private/image.png')
|
||||||
|
(self.workdir / 'Images').mkdir()
|
||||||
|
(self.workdir / 'Images/link.png').symlink_to(outside)
|
||||||
|
sources = ['https://example.com/image.png', str(outside), 'Images/link.png',
|
||||||
|
'Images/missing.png', 'Videos/playlist.m3u8', None]
|
||||||
|
with patch('blueprints.media_library.media_library.subprocess.run') as run:
|
||||||
|
for source in sources:
|
||||||
|
media_id = self.add_media(uri=source)
|
||||||
|
self.assertEqual(self.client.get(f'/media/{media_id}/thumbnail').status_code, 404)
|
||||||
|
run.assert_not_called()
|
||||||
|
|
||||||
|
def test_thumbnail_failure_cleans_temporary_files(self):
|
||||||
|
self.create_local()
|
||||||
|
media_id = self.add_media(uri='Images/photo.png')
|
||||||
|
for error in (FileNotFoundError('ffmpeg missing'), subprocess.TimeoutExpired('ffmpeg', 10)):
|
||||||
|
with self.subTest(error=error):
|
||||||
|
with patch('blueprints.media_library.media_library.subprocess.run', side_effect=error):
|
||||||
|
with self.assertLogs(self.app.logger, level='WARNING'):
|
||||||
|
self.assertEqual(self.client.get(f'/media/{media_id}/thumbnail').status_code, 404)
|
||||||
|
self.assertEqual(list((self.workdir / '.thumbnails').iterdir()), [])
|
||||||
|
|
||||||
|
def test_thumbnail_supports_custom_storage_root(self):
|
||||||
|
self.app.config['config']['image_upload_location'] = 'CustomImages'
|
||||||
|
self.create_local('CustomImages/photo.png')
|
||||||
|
media_id = self.add_media(uri='CustomImages/photo.png')
|
||||||
|
with patch('blueprints.media_library.media_library.subprocess.run', side_effect=self.fake_ffmpeg):
|
||||||
|
with self.client.get(f'/media/{media_id}/thumbnail') as response:
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_media_types(self):
|
||||||
|
for uri, kind in [('Images/a.JPG', 'image'), ('Videos/a.mkv', 'video'),
|
||||||
|
('https://example.com/a.png', 'stream'), (None, 'unknown')]:
|
||||||
|
self.assertEqual(media_kind(uri), kind)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user