diff --git a/partitioncloud/modules/albums.py b/partitioncloud/modules/albums.py index 7cb71a4..7f1334e 100644 --- a/partitioncloud/modules/albums.py +++ b/partitioncloud/modules/albums.py @@ -3,7 +3,9 @@ Albums module """ import os +import pypdf import shutil + from uuid import uuid4 from typing import TypeVar @@ -263,6 +265,12 @@ def add_partition(album_uuid): else: partition_type = "file" + try: + pypdf.PdfReader(request.files["file"]) + request.files["file"].seek(0) + except (pypdf.errors.PdfReadError, pypdf.errors.PdfStreamError): + error = _("Invalid PDF file") + if error is not None: flash(error) return redirect(request.referrer) diff --git a/partitioncloud/modules/thumbnails.py b/partitioncloud/modules/thumbnails.py index 36dc7c1..2513af7 100644 --- a/partitioncloud/modules/thumbnails.py +++ b/partitioncloud/modules/thumbnails.py @@ -2,6 +2,7 @@ Thumbnails """ import os +import pypdf from flask import current_app, abort, Blueprint, send_file @@ -14,13 +15,18 @@ def generate_thumbnail(source, dest): """ Generates a thumbnail with 'convert' (ImageMagick) """ - os.system( - f'/usr/bin/convert -thumbnail\ - "178^>" -background white -alpha \ - remove -crop 178x178+0+0 \ - {source}[0] \ - {dest}' + try: + pypdf.PdfReader(source) # Check if file is really a PDF + except (pypdf.errors.PdfReadError, pypdf.errors.PdfStreamError): + return + + command = ( + f"gs -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 \ + -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=png16m -dBackgroundColor=16#FFFFFF -dTextAlphaBits=4 \ + -dGraphicsAlphaBits=4 -r72x72 -dPrinted=false -dFirstPage=1 -dPDFFitPage -g356x356 \ + -dLastPage=1 -sOutputFile={dest} {source}" ) + os.system(command) def serve_thumbnail(partition_file, thumbnail_file): """ @@ -32,6 +38,9 @@ def serve_thumbnail(partition_file, thumbnail_file): if not os.path.exists(thumbnail_file): generate_thumbnail(partition_file, thumbnail_file) + if not os.path.exists(thumbnail_file): + abort(404) + return send_file(thumbnail_file)