import hashlib from pathlib import Path import subprocess from tempfile import NamedTemporaryFile from urllib.parse import urlsplit from uuid import uuid4 from flask import Blueprint, abort, current_app, jsonify, redirect, render_template, request, send_file, url_for from utilities.tools import get_db from utilities.media_deletion import confirmation_version, deletion_plan from utilities.validation import write_transaction 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('//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) def deletion_media(db, media_id): rows = db.query('SELECT media_id, media_name, media_uri, media_active, media_default ' 'FROM media WHERE media_id = ?', [media_id])[1] if not rows: abort(404) return rows[0] def restore_staged_file(staged, source): try: if staged is not None and staged.exists(): if source.exists() or source.is_symlink(): raise OSError('Original file location is occupied; recovery file retained') staged.rename(source) except OSError: current_app.logger.exception('Restore media manually from %s to %s', staged, source) @media_library_bp.route('//delete', methods=['GET', 'POST']) def delete_media(media_id): db = get_db() directory = current_app.config['CONFIG_DIRECTORY'] config = current_app.config['config'] staged = None source = None legacy_thumbnail = None try: if request.method == 'GET': media = deletion_media(db, media_id) plan = deletion_plan(db, media, directory, config) return render_template('media_delete.html', media=media, plan=plan, version=confirmation_version(media, plan)) # Reject cross-site browser submissions to this destructive endpoint. origin = request.headers.get('Origin') if (request.headers.get('Sec-Fetch-Site') == 'cross-site' or (origin and origin.rstrip('/') != request.host_url.rstrip('/'))): abort(403) with write_transaction(db): media = deletion_media(db, media_id) plan = deletion_plan(db, media, directory, config) version = confirmation_version(media, plan) if request.form.get('confirm') != 'yes': return render_template('media_delete.html', media=media, plan=plan, version=version, error='Please confirm the deletion using the button below.'), 400 if request.form.get('version') != version: return render_template('media_delete.html', media=media, plan=plan, version=version, error='This media or its storage has changed. Please review and confirm again.'), 409 preview = local_preview_source(media[2]) if preview is not None: stat = preview.stat() legacy_thumbnail = hashlib.sha256( f'{media_id}:{preview}:{stat.st_mtime_ns}:{stat.st_size}'.encode() ).hexdigest() + '.png' source = plan['path'] if source is not None: # Rename within the same directory so a database failure can be undone. staged = source.with_name(f'.deleting-{uuid4().hex}-{source.name}') source.rename(staged) db.query('DELETE FROM media_playback_option WHERE media_id = ?', [media_id]) db.query('DELETE FROM media WHERE media_id = ?', [media_id]) except (OSError, RuntimeError): restore_staged_file(staged, source) current_app.logger.exception('Unable to prepare deletion of media %s', media_id) return render_template('media_delete.html', error='Unable to access or remove the stored file. ' 'The media record was not deleted. Please try again or contact the administrator.'), 500 except BaseException: restore_staged_file(staged, source) raise # Only destroy the staged file after the database transaction has committed. if staged is not None: try: staged.unlink() except OSError: current_app.logger.exception('Media record %s deleted, but storage cleanup is needed at %s', media_id, staged) return render_template('media_delete.html', error='The database record was deleted, but its file ' 'could not be removed. Storage has not been freed; contact the administrator ' 'to clean up the retained file (details are in the server log).'), 500 cache = Path(directory) / '.thumbnails' try: if not cache.is_symlink(): thumbnails = list(cache.glob(f'{media_id}-*.png')) if legacy_thumbnail: thumbnails.append(cache / legacy_thumbnail) for path in thumbnails: path.unlink(missing_ok=True) except OSError: current_app.logger.warning('Could not clean cached thumbnails for deleted media %s', media_id) return redirect(url_for('media_library.media_list'), code=303) @media_library_bp.route('//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'{media_id}-{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)