from pathlib import Path import sqlite3 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) MULTIPART_OVERHEAD = 1024 ** 2 IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tif', '.tiff', '.gif'} upload_photo_bp = Blueprint('upload_photo', __name__, url_prefix='/upload', template_folder='.') @upload_photo_bp.before_request def set_upload_limit(): if request.method == 'POST': request.max_content_length = MAX_IMAGE_SIZE + MULTIPART_OVERHEAD @upload_photo_bp.errorhandler(RequestEntityTooLarge) def upload_too_large(error): return jsonify(status='FAILED', error='The image must be no larger than 100MB.'), 413 @upload_photo_bp.route('/photo', methods=['GET', 'POST']) def get_page(): if request.method == 'GET': return render_template('upload_photo.html', max_image_size=MAX_IMAGE_SIZE) return upload() def upload(): 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 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 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}' partial = storage / f'upload-{token}.part' saved = False try: storage.mkdir(parents=True, exist_ok=True) size = 0 with partial.open('xb') as output: while chunk := image.stream.read(1024 ** 2): size += len(chunk) if size > MAX_IMAGE_SIZE: raise RequestEntityTooLarge() output.write(chunk) if size == 0: return jsonify(status='FAILED', error='The image file is empty.'), 400 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 finally: for path in ([partial] if saved else [partial, destination]): try: path.unlink(missing_ok=True) except OSError: current_app.logger.exception('Unable to clean up upload file %s', path)