"""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