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
@@ -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">
|
||||
|
||||
Reference in new issue
Block a user