From a5ae6d8925c29ee3424b9c378be4c7317430b3e6 Mon Sep 17 00:00:00 2001 From: Roland Date: Fri, 16 Dec 2022 08:14:31 -0700 Subject: [PATCH] Do not index the contents of a PDF if it is too large. --- wrolpi/common.py | 1 + wrolpi/files/api.py | 2 +- wrolpi/files/indexers.py | 15 +++++++++------ wrolpi/files/models.py | 11 +++++------ wrolpi/files/test/test_lib.py | 13 +++++++++++++ wrolpi/vars.py | 2 ++ 6 files changed, 31 insertions(+), 13 deletions(-) diff --git a/wrolpi/common.py b/wrolpi/common.py index 674d42c2..d2b69a1f 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -95,6 +95,7 @@ __all__ = [ 'background_task', 'get_warn_once', 'ordered_unique_list', + 'truncate_generator_bytes', ] # Base is used for all SQLAlchemy models. diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index 5cbe33e3..56d5dd28 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -127,7 +127,7 @@ async def post_search_files(_: Request, body: schema.FilesSearchRequest): @openapi.response(HTTPStatus.OK, schema.DirectoriesResponse) @openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse) @validate(schema.DirectoriesRequest) -def directories(_, body: schema.DirectoriesRequest): +def post_directories(_, body: schema.DirectoriesRequest): path = get_media_directory() / (body.search_str or '') search_str = str(path) dirs = lib.get_matching_directories(search_str) diff --git a/wrolpi/files/indexers.py b/wrolpi/files/indexers.py index 1b98128a..7533ab4f 100644 --- a/wrolpi/files/indexers.py +++ b/wrolpi/files/indexers.py @@ -5,7 +5,7 @@ from collections import defaultdict from typing import List, Type, Tuple, Generator from zipfile import ZipFile -from wrolpi.vars import PYTEST +from wrolpi.vars import PYTEST, FILE_MAX_PDF_SIZE, FILE_MAX_TEXT_SIZE try: from PyPDF2 import PdfReader @@ -16,8 +16,7 @@ from wrolpi.common import logger, truncate_generator_bytes logger = logger.getChild(__name__) -__all__ = ['Indexer', 'DefaultIndexer', 'ZipIndexer', 'TextIndexer', 'find_indexer', 'register_indexer', - 'MAX_TEXT_FILE_BYTES'] +__all__ = ['Indexer', 'DefaultIndexer', 'ZipIndexer', 'TextIndexer', 'find_indexer', 'register_indexer'] class Indexer(object): @@ -103,7 +102,6 @@ class ZipIndexer(Indexer, ABC): WORD_SPLITTER = re.compile(r"([\w’'-]+)") -MAX_TEXT_FILE_BYTES = 100_000 @register_indexer('text/plain') @@ -143,12 +141,17 @@ class PDFIndexer(Indexer, ABC): @classmethod def create_index(cls, file): - path = file.path.path if hasattr(file.path, 'path') else file.path + path: pathlib.Path = file.path.path if hasattr(file.path, 'path') else file.path a = cls.get_title(file) + + if path.stat().st_size > FILE_MAX_PDF_SIZE: + logger.warning(f'PDF too large to fully index: {path}') + return a, None, None, None + words = '' try: # PDFs are complex, don't fail to create title index if text extraction fails. - words = '\n'.join(truncate_generator_bytes(cls.get_words(path), MAX_TEXT_FILE_BYTES)) + words = '\n'.join(truncate_generator_bytes(cls.get_words(path), FILE_MAX_TEXT_SIZE)) except Exception as e: logger.error(f'Failed to index {path}', exc_info=e) if PYTEST: diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index cae70b07..92a8912c 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -7,9 +7,8 @@ import wrolpi.files.indexers from wrolpi.common import Base, ModelHelper, get_media_directory, tsvector, logger, get_model_by_table_name, \ truncate_object_bytes from wrolpi.dates import TZDateTime, from_timestamp, now -from wrolpi.files.indexers import MAX_TEXT_FILE_BYTES from wrolpi.media_path import MediaPathType -from wrolpi.vars import PYTEST +from wrolpi.vars import PYTEST, FILE_MAX_TEXT_SIZE logger = logger.getChild(__name__) @@ -103,10 +102,10 @@ class File(ModelHelper, Base): # Only read the contents of the file once. start = now() a_text, b_text, c_text, d_text = indexer.create_index(self) - self.a_text = truncate_object_bytes(a_text, MAX_TEXT_FILE_BYTES) - self.b_text = truncate_object_bytes(b_text, MAX_TEXT_FILE_BYTES) - self.c_text = truncate_object_bytes(c_text, MAX_TEXT_FILE_BYTES) - self.d_text = truncate_object_bytes(d_text, MAX_TEXT_FILE_BYTES) + self.a_text = truncate_object_bytes(a_text, FILE_MAX_TEXT_SIZE) + self.b_text = truncate_object_bytes(b_text, FILE_MAX_TEXT_SIZE) + self.c_text = truncate_object_bytes(c_text, FILE_MAX_TEXT_SIZE) + self.d_text = truncate_object_bytes(d_text, FILE_MAX_TEXT_SIZE) if (total_seconds := (now() - start).total_seconds()) > 1: logger.info(f'Indexing {self.path} took {total_seconds} seconds') diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index c012e62f..ed172c5b 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -496,6 +496,19 @@ def test_pdf_indexer(example_pdf): assert d_text == 'Page one\nPage two' +def test_pdf_indexer_max_size(example_pdf): + """The contents of a large PDF are not indexed.""" + example_pdf.write_bytes(example_pdf.read_bytes() * 5000) + + file = File(path=example_pdf) + + a_text, b_text, c_text, d_text = indexers.PDFIndexer.create_index(file) + + # The file name is still indexed. + assert a_text == ['example', 'pdf'] + assert d_text is None + + def test_get_mimetype(example_epub, example_mobi, example_pdf, image_file, video_file): assert lib.get_mimetype(example_epub) == 'application/epub+zip' assert lib.get_mimetype(example_mobi) == 'application/x-mobipocket-ebook' diff --git a/wrolpi/vars.py b/wrolpi/vars.py index f33fa206..c742d2d1 100644 --- a/wrolpi/vars.py +++ b/wrolpi/vars.py @@ -74,3 +74,5 @@ API_ACCESS_LOG = truthy_arg(os.environ.get('API_ACCESS_LOG', DOCKERIZED)) API_DEBUG = truthy_arg(os.environ.get('API_DEBUG', False)) FILE_REFRESH_CHUNK_SIZE = int(os.environ.get('FILE_CHUNK_SIZE', 100)) +FILE_MAX_PDF_SIZE = int(os.environ.get('FILE_MAX_PDF_SIZE', 40_000_000)) +FILE_MAX_TEXT_SIZE = int(os.environ.get('FILE_MAX_TEXT_SIZE', 100_000))