Input validation work and error handling
This commit is contained in:
1 parent
4e2520ee76
commit
554b7cc82c
20 files changed
+627
-96
No files matched your search
@@ -96,13 +96,36 @@ 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.
|
||||
|
||||
## Submission validation
|
||||
|
||||
All new image, video, stream, and YouTube submissions require a nonblank media
|
||||
name of at most 120 characters, without control characters. Surrounding spaces
|
||||
are removed. Names must be unique across the media catalog and pending or
|
||||
currently downloading YouTube jobs, compared case-insensitively after Unicode
|
||||
normalization and trimming. Failed jobs do not reserve names; completed jobs
|
||||
normally have a catalog entry that does. Existing records are not renamed or
|
||||
removed. This rule is enforced by the app and worker when writing under SQLite
|
||||
transactions, not by a database constraint; direct SQL can bypass it.
|
||||
|
||||
Stream registration accepts HTTP, HTTPS, RTSP, RTMP, RTMPS, UDP, and TCP network
|
||||
URLs, including local-network hosts. YouTube requests require a supported
|
||||
individual video URL. Validation checks syntax, not network reachability.
|
||||
|
||||
Image and video uploads require **FFprobe and FFmpeg on PATH** for local-only,
|
||||
time-limited content validation. Extensions and client MIME types alone are not
|
||||
trusted; a video stream and a decodable first frame are required. Full files are
|
||||
not decoded or scanned for malware. Missing validation tools, storage issues,
|
||||
database failures, and invalid fields produce user-facing errors without saving
|
||||
an incomplete media entry. Retrying a failed upload starts it from the beginning.
|
||||
|
||||
## Uploading local videos
|
||||
|
||||
Use **Upload a Video** on the home page, or visit `/upload/video`. Enter a display
|
||||
name and select one video. The limit is 5GB (5 × 1024³ bytes), checked both in the
|
||||
browser and on the server. Common formats including MP4, MKV, MOV, WebM, AVI,
|
||||
MPEG, and WMV are accepted by extension; the upload does not transcode or inspect
|
||||
video codecs.
|
||||
MPEG, and WMV are accepted by extension. Before saving, FFprobe checks for a
|
||||
video stream and FFmpeg decodes its first frame; the upload does not transcode the
|
||||
file or guarantee the rest of the video is valid.
|
||||
|
||||
The page displays transfer progress and warns against navigating away. At 100%,
|
||||
wait for the server to finish saving; only then will the page automatically
|
||||
@@ -125,8 +148,9 @@ space for both Flask's temporary upload and the final video file.
|
||||
|
||||
Use **Upload a Static Image** on the home page, or visit `/upload/photo`. Enter
|
||||
an image name and choose one JPG/JPEG, PNG, WebP, BMP, TIFF, or GIF file. Files
|
||||
are accepted by extension; this workflow does not decode the image or check for
|
||||
animation. SVG and other active-content formats are not accepted.
|
||||
are checked against their extensions and decoded for validation. Images may be
|
||||
animated, but only the first frame is checked; dimensions are limited to 50
|
||||
megapixels. SVG and other active-content formats are not accepted.
|
||||
|
||||
Image uploads now use `"image_upload_location": "Images"` in `config.json`,
|
||||
relative to that file. The folder is created automatically when saving an upload
|
||||
@@ -238,5 +262,5 @@ WHERE youtube_download_job_id = 123
|
||||
Run the database and worker tests without downloading any videos:
|
||||
|
||||
```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 test.media_library_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 test.submission_validation_test -v
|
||||
```
|
||||
@@ -30,10 +30,10 @@ an FFplay-based player with unified playback selection; device control is still
|
||||
- [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.
|
||||
- [ ] Add input validation for media names, duplicate names, stream URLs, and
|
||||
- [x] Add input validation for media names, duplicate names, stream URLs, and
|
||||
uploaded files.
|
||||
- [ ] Ensure upload destinations remain inside the configured upload directory.
|
||||
- [ ] Handle missing form fields, missing files, and storage/database failures
|
||||
- [x] Handle missing form fields, missing files, and storage/database failures
|
||||
with useful error messages.
|
||||
- [x] Close request-scoped database connections when requests finish.
|
||||
|
||||
|
||||
@@ -14,17 +14,18 @@
|
||||
<div class="alert alert-info text-center" role="alert">
|
||||
Configure a stream, content that is played from a location on the local network or the Internet.
|
||||
</div>
|
||||
<form action="/configure/stream" method="POST">
|
||||
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
|
||||
<form action="{{ url_for('configure_stream.get_page') }}" method="POST">
|
||||
<div class="form-group">
|
||||
<label for="buttonName">Button Name</label>
|
||||
<input type="text" class="form-control" name="buttonName" id="buttonName" />
|
||||
<input type="text" class="form-control" name="buttonName" id="buttonName" value="{{ name }}" maxlength="120" required />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="streamURL">Stream URL</label>
|
||||
<input type="text" class="form-control" name="streamURL" id="streamURL" />
|
||||
<input type="text" class="form-control" name="streamURL" id="streamURL" value="{{ stream_url }}" required />
|
||||
</div>
|
||||
<div class="form-check form-switch form-check-input-lg">
|
||||
<input type="checkbox" class="form-check-input" name="fullScreen" id="fullScreen" checked/>
|
||||
<input type="checkbox" class="form-check-input" name="fullScreen" id="fullScreen" {% if fullscreen %}checked{% endif %}/>
|
||||
<label for="fullScreen" class="form-check-label">Play the stream in Full Screen?</label>
|
||||
</div>
|
||||
<button id="submit" class="btn btn-primary form-control" type="submit">Submit</button>
|
||||
|
||||
@@ -1,33 +1,44 @@
|
||||
from flask import Blueprint, request, render_template, redirect
|
||||
import sqlite3
|
||||
|
||||
from flask import Blueprint, request, render_template, redirect, url_for, current_app
|
||||
from utilities.tools import get_db
|
||||
from utilities.validation import (ValidationError, ensure_name_available,
|
||||
validate_media_name, valid_stream_url, write_transaction)
|
||||
|
||||
|
||||
configure_stream_bp = Blueprint('configure_stream', __name__, url_prefix='/configure', template_folder='.')
|
||||
|
||||
|
||||
@configure_stream_bp.route('/stream', methods=['GET', 'POST'])
|
||||
def get_page():
|
||||
if request.method == "GET":
|
||||
return render_get()
|
||||
elif request.method == "POST":
|
||||
return upload()
|
||||
|
||||
|
||||
def render_get():
|
||||
return render_template('configure_stream.html'), 200
|
||||
|
||||
def upload():
|
||||
# TODO Input Validation
|
||||
|
||||
new_id = get_db().insert(
|
||||
"media",
|
||||
["media_name", "media_uri"],
|
||||
[request.form["buttonName"], request.form["streamURL"]]
|
||||
)
|
||||
|
||||
if request.form.get("fullScreen", False):
|
||||
get_db().insert(
|
||||
"media_playback_option",
|
||||
["media_id", "media_playback_option", "media_playback_option_weight"],
|
||||
[new_id, "-fs", 1]
|
||||
)
|
||||
|
||||
return redirect("/")
|
||||
name = ''
|
||||
stream_url = ''
|
||||
fullscreen = True
|
||||
error = None
|
||||
status = 200
|
||||
if request.method == 'POST':
|
||||
name = request.form.get('buttonName', '')
|
||||
stream_url = request.form.get('streamURL', '').strip(' ')
|
||||
fullscreen = request.form.get('fullScreen') in ('on', '1', 'true')
|
||||
try:
|
||||
name = validate_media_name(name)
|
||||
if not valid_stream_url(stream_url):
|
||||
raise ValidationError('Enter a valid network stream URL (HTTP, HTTPS, RTSP, RTMP, RTMPS, UDP, or TCP).')
|
||||
db = get_db()
|
||||
with write_transaction(db):
|
||||
ensure_name_available(db.db, name)
|
||||
new_id = db.insert('media', ['media_name', 'media_uri'], [name, stream_url])
|
||||
if fullscreen:
|
||||
db.insert('media_playback_option',
|
||||
['media_id', 'media_playback_option', 'media_playback_option_weight'],
|
||||
[new_id, '-fs', 1])
|
||||
return redirect(url_for('home.root_route'), code=303)
|
||||
except ValidationError as exception:
|
||||
error = str(exception)
|
||||
status = 400
|
||||
except sqlite3.Error:
|
||||
current_app.logger.exception('Unable to save stream')
|
||||
error = 'Unable to save the stream due to a database error. Please try again.'
|
||||
status = 503
|
||||
return render_template('configure_stream.html', name=name, stream_url=stream_url,
|
||||
fullscreen=fullscreen, error=error), status
|
||||
@@ -25,7 +25,7 @@
|
||||
<fieldset id="uploadFields">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="imageName">Image Name</label>
|
||||
<input class="form-control" type="text" id="imageName" name="name" required>
|
||||
<input class="form-control" type="text" id="imageName" name="name" maxlength="120" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="imageFile">Image File</label>
|
||||
|
||||
@@ -5,6 +5,8 @@ from uuid import uuid4
|
||||
from flask import Blueprint, request, render_template, jsonify, current_app
|
||||
from werkzeug.exceptions import RequestEntityTooLarge
|
||||
from utilities.tools import get_db
|
||||
from utilities.validation import (ValidationError, ValidationUnavailable, ensure_name_available,
|
||||
validate_media_name, validate_upload_content, write_transaction)
|
||||
|
||||
|
||||
MAX_IMAGE_SIZE = 100 * (1024 ** 2)
|
||||
@@ -33,19 +35,24 @@ def get_page():
|
||||
|
||||
|
||||
def upload():
|
||||
name = request.form.get('name', '').strip()
|
||||
if not name:
|
||||
return jsonify(status='FAILED', error='Please enter a name for the image.'), 400
|
||||
try:
|
||||
name = validate_media_name(request.form.get('name', ''))
|
||||
except ValidationError as error:
|
||||
return jsonify(status='FAILED', error=str(error)), 400
|
||||
files = request.files.getlist('files[]')
|
||||
if len(files) != 1 or not files[0].filename:
|
||||
if len(files) != 1 or len(list(request.files.items(multi=True))) != 1 or not files[0].filename:
|
||||
return jsonify(status='FAILED', error='Please select exactly one image file.'), 400
|
||||
image = files[0]
|
||||
extension = Path(image.filename).suffix.lower()
|
||||
if extension not in IMAGE_EXTENSIONS:
|
||||
return jsonify(status='FAILED', error='Please select a supported image file.'), 400
|
||||
|
||||
storage = (Path(current_app.config['CONFIG_DIRECTORY']) /
|
||||
current_app.config['config'].get('image_upload_location', 'Images')).resolve()
|
||||
try:
|
||||
storage = (Path(current_app.config['CONFIG_DIRECTORY']) /
|
||||
current_app.config['config'].get('image_upload_location', 'Images')).resolve()
|
||||
except (OSError, RuntimeError):
|
||||
current_app.logger.exception('Unable to resolve image storage location')
|
||||
return jsonify(status='FAILED', error='Unable to access image storage. Please contact the administrator.'), 500
|
||||
# Names are display metadata, never user-controlled storage paths.
|
||||
token = uuid4().hex
|
||||
destination = storage / f'upload-{token}{extension}'
|
||||
@@ -62,10 +69,19 @@ def upload():
|
||||
output.write(chunk)
|
||||
if size == 0:
|
||||
return jsonify(status='FAILED', error='The image file is empty.'), 400
|
||||
partial.rename(destination)
|
||||
get_db().insert('media', ['media_name', 'media_uri'], [name, str(destination)])
|
||||
validate_upload_content(partial, 'image', extension)
|
||||
db = get_db()
|
||||
with write_transaction(db):
|
||||
ensure_name_available(db.db, name)
|
||||
partial.rename(destination)
|
||||
db.insert('media', ['media_name', 'media_uri'], [name, str(destination)])
|
||||
saved = True
|
||||
return jsonify(status='SUCCESS'), 200
|
||||
except ValidationError as error:
|
||||
return jsonify(status='FAILED', error=str(error)), 400
|
||||
except ValidationUnavailable as error:
|
||||
current_app.logger.warning('Image validation unavailable: %s', error)
|
||||
return jsonify(status='FAILED', error=str(error)), 503
|
||||
except (OSError, sqlite3.Error):
|
||||
current_app.logger.exception('Unable to save uploaded image')
|
||||
return jsonify(status='FAILED', error='Unable to save the image. Please try again.'), 500
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<fieldset id="uploadFields">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="videoName">Video Name</label>
|
||||
<input class="form-control" type="text" id="videoName" name="name" required>
|
||||
<input class="form-control" type="text" id="videoName" name="name" maxlength="120" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="videoFile">Video File</label>
|
||||
|
||||
@@ -5,6 +5,8 @@ from uuid import uuid4
|
||||
from flask import Blueprint, request, render_template, jsonify, current_app
|
||||
from werkzeug.exceptions import RequestEntityTooLarge
|
||||
from utilities.tools import get_db
|
||||
from utilities.validation import (ValidationError, ValidationUnavailable, ensure_name_available,
|
||||
validate_media_name, validate_upload_content, write_transaction)
|
||||
|
||||
|
||||
MAX_VIDEO_SIZE = 5 * (1024 ** 3)
|
||||
@@ -36,19 +38,24 @@ def get_page():
|
||||
|
||||
|
||||
def upload():
|
||||
name = request.form.get('name', '').strip()
|
||||
if not name:
|
||||
return jsonify(status='FAILED', error='Please enter a name for the video.'), 400
|
||||
try:
|
||||
name = validate_media_name(request.form.get('name', ''))
|
||||
except ValidationError as error:
|
||||
return jsonify(status='FAILED', error=str(error)), 400
|
||||
files = request.files.getlist('files[]')
|
||||
if len(files) != 1 or not files[0].filename:
|
||||
if len(files) != 1 or len(list(request.files.items(multi=True))) != 1 or not files[0].filename:
|
||||
return jsonify(status='FAILED', error='Please select exactly one video file.'), 400
|
||||
video = files[0]
|
||||
extension = Path(video.filename).suffix.lower()
|
||||
if extension not in VIDEO_EXTENSIONS:
|
||||
return jsonify(status='FAILED', error='Please select a supported video file.'), 400
|
||||
|
||||
storage = (Path(current_app.config['CONFIG_DIRECTORY']) /
|
||||
current_app.config['config'].get('youtube_download_location', 'Videos')).resolve()
|
||||
try:
|
||||
storage = (Path(current_app.config['CONFIG_DIRECTORY']) /
|
||||
current_app.config['config'].get('youtube_download_location', 'Videos')).resolve()
|
||||
except (OSError, RuntimeError):
|
||||
current_app.logger.exception('Unable to resolve video storage location')
|
||||
return jsonify(status='FAILED', error='Unable to access video storage. Please contact the administrator.'), 500
|
||||
# Never use the media name or client filename as a storage path.
|
||||
token = uuid4().hex
|
||||
destination = storage / f'upload-{token}{extension}'
|
||||
@@ -65,10 +72,19 @@ def upload():
|
||||
output.write(chunk)
|
||||
if size == 0:
|
||||
return jsonify(status='FAILED', error='The video file is empty.'), 400
|
||||
partial.rename(destination)
|
||||
get_db().insert('media', ['media_name', 'media_uri'], [name, str(destination)])
|
||||
validate_upload_content(partial, 'video', extension)
|
||||
db = get_db()
|
||||
with write_transaction(db):
|
||||
ensure_name_available(db.db, name)
|
||||
partial.rename(destination)
|
||||
db.insert('media', ['media_name', 'media_uri'], [name, str(destination)])
|
||||
saved = True
|
||||
return jsonify(status='SUCCESS'), 200
|
||||
except ValidationError as error:
|
||||
return jsonify(status='FAILED', error=str(error)), 400
|
||||
except ValidationUnavailable as error:
|
||||
current_app.logger.warning('Video validation unavailable: %s', error)
|
||||
return jsonify(status='FAILED', error=str(error)), 503
|
||||
except (OSError, sqlite3.Error):
|
||||
current_app.logger.exception('Unable to save uploaded video')
|
||||
return jsonify(status='FAILED', error='Unable to save the video. Please try again.'), 500
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
from urllib.parse import urlsplit
|
||||
import re
|
||||
import sqlite3
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from flask import Blueprint, request, render_template, redirect, url_for
|
||||
from flask import Blueprint, request, render_template, redirect, url_for, current_app
|
||||
from utilities.tools import get_db
|
||||
from utilities.validation import (ValidationError, ensure_name_available, validate_media_name,
|
||||
valid_stream_url, write_transaction)
|
||||
|
||||
|
||||
youtube_download_bp = Blueprint('youtube_download', __name__, url_prefix='/youtube', template_folder='.')
|
||||
@@ -13,19 +17,26 @@ def request_download():
|
||||
youtube_url = ''
|
||||
error = None
|
||||
if request.method == 'POST':
|
||||
media_name = request.form.get('media_name', '').strip()
|
||||
youtube_url = request.form.get('youtube_url', '').strip()
|
||||
if not media_name:
|
||||
error = 'Please enter a name for the media item.'
|
||||
elif not valid_youtube_url(youtube_url):
|
||||
error = 'Please enter a valid YouTube video URL (youtube.com or youtu.be).'
|
||||
else:
|
||||
get_db().insert(
|
||||
'youtube_download_job',
|
||||
['youtube_download_job_url', 'youtube_download_job_media_name'],
|
||||
[youtube_url, media_name]
|
||||
)
|
||||
media_name = request.form.get('media_name', '')
|
||||
youtube_url = request.form.get('youtube_url', '').strip(' ')
|
||||
try:
|
||||
media_name = validate_media_name(media_name)
|
||||
if not valid_youtube_url(youtube_url):
|
||||
raise ValidationError('Please enter a valid YouTube video URL (youtube.com or youtu.be).')
|
||||
db = get_db()
|
||||
with write_transaction(db):
|
||||
ensure_name_available(db.db, media_name)
|
||||
db.insert('youtube_download_job',
|
||||
['youtube_download_job_url', 'youtube_download_job_media_name'],
|
||||
[youtube_url, media_name])
|
||||
return redirect(url_for('youtube_download.list_jobs'), code=303)
|
||||
except ValidationError as exception:
|
||||
error = str(exception)
|
||||
except sqlite3.Error:
|
||||
current_app.logger.exception('Unable to queue YouTube download')
|
||||
return render_template('youtube_request.html', media_name=media_name,
|
||||
youtube_url=youtube_url,
|
||||
error='Unable to queue the download due to a database error. Please try again.'), 503
|
||||
|
||||
return render_template(
|
||||
'youtube_request.html', media_name=media_name, youtube_url=youtube_url, error=error
|
||||
@@ -33,17 +44,27 @@ def request_download():
|
||||
|
||||
|
||||
def valid_youtube_url(value):
|
||||
if not valid_stream_url(value):
|
||||
return False
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
return (
|
||||
parsed.scheme in ('http', 'https')
|
||||
and parsed.hostname in ('youtube.com', 'www.youtube.com', 'm.youtube.com',
|
||||
'music.youtube.com', 'youtu.be', 'www.youtu.be')
|
||||
and not parsed.username and not parsed.password
|
||||
and parsed.port in (None, 80, 443)
|
||||
and bool(parsed.path.strip('/'))
|
||||
and not any(character.isspace() for character in value)
|
||||
)
|
||||
if parsed.scheme not in ('http', 'https') or parsed.username or parsed.password or parsed.port not in (None, 80, 443):
|
||||
return False
|
||||
host = parsed.hostname
|
||||
path = parsed.path.strip('/').split('/')
|
||||
if host in ('youtu.be', 'www.youtu.be') and len(path) == 1:
|
||||
video_id = path[0]
|
||||
elif host in ('youtube.com', 'www.youtube.com', 'm.youtube.com', 'music.youtube.com'):
|
||||
if path == ['watch']:
|
||||
ids = parse_qs(parsed.query).get('v', [])
|
||||
video_id = ids[0] if len(ids) == 1 else ''
|
||||
elif len(path) == 2 and path[0] in ('shorts', 'live', 'embed'):
|
||||
video_id = path[1]
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
return bool(re.fullmatch(r'[A-Za-z0-9_-]{1,128}', video_id))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<form action="{{ url_for('youtube_download.request_download') }}" method="POST">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="media_name">Media Name</label>
|
||||
<input type="text" class="form-control" name="media_name" id="media_name" value="{{ media_name }}" required>
|
||||
<input type="text" class="form-control" name="media_name" id="media_name" value="{{ media_name }}" maxlength="120" required>
|
||||
<div class="form-text">The name to display when the downloaded video is ready to play.</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
|
||||
+11
-1
@@ -1,4 +1,4 @@
|
||||
from flask import Flask, g
|
||||
from flask import Flask, g, jsonify, render_template, request
|
||||
from blueprints.home.home import home_bp
|
||||
from blueprints.upload_photo.upload_photo import upload_photo_bp
|
||||
from blueprints.upload_video.upload_video import upload_video_bp
|
||||
@@ -7,6 +7,7 @@ from blueprints.youtube_download.youtube_download import youtube_download_bp
|
||||
from blueprints.media_library.media_library import media_library_bp
|
||||
import os
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
with open("config.json", 'r') as config_file:
|
||||
config_json = json.loads(config_file.read())
|
||||
@@ -26,6 +27,15 @@ app.register_blueprint(youtube_download_bp)
|
||||
app.register_blueprint(media_library_bp)
|
||||
|
||||
|
||||
@app.errorhandler(sqlite3.Error)
|
||||
def database_error(error):
|
||||
app.logger.exception('Database request failed')
|
||||
message = 'The database is unavailable. Please try again or contact the administrator.'
|
||||
if request.path.startswith('/upload/') or request.path == '/media/status':
|
||||
return jsonify(status='FAILED', error=message), 503
|
||||
return render_template('database_error.html', message=message), 503
|
||||
|
||||
|
||||
@app.teardown_appcontext
|
||||
def close_database(error):
|
||||
db = g.pop('_database', None)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Database unavailable - 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">
|
||||
</head>
|
||||
<body>
|
||||
<main class="container py-3">
|
||||
<h1>Unable to complete the request</h1>
|
||||
<div class="alert alert-danger" role="alert">{{ message }}</div>
|
||||
<a class="btn btn-secondary" href="{{ url_for('home.root_route') }}">Home</a>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -107,8 +107,10 @@ class MediaLibraryTest(unittest.TestCase):
|
||||
BEGIN SELECT RAISE(ABORT, 'Test failure'); END
|
||||
''')
|
||||
db.commit()
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.client.post(f'/media/{second}/play')
|
||||
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||
response = self.client.post(f'/media/{second}/play')
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertIn(b'database is unavailable', response.data)
|
||||
self.assert_active(first)
|
||||
|
||||
def test_status_matches_player_priority_and_changes(self):
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import closing
|
||||
from io import BytesIO
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import wave
|
||||
from unittest.mock import patch
|
||||
|
||||
from test.upload_photo_test import PNG
|
||||
from test.upload_video_test import VIDEO
|
||||
from utilities.validation import valid_stream_url
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class SubmissionValidationTest(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': 'test.db'},
|
||||
'upload_location': '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 submit(self, kind, name):
|
||||
if kind == 'photo':
|
||||
return self.client.post('/upload/photo', data={
|
||||
'name': name, 'files[]': (BytesIO(PNG), 'photo.png')})
|
||||
if kind == 'video':
|
||||
return self.client.post('/upload/video', data={
|
||||
'name': name, 'files[]': (BytesIO(VIDEO), 'video.mp4')})
|
||||
if kind == 'stream':
|
||||
return self.client.post('/configure/stream', data={
|
||||
'buttonName': name, 'streamURL': 'https://example.com/stream'})
|
||||
return self.client.post('/youtube/download', data={
|
||||
'media_name': name, 'youtube_url': 'https://youtu.be/video'})
|
||||
|
||||
def test_duplicate_catalog_names_rejected_for_all_workflows(self):
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
db.execute('INSERT INTO media (media_name, media_uri) VALUES (?, ?)', ['Straße', 'old'])
|
||||
db.commit()
|
||||
for kind in ('photo', 'video', 'stream', 'youtube'):
|
||||
with self.subTest(kind=kind):
|
||||
response = self.submit(kind, ' STRASSE ')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
message = response.json['error'] if response.is_json else response.get_data(as_text=True)
|
||||
self.assertIn('already in use', message)
|
||||
self.assertEqual(list((self.workdir / 'Images').glob('*')), [])
|
||||
self.assertEqual(list((self.workdir / 'Videos').glob('*')), [])
|
||||
|
||||
def test_pending_and_downloading_jobs_reserve_names_but_failed_jobs_do_not(self):
|
||||
for status in ('pending', 'downloading', 'failed', 'downloaded'):
|
||||
with self.subTest(status=status):
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
db.execute('DELETE FROM youtube_download_job')
|
||||
db.execute('DELETE FROM media')
|
||||
db.execute('INSERT INTO youtube_download_job (youtube_download_job_url, '
|
||||
'youtube_download_job_media_name, youtube_download_job_status) VALUES (?, ?, ?)',
|
||||
['https://youtu.be/video', 'Reserved', status])
|
||||
db.commit()
|
||||
for kind in ('photo', 'video', 'stream', 'youtube'):
|
||||
response = self.submit(kind, ' reserved ')
|
||||
if status in ('pending', 'downloading'):
|
||||
self.assertEqual(response.status_code, 400, kind)
|
||||
else:
|
||||
self.assertIn(response.status_code, (200, 303), kind)
|
||||
# Isolate each submission so successful routes do not reserve the name for the next.
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
db.execute('DELETE FROM media')
|
||||
db.execute("DELETE FROM youtube_download_job WHERE youtube_download_job_status = 'pending'")
|
||||
db.commit()
|
||||
|
||||
def test_names_must_be_nonempty_bounded_and_without_controls(self):
|
||||
for name in ('', ' ', 'x' * 121, 'x\x00y', 'x\n'):
|
||||
for kind in ('photo', 'video', 'stream', 'youtube'):
|
||||
with self.subTest(name=name, kind=kind):
|
||||
self.assertEqual(self.submit(kind, name).status_code, 400)
|
||||
|
||||
def test_stream_url_validation_and_error_preserves_input(self):
|
||||
for url in ('https://example.com/live', 'rtsp://192.168.1.20:8554/live',
|
||||
'rtmp://localhost/live', 'udp://239.1.1.1:1234', 'tcp://[::1]:8000'):
|
||||
self.assertTrue(valid_stream_url(url), url)
|
||||
for url in ('', 'file:///etc/passwd', 'https://', 'https://host:bad/path',
|
||||
'https://a b/test', 'http://example.com\\@evil/', 'https://-bad.host/test',
|
||||
'http://host:0/', 'concat:foo', 'http://host/\x00'):
|
||||
self.assertFalse(valid_stream_url(url), repr(url))
|
||||
response = self.client.post('/configure/stream', data={
|
||||
'buttonName': '<Name>', 'streamURL': 'not-a-url'})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn(b'<Name>', response.data)
|
||||
self.assertIn(b'network stream URL', response.data)
|
||||
self.assertEqual(self.client.post('/configure/stream', data={}).status_code, 400)
|
||||
|
||||
def test_stream_is_atomic_and_checkbox_optional(self):
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
db.execute("""CREATE TRIGGER reject_option BEFORE INSERT ON media_playback_option
|
||||
BEGIN SELECT RAISE(ABORT, 'option failure'); END""")
|
||||
db.commit()
|
||||
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||
response = self.client.post('/configure/stream', data={
|
||||
'buttonName': 'Stream', 'streamURL': 'rtsp://example.com/live', 'fullScreen': 'on'})
|
||||
self.assertEqual(response.status_code, 503)
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
|
||||
response = self.client.post('/configure/stream', data={
|
||||
'buttonName': 'Stream', 'streamURL': 'rtsp://example.com/live'})
|
||||
self.assertEqual(response.status_code, 303)
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
self.assertEqual(db.execute('SELECT media_name, media_uri FROM media').fetchall(),
|
||||
[('Stream', 'rtsp://example.com/live')])
|
||||
|
||||
def test_youtube_urls_require_specific_video(self):
|
||||
from blueprints.youtube_download.youtube_download import valid_youtube_url
|
||||
for url in ('https://youtu.be/abc', 'https://youtube.com/watch?v=abc',
|
||||
'https://www.youtube.com/shorts/abc', 'https://youtube.com/live/abc',
|
||||
'https://youtube.com/embed/abc'):
|
||||
self.assertTrue(valid_youtube_url(url), url)
|
||||
for url in ('https://youtube.com/watch', 'https://youtube.com/watch?v=',
|
||||
'https://youtube.com/playlist?list=abc', 'https://youtube.com/channel/abc',
|
||||
'https://youtube.com/unrelated', 'https://youtu.be/',
|
||||
'https://youtube.com/watch?v=abc&v=def', 'https://youtube.com/watch?v=abc%0A'):
|
||||
self.assertFalse(valid_youtube_url(url), url)
|
||||
|
||||
def test_uploads_reject_invalid_and_mismatched_content(self):
|
||||
cases = [('/upload/photo', b'not an image', 'image.png'),
|
||||
('/upload/photo', VIDEO, 'image.png'),
|
||||
('/upload/photo', PNG, 'image.jpg'),
|
||||
('/upload/video', b'not a video', 'video.mp4'),
|
||||
('/upload/video', PNG, 'video.mp4')]
|
||||
for route, content, filename in cases:
|
||||
with self.subTest(route=route, filename=filename):
|
||||
response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename)})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json['status'], 'FAILED')
|
||||
self.assertEqual(list((self.workdir / 'Images').glob('*')), [])
|
||||
self.assertEqual(list((self.workdir / 'Videos').glob('*')), [])
|
||||
with closing(sqlite3.connect(self.database)) as db:
|
||||
self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
|
||||
|
||||
def test_audio_only_and_truncated_files_are_rejected(self):
|
||||
buffer = BytesIO()
|
||||
with wave.open(buffer, 'wb') as audio:
|
||||
audio.setnchannels(1)
|
||||
audio.setsampwidth(2)
|
||||
audio.setframerate(8000)
|
||||
audio.writeframes(b'\x00\x00' * 800)
|
||||
for route, content, filename in (
|
||||
('/upload/video', buffer.getvalue(), 'audio.mp4'),
|
||||
('/upload/photo', PNG[:35], 'truncated.png'),
|
||||
('/upload/video', VIDEO[:80], 'truncated.mp4')
|
||||
):
|
||||
with self.subTest(filename=filename):
|
||||
response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename)})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(list((self.workdir / 'Images').glob('*')), [])
|
||||
self.assertEqual(list((self.workdir / 'Videos').glob('*')), [])
|
||||
|
||||
def test_upload_unexpected_extra_files_are_rejected(self):
|
||||
for route, content, filename in (('/upload/photo', PNG, 'photo.png'),
|
||||
('/upload/video', VIDEO, 'video.mp4')):
|
||||
response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename),
|
||||
'extra': (BytesIO(b'bad'), 'other.txt')})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
def test_probe_unavailable_or_timed_out_is_helpful_and_cleans_up(self):
|
||||
for error in (FileNotFoundError(), subprocess.TimeoutExpired('ffprobe', 30)):
|
||||
with self.subTest(error=error):
|
||||
with patch('utilities.validation.subprocess.run', side_effect=error):
|
||||
with self.assertLogs(self.app.logger, level='WARNING'):
|
||||
response = self.submit('photo', 'Name')
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertIn('validat', response.json['error'])
|
||||
self.assertEqual(list((self.workdir / 'Images').glob('*')), [])
|
||||
|
||||
def test_corrupt_or_excessive_image_metadata_is_rejected(self):
|
||||
for width, height in ((0, 10), (10000, 10000)):
|
||||
report = json.dumps({'format': {'format_name': 'png_pipe'}, 'streams': [{
|
||||
'codec_type': 'video', 'codec_name': 'png', 'width': width, 'height': height
|
||||
}]}).encode()
|
||||
with self.subTest(width=width, height=height):
|
||||
with patch('utilities.validation.subprocess.run', return_value=subprocess.CompletedProcess([], 0, report)):
|
||||
response = self.submit('photo', 'Name')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn('dimensions', response.json['error'])
|
||||
self.assertEqual(list((self.workdir / 'Images').glob('*')), [])
|
||||
|
||||
def test_database_failure_reports_error_for_forms_and_listing(self):
|
||||
with patch('utilities.database.sqlite.SQLite.query', side_effect=sqlite3.OperationalError('secret')):
|
||||
for kind in ('stream', 'youtube'):
|
||||
with self.subTest(kind=kind):
|
||||
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||
response = self.submit(kind, 'Name')
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertIn(b'database', response.data)
|
||||
self.assertNotIn(b'secret', response.data)
|
||||
for endpoint in ('/youtube/jobs', '/media', '/media/status'):
|
||||
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||
response = self.client.get(endpoint)
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertNotIn(b'secret', response.data)
|
||||
|
||||
def test_concurrent_submissions_allow_only_one_name(self):
|
||||
barrier = threading.Barrier(2)
|
||||
def submit(kind):
|
||||
with self.app.test_client() as client:
|
||||
barrier.wait(timeout=5)
|
||||
if kind == 'youtube':
|
||||
return client.post('/youtube/download', data={
|
||||
'media_name': 'Same Name', 'youtube_url': 'https://youtu.be/video'}).status_code
|
||||
return client.post('/configure/stream', data={
|
||||
'buttonName': 'same name', 'streamURL': 'https://example.com/stream'}).status_code
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
results = list(executor.map(submit, ('youtube', 'stream')))
|
||||
self.assertCountEqual(results, [303, 400])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -110,8 +110,8 @@ class UploadPhotoTest(unittest.TestCase):
|
||||
self.assert_no_files_or_records()
|
||||
|
||||
def test_filenames_and_names_cannot_escape_or_overwrite_storage(self):
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.post_image(name='../../Display name', filename='../../photo.png').status_code, 200)
|
||||
for index in range(2):
|
||||
self.assertEqual(self.post_image(name=f'../../Display name {index}', filename='../../photo.png').status_code, 200)
|
||||
paths = list(self.storage.iterdir())
|
||||
self.assertEqual(len(paths), 2)
|
||||
self.assertTrue(all(path.name.startswith('upload-') for path in paths))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from contextlib import closing
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import json
|
||||
import os
|
||||
@@ -15,6 +16,7 @@ from blueprints.upload_video.upload_video import MAX_VIDEO_SIZE
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VIDEO = base64.b64decode('AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAGW1kYXQAAAGzABAHAAABthYFGCPbfgAAAz9tb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAD6AABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACanRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAD6AAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAEAAAABAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAA+gAAAAAAAEAAAAAAeJtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAEAAAABAAFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAGNbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABTXN0YmwAAADpc3RzZAAAAAAAAAABAAAA2W1wNHYAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAEAAQAEgAAABIAAAAAAAAAAESTGF2YzYzLjEuMTAyIG1wZWc0AAAAAAAAAAAAAAAAAAAY//8AAABfZXNkcwAAAAADgICATgABAASAgIBAIBEAAAAAAw1AAAAAiAWAgIAuAAABsAEAAAG1iRMAAAEAAAABIADEjYgADQCEAhRjAAABskxhdmM2My4xLjEwMgaAgIABAgAAABBwYXNwAAAAAQAAAAEAAAAUYnRydAAAAAAAAw1AAAAAiAAAABhzdHRzAAAAAAAAAAEAAAABAABAAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAARAAAAAQAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYXVkdGEAAABZbWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAsaWxzdAAAACSpdG9vAAAAHGRhdGEAAAABAAAAAExhdmY2My4xLjEwMg==')
|
||||
|
||||
|
||||
class UploadVideoTest(unittest.TestCase):
|
||||
@@ -39,7 +41,7 @@ class UploadVideoTest(unittest.TestCase):
|
||||
self.app.config['TESTING'] = True
|
||||
self.client = self.app.test_client()
|
||||
|
||||
def post_video(self, content=b'example-video', name='Video', filename='clip.mp4'):
|
||||
def post_video(self, content=VIDEO, name='Video', filename='clip.mp4'):
|
||||
return self.client.post('/upload/video', data={
|
||||
'name': name, 'files[]': (BytesIO(content), filename)
|
||||
})
|
||||
@@ -66,7 +68,7 @@ class UploadVideoTest(unittest.TestCase):
|
||||
name, uri = db.execute('SELECT media_name, media_uri FROM media').fetchone()
|
||||
self.assertEqual(name, 'Sunday video')
|
||||
self.assertEqual(Path(uri).parent, self.storage)
|
||||
self.assertEqual(Path(uri).read_bytes(), b'example-video')
|
||||
self.assertEqual(Path(uri).read_bytes(), VIDEO)
|
||||
self.assertEqual(Path(uri).suffix, '.mp4')
|
||||
self.assertEqual(len(list(self.storage.iterdir())), 1)
|
||||
|
||||
@@ -90,12 +92,12 @@ class UploadVideoTest(unittest.TestCase):
|
||||
self.assert_no_files_or_records()
|
||||
|
||||
def test_file_limit_exact_boundary_and_one_byte_over(self):
|
||||
with patch('blueprints.upload_video.upload_video.MAX_VIDEO_SIZE', 16):
|
||||
response = self.post_video(content=b'x' * 17)
|
||||
with patch('blueprints.upload_video.upload_video.MAX_VIDEO_SIZE', len(VIDEO)):
|
||||
response = self.post_video(content=VIDEO + b'x')
|
||||
self.assertEqual(response.status_code, 413)
|
||||
self.assertEqual(response.json['status'], 'FAILED')
|
||||
self.assert_no_files_or_records()
|
||||
self.assertEqual(self.post_video(content=b'x' * 16).status_code, 200)
|
||||
self.assertEqual(self.post_video().status_code, 200)
|
||||
|
||||
def test_request_limit_rejects_oversized_body_with_json(self):
|
||||
with patch('blueprints.upload_video.upload_video.MAX_VIDEO_SIZE', 16):
|
||||
@@ -109,8 +111,8 @@ class UploadVideoTest(unittest.TestCase):
|
||||
self.assertEqual(self.app.config['MAX_CONTENT_LENGTH'], 3 * 1024 ** 3)
|
||||
|
||||
def test_filenames_and_names_cannot_escape_or_overwrite_storage(self):
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.post_video(name='../../Display name', filename='../../clip.mp4').status_code, 200)
|
||||
for index in range(2):
|
||||
self.assertEqual(self.post_video(name=f'../../Display name {index}', filename='../../clip.mp4').status_code, 200)
|
||||
paths = list(self.storage.iterdir())
|
||||
self.assertEqual(len(paths), 2)
|
||||
self.assertTrue(all(path.name.startswith('upload-') for path in paths))
|
||||
|
||||
@@ -226,6 +226,19 @@ class YouTubeDownloadJobTest(unittest.TestCase):
|
||||
"SELECT COUNT(*) FROM youtube_download_job WHERE youtube_download_job_status = 'failed'"
|
||||
).fetchone(), (4,))
|
||||
|
||||
def test_worker_rejects_a_legacy_catalog_name_collision(self):
|
||||
self.insert_job()
|
||||
self.db.execute("UPDATE youtube_download_job SET youtube_download_job_media_name = 'VIDEO'")
|
||||
self.db.execute("INSERT INTO media (media_name, media_uri) VALUES ('Video', 'existing')")
|
||||
self.db.commit()
|
||||
with patch('youtube_downloader.download_video', return_value=(self.workdir / 'video.mp4', 'Title')):
|
||||
with self.assertLogs('youtube_downloader', level='ERROR'):
|
||||
self.assertFalse(process_next_job(self.db, self.workdir, max_retries=0))
|
||||
self.assertEqual(self.db.execute('SELECT media_name, media_uri FROM media').fetchall(), [('Video', 'existing')])
|
||||
self.assertEqual(self.db.execute(
|
||||
'SELECT youtube_download_job_status, youtube_download_job_retry_count FROM youtube_download_job'
|
||||
).fetchone(), ('failed', 1))
|
||||
|
||||
def test_claims_oldest_pending_job_only_once(self):
|
||||
first = self.insert_job()
|
||||
second = self.insert_job()
|
||||
|
||||
+3
-2
@@ -1,12 +1,13 @@
|
||||
from flask import g, current_app
|
||||
from .database.sqlite import SQLite
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
def get_db():
|
||||
db = getattr(g, "_database", None)
|
||||
|
||||
if db is None:
|
||||
if str(current_app.config["config"]["database"]["type"]).casefold() == "SQLite".casefold():
|
||||
db = g._database = SQLite(current_app.config["config"]["database"]["name"])
|
||||
database = Path(current_app.config['CONFIG_DIRECTORY']) / current_app.config['config']['database']['name']
|
||||
db = g._database = SQLite(str(database))
|
||||
|
||||
return db
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Validation shared by media submission routes and the download worker."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import unicodedata
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
MAX_MEDIA_NAME_LENGTH = 120
|
||||
DUPLICATE_NAME_MESSAGE = 'That media name is already in use or reserved by a download. Please choose another name.'
|
||||
|
||||
|
||||
class ValidationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class ValidationUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def validate_media_name(value):
|
||||
name = unicodedata.normalize('NFC', value)
|
||||
if any(unicodedata.category(char).startswith('C') for char in name):
|
||||
raise ValidationError('Media names cannot contain control characters.')
|
||||
name = name.strip()
|
||||
if not name:
|
||||
raise ValidationError('Please enter a media name.')
|
||||
if len(name) > MAX_MEDIA_NAME_LENGTH:
|
||||
raise ValidationError(f'Media names must be at most {MAX_MEDIA_NAME_LENGTH} characters.')
|
||||
return name
|
||||
|
||||
|
||||
def name_key(value):
|
||||
return unicodedata.normalize('NFC', value or '').strip().casefold()
|
||||
|
||||
|
||||
def ensure_catalog_name_available(connection, name):
|
||||
key = name_key(name)
|
||||
existing = connection.execute('SELECT media_name FROM media')
|
||||
if any(name_key(row[0]) == key for row in existing):
|
||||
raise ValidationError(DUPLICATE_NAME_MESSAGE)
|
||||
|
||||
|
||||
def ensure_name_available(connection, name):
|
||||
"""Call while holding a write transaction so checks and insertion are atomic."""
|
||||
ensure_catalog_name_available(connection, name)
|
||||
key = name_key(name)
|
||||
jobs = connection.execute("""
|
||||
SELECT youtube_download_job_media_name FROM youtube_download_job
|
||||
WHERE youtube_download_job_status IN ('pending', 'downloading')
|
||||
""")
|
||||
if any(name_key(row[0]) == key for row in jobs):
|
||||
raise ValidationError(DUPLICATE_NAME_MESSAGE)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def write_transaction(db):
|
||||
db.query('BEGIN IMMEDIATE')
|
||||
try:
|
||||
yield db
|
||||
db.query('COMMIT')
|
||||
except BaseException:
|
||||
try:
|
||||
db.query('ROLLBACK')
|
||||
except sqlite3.Error:
|
||||
pass # Keep the original failure; SQLite may already have rolled back.
|
||||
raise
|
||||
|
||||
|
||||
def valid_stream_url(value):
|
||||
"""Accept network streams, not local paths or arbitrary FFmpeg protocols."""
|
||||
if not value or any(char.isspace() or unicodedata.category(char).startswith('C') for char in value):
|
||||
return False
|
||||
if '\\' in value:
|
||||
return False
|
||||
try:
|
||||
url = urlsplit(value)
|
||||
if url.scheme.lower() not in {'http', 'https', 'rtsp', 'rtmp', 'rtmps', 'udp', 'tcp'}:
|
||||
return False
|
||||
hostname = url.hostname
|
||||
if not hostname or url.port == 0:
|
||||
return False
|
||||
if any(char in hostname for char in '/?#%@'):
|
||||
return False
|
||||
# IPv6 is parsed by urlsplit; hostnames must not contain stray brackets.
|
||||
if ':' not in hostname:
|
||||
hostname = hostname.encode('idna').decode('ascii')
|
||||
if len(hostname) > 253 or not all(
|
||||
re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?', part)
|
||||
for part in hostname.rstrip('.').split('.')
|
||||
):
|
||||
return False
|
||||
return True
|
||||
except (ValueError, UnicodeError):
|
||||
return False
|
||||
|
||||
|
||||
IMAGE_CODECS = {
|
||||
'.jpg': {'mjpeg'}, '.jpeg': {'mjpeg'}, '.png': {'png', 'apng'},
|
||||
'.webp': {'webp'}, '.bmp': {'bmp'}, '.tif': {'tiff'}, '.tiff': {'tiff'},
|
||||
'.gif': {'gif'},
|
||||
}
|
||||
|
||||
|
||||
def validate_upload_content(path, kind, extension):
|
||||
"""Probe local content, rejecting mismatched/invalid files and network inputs."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['ffprobe', '-v', 'error', '-protocol_whitelist', 'file,pipe',
|
||||
'-show_entries', 'format=format_name:stream=codec_type,codec_name,width,height',
|
||||
'-of', 'json', str(Path(path))],
|
||||
check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
timeout=30
|
||||
)
|
||||
metadata = json.loads(result.stdout)
|
||||
except FileNotFoundError as error:
|
||||
raise ValidationUnavailable('File validation is unavailable. Please contact the administrator.') from error
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
raise ValidationUnavailable('Unable to validate the uploaded file. Please try again.') from error
|
||||
except (subprocess.CalledProcessError, ValueError) as error:
|
||||
raise ValidationError(f'The uploaded file is not a valid {kind}.') from error
|
||||
streams = metadata.get('streams', [])
|
||||
video_streams = [stream for stream in streams if stream.get('codec_type') == 'video']
|
||||
formats = set(metadata.get('format', {}).get('format_name', '').split(','))
|
||||
if kind == 'image':
|
||||
if not video_streams or video_streams[0].get('codec_name') not in IMAGE_CODECS[extension]:
|
||||
raise ValidationError('The image content does not match its file extension or is invalid.')
|
||||
elif not video_streams or formats.intersection({'image2', 'image2pipe', 'png_pipe', 'jpeg_pipe',
|
||||
'webp_pipe', 'bmp_pipe', 'tiff_pipe', 'gif', 'apng'}):
|
||||
raise ValidationError('The uploaded file must contain a valid video, not an image or audio-only file.')
|
||||
|
||||
width = video_streams[0].get('width', 0)
|
||||
height = video_streams[0].get('height', 0)
|
||||
if kind == 'image' and (not isinstance(width, int) or not isinstance(height, int)
|
||||
or width <= 0 or height <= 0 or width * height > 50_000_000):
|
||||
raise ValidationError('The image dimensions are invalid or exceed 50 megapixels.')
|
||||
# Probe metadata alone can accept a truncated image. Decode one frame; this is
|
||||
# bounded and avoids decoding an entire large video or animated image.
|
||||
try:
|
||||
subprocess.run(
|
||||
['ffmpeg', '-hide_banner', '-v', 'error', '-xerror', '-nostdin',
|
||||
'-protocol_whitelist', 'file,pipe', '-i', str(Path(path)),
|
||||
'-map', '0:v:0', '-frames:v', '1', '-f', 'null', '-'],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30
|
||||
)
|
||||
except FileNotFoundError as error:
|
||||
raise ValidationUnavailable('File validation is unavailable. Please contact the administrator.') from error
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
raise ValidationUnavailable('Unable to validate the uploaded file. Please try again.') from error
|
||||
except subprocess.CalledProcessError as error:
|
||||
raise ValidationError(f'The uploaded file is not a valid {kind}.') from error
|
||||
@@ -8,6 +8,8 @@ import sqlite3
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from utilities.validation import ensure_catalog_name_available, validate_media_name
|
||||
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -74,9 +76,12 @@ def process_next_job(db, storage, max_retries=3):
|
||||
try:
|
||||
LOGGER.info('Downloading job %s: %s', job_id, url)
|
||||
path, title = download_video(job_id, url, storage)
|
||||
media_name = requested_name.strip() or title
|
||||
# Insert the media and finish the job together, or roll both changes back.
|
||||
media_name = validate_media_name(requested_name.strip() or title)
|
||||
# Check existing catalog names under the same write lock as completion.
|
||||
# The job's own reservation is intentionally not treated as a conflict.
|
||||
with db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
ensure_catalog_name_available(db, media_name)
|
||||
db.execute(
|
||||
'INSERT INTO media (media_name, media_uri) VALUES (?, ?)',
|
||||
[media_name, str(path)]
|
||||
|
||||
Reference in new issue
Block a user