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(): 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