diff --git a/modules/archive/__init__.py b/modules/archive/__init__.py index 45c4d570..aa4a2bcd 100644 --- a/modules/archive/__init__.py +++ b/modules/archive/__init__.py @@ -3,7 +3,7 @@ import json import pathlib import tempfile from abc import ABC -from typing import List, Tuple +from typing import List, Tuple, Iterable from selenium import webdriver from sqlalchemy import not_ @@ -242,7 +242,7 @@ def model_archive(file_group: FileGroup, session: Session = None) -> Archive: archive = Archive(file_group_id=file_group_id, file_group=file_group) session.add(archive) archive.validate() - session.flush([archive]) + archive.flush() file_group.title = file_group.a_text = title file_group.d_text = contents @@ -278,10 +278,10 @@ async def archive_modeler(): ).filter(not_(FileGroup.id.in_(list(invalid_archives)))) \ .outerjoin(Archive, Archive.file_group_id == FileGroup.id) \ .limit(20) + results: Iterable[Tuple[FileGroup, Archive]] processed = 0 - for file_group, archive in results: - processed += 1 + for processed, (file_group, archive) in enumerate(results): # Even if indexing fails, we mark it as indexed. We won't retry indexing this. file_group.indexed = True @@ -289,7 +289,6 @@ async def archive_modeler(): with slow_logger(1, f'Modeling archive took %(elapsed)s seconds: {file_group}', logger__=logger): if archive: - archive: Archive try: archive_id = archive.id archive.validate() diff --git a/modules/archive/models.py b/modules/archive/models.py index c511ab61..8c41c0c4 100644 --- a/modules/archive/models.py +++ b/modules/archive/models.py @@ -14,7 +14,7 @@ from wrolpi.db import optional_session from wrolpi.errors import UnknownArchive from wrolpi.files.models import FileGroup from wrolpi.media_path import MediaPathType -from wrolpi.tags import Tag, TagFile +from wrolpi.tags import TagFile from wrolpi.vars import PYTEST from .errors import InvalidArchive @@ -73,6 +73,21 @@ class Archive(Base, ModelHelper): return archive raise UnknownArchive(f'Cannot find Archive with path: {path}') + @staticmethod + def can_model(file_group: FileGroup) -> bool: + from modules.archive.lib import is_singlefile_file + if file_group.mimetype.startswith('text') and is_singlefile_file(file_group.primary_path): + return True + return False + + @staticmethod + def do_model(file_group: FileGroup, session: Session) -> 'Archive': + from modules.archive import model_archive + archive = model_archive(file_group, session) + archive.validate() + file_group.indexed = True + return archive + def my_paths(self, *mimetypes: str) -> List[pathlib.Path]: return self.file_group.my_paths(*mimetypes) diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index 4bc8c80a..d9634c30 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -47,7 +47,7 @@ async def test_no_screenshot(test_directory, test_session): @pytest.mark.asyncio -async def test_no_readability(test_session): +async def test_no_readability(test_directory, test_session): singlefile, readability, screenshot = make_fake_archive_result(readability=False) archive = await model_archive_result('https://example.com', singlefile, readability, screenshot) assert isinstance(archive.singlefile_path, pathlib.Path) diff --git a/modules/videos/models.py b/modules/videos/models.py index 9a3d1ac2..6ae9ed9e 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -94,19 +94,22 @@ class Video(ModelHelper, Base): def delete(self, add_to_skip_list: bool = True): """Remove all files and File records related to this video. Delete this Video record. Add it to it's Channel's skip list.""" - self.file_group.delete() - - if add_to_skip_list: - self.add_to_skip_list() + self.file_group.delete(add_to_skip_list=add_to_skip_list) session = Session.object_session(self) session.delete(self) - def add_to_skip_list(self): - """Add this video to the DownloadManager's skip list.""" - if self.file_group.url: - download_manager.add_to_skip_list(self.file_group.url) - else: - logger.warning(f'{self} cannot be added to skip list because it does not have a URL') + @staticmethod + def can_model(file_group: FileGroup) -> bool: + return file_group.mimetype.startswith('video/') + + @staticmethod + def do_model(file_group: FileGroup, session: Session) -> 'Video': + video = Video(file_group_id=file_group.id, file_group=file_group) + session.add(video) + video.validate() + file_group.indexed = True + video.flush() + return video def get_info_json(self) -> Optional[Dict]: """If this Video has an info_json file, return its contents. Otherwise, return None.""" @@ -613,12 +616,6 @@ class Channel(ModelHelper, Base): ) return config - def get_relative_path(self, path: Path, exists: bool = True): - path = self.directory / path - if exists and not path.exists(): - raise FileNotFoundError(f'{path} does not exist!') - return path - @staticmethod def get_by_path(path: pathlib.Path, session: Session) -> Optional['Channel']: if not path: diff --git a/modules/videos/test/test_common.py b/modules/videos/test/test_common.py index 6bcf12f5..b5aea3c8 100644 --- a/modules/videos/test/test_common.py +++ b/modules/videos/test/test_common.py @@ -185,7 +185,7 @@ async def test_import_channel_downloads(test_async_client, test_session, channel # Creating Download that matches Channel2's URL means they are related. Delete it and it should be re-created. channel2.get_or_create_download(channel2.url, 60, test_session) save_channels_config() - Download.find_by_url(channel2.url).delete(skip=False) + Download.find_by_url(channel2.url).delete(add_to_skip_list=False) test_session.commit() # Missing Download is re-created on import. @@ -217,7 +217,7 @@ async def test_import_channel_downloads(test_async_client, test_session, channel # Get Channels with their Downloads. channels_backup = copy(get_channels_config().channels) # Reset Downloads. Downloads should be recreated from the channels config file. - [i.delete(skip=False) for i in test_session.query(Download).all()] + [i.delete(add_to_skip_list=False) for i in test_session.query(Download).all()] # Write config with Channel Downloads now that the delete() has removed them from the config. get_channels_config().channels = channels_backup import_channels_config() diff --git a/modules/videos/test/test_downloader.py b/modules/videos/test/test_downloader.py index 8af8e7d3..4bd30bf1 100644 --- a/modules/videos/test/test_downloader.py +++ b/modules/videos/test/test_downloader.py @@ -143,7 +143,7 @@ async def test_download_channel(test_session, simple_channel, video_download_man await video_download_manager.wait_for_all_downloads() def reset_downloads(): - [i.delete(skip=False) for i in test_session.query(Download)] + [i.delete(add_to_skip_list=False) for i in test_session.query(Download)] # Let background tasks run. await asyncio.sleep(0) diff --git a/modules/videos/video/lib.py b/modules/videos/video/lib.py index 238778d5..89ec00bf 100644 --- a/modules/videos/video/lib.py +++ b/modules/videos/video/lib.py @@ -165,7 +165,7 @@ def delete_videos(*video_ids: int, session: Session = None): logger.warning(f'Deleting {len(videos)} videos') for video in videos: - video.delete() + video.delete(add_to_skip_list=True) session.commit() diff --git a/wrolpi/common.py b/wrolpi/common.py index cfbe820f..88f6b45e 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -266,6 +266,14 @@ class ModelHelper: """Get a model instance by its id, raise an error if no instance is found.""" raise NotImplementedError('This model has not defined this method.') + @staticmethod + def can_model(file_group) -> bool: + raise NotImplementedError('This model has not defined this method.') + + @staticmethod + def do_model(file_group, session: Session): + raise NotImplementedError('This model has not defined this method.') + def flush(self): """A convenience function which flushes this record using its DB Session.""" Session.object_session(self).flush([self]) diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index 11904214..ee12fab0 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -212,9 +212,9 @@ class Download(ModelHelper, Base): # noqa def add_to_skip_list(self): download_manager.add_to_skip_list(self.url) - def delete(self, skip: bool = True): + def delete(self, add_to_skip_list: bool = True): # Do not download this automatically again. This saves the config. - if skip: + if add_to_skip_list: self.add_to_skip_list() session = Session.object_session(self) diff --git a/wrolpi/files/ebooks.py b/wrolpi/files/ebooks.py index cec06296..e36541e7 100644 --- a/wrolpi/files/ebooks.py +++ b/wrolpi/files/ebooks.py @@ -73,8 +73,8 @@ def extract_text(html: str) -> str: return text -def mimetype_is_ebook(mimetype: str) -> List[str]: - return [i for i in EBOOK_MIMETYPES if mimetype.startswith(i)] +def mimetype_is_ebook(mimetype: str) -> bool: + return any(i for i in EBOOK_MIMETYPES if mimetype.startswith(i)) def extract_ebook_data(path: pathlib.Path, mimetype: str) -> Optional[EBookData]: @@ -167,6 +167,18 @@ class EBook(ModelHelper, Base): d['data']['cover_path'] = pathlib.Path(d['data']['cover_path']) if 'cover_path' in d['data'] else None return d + @staticmethod + def can_model(file_group: FileGroup) -> bool: + if mimetype_is_ebook(file_group.mimetype): + return True + return False + + @staticmethod + def do_model(file_group: FileGroup, session: Session) -> 'EBook': + ebook = model_ebook(file_group, session) + file_group.indexed = True + return ebook + def generate_cover(self) -> Optional[pathlib.Path]: """Discover this ebook's cover, if found, store it next to the ebook file.""" path = self.file_group.primary_path @@ -268,7 +280,7 @@ def model_ebook(file_group: FileGroup, session: Session) -> EBook: ebook.file_group.title = stem ebook.size = size - session.flush([ebook, ]) + ebook.flush() return ebook diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 559c1da8..42aae17b 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -1404,8 +1404,7 @@ async def upsert_file(file: pathlib.Path | str, session: Session = None, tag_nam session.flush([file_group, ]) try: - if model := file_group.do_model(session): - session.add(model) + file_group.do_model(session) except Exception as e: logger.error(f'Failed to model FileGroup: {file_group}', exc_info=e) if PYTEST: diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index 649d5ea6..44ddd66e 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -3,12 +3,11 @@ import pathlib import shutil import urllib.parse from datetime import datetime -from typing import List, Type, Optional +from typing import List, Type, Optional, Iterable from sqlalchemy import Column, String, Computed, BigInteger, Boolean from sqlalchemy import types from sqlalchemy.orm import deferred, relationship, Session -from sqlalchemy.orm.collections import InstrumentedList from wrolpi.common import Base, ModelHelper, tsvector, logger, recursive_map, get_media_directory, \ get_relative_to_media_directory @@ -86,7 +85,7 @@ class FileGroup(ModelHelper, Base): url = Column(String) # the location where this file can be downloaded. viewed = Column(TZDateTime) # the most recent time a User viewed this file. - tag_files: InstrumentedList = relationship('TagFile', cascade='all') + tag_files: Iterable[TagFile] = relationship('TagFile', cascade='all') a_text = deferred(Column(String)) b_text = deferred(Column(String)) @@ -176,10 +175,12 @@ class FileGroup(ModelHelper, Base): files[i]['path'] = pathlib.Path(files[i]['path']) if mimetypes: - files = list(filter(lambda i: any(i['mimetype'].startswith(m) for m in mimetypes), files)) + files = list(filter(lambda j: any(j['mimetype'].startswith(m) for m in mimetypes), files)) - # Sort files to avoid random order. - return sorted(files, key=lambda i: i['path']) + if PYTEST: + # Sort files to avoid random order during testing. + return sorted(files, key=lambda j: j['path']) + return files def my_paths(self, *mimetypes: str) -> List[pathlib.Path]: return [i['path'] for i in self.my_files(*mimetypes)] @@ -212,7 +213,7 @@ class FileGroup(ModelHelper, Base): def my_mobi_files(self) -> List[dict]: return self.my_files('application/x-mobipocket-ebook') - def delete(self): + def delete(self, add_to_skip_list: bool = True): """Delete this FileGroup record, and all of its files. @raise FileGroupIsTagged: If any tags are related to me.""" @@ -223,6 +224,9 @@ class FileGroup(ModelHelper, Base): path.unlink(missing_ok=True) if session := Session.object_session(self): + from wrolpi.downloader import download_manager + if self.url and add_to_skip_list is True: + download_manager.add_to_skip_list(self.url) session.delete(self) @property @@ -289,7 +293,7 @@ class FileGroup(ModelHelper, Base): def find_by_id(id_: int, session: Session = None) -> 'FileGroup': fg = session.query(FileGroup).filter(FileGroup.id == id_).one_or_none() if not fg: - raise RuntimeError(f'Unable to find FileGroup with id {id_}') + raise UnknownFile(f'Unable to find FileGroup with id {id_}') return fg @staticmethod @@ -360,51 +364,31 @@ class FileGroup(ModelHelper, Base): query = urllib.parse.urlencode(dict(folders=str(parent), preview=str(preview))) return f'/files?{query}' - def get_model_class(self) -> Optional[Type[Base]]: + def get_model_class(self) -> Optional[Type[ModelHelper]]: + """Return the class that is suitable for this FileGroup (usually based on mimetype), if any.""" from modules.videos.models import Video - from modules.archive.lib import is_singlefile_file from modules.archive.models import Archive from wrolpi.files.ebooks import EBook - from wrolpi.files.ebooks import mimetype_is_ebook - if self.mimetype.startswith('video/'): + if Video.can_model(self): return Video - elif self.mimetype.startswith('text') and is_singlefile_file(self.primary_path): - return Archive - elif mimetype_is_ebook(self.mimetype): + elif EBook.can_model(self): return EBook + elif Archive.can_model(self): + return Archive - def get_model(self, session: Session) -> Optional[Base]: + def do_model(self, session: Session) -> Optional[ModelHelper]: + """Get/Create the Model record (Video/Archive/etc.) for this FileGroup, if any.""" if model_class := self.get_model_class(): - return model_class.get_by_path(self.primary_path, session) + if model := model_class.get_by_path(self.primary_path, session): + # Already modeled. + return model + # Create new model (Video/Archive/Ebook). + return model_class.do_model(self, session) - def do_model(self, session: Session) -> Base: - """Create the Model record (Video/Archive/etc.) for this FileGroup, if any.""" - if model := self.get_model(session): - return model - - from modules.archive.lib import is_singlefile_file - from modules.archive import model_archive - from modules.videos.models import Video - from wrolpi.files.ebooks import model_ebook, mimetype_is_ebook - - if self.mimetype.startswith('video/'): - video = Video(file_group_id=self.id, file_group=self) - session.add(video) - video.validate() - self.indexed = True - session.flush([video, ]) - return video - elif self.mimetype.startswith('text') and is_singlefile_file(self.primary_path): - archive = model_archive(self, session) - self.indexed = True - return archive - elif mimetype_is_ebook(self.mimetype): - ebook = model_ebook(self, session) - self.indexed = True - return ebook - - raise UnknownFile(f'Cannot model file with mimetype {self.mimetype}') + # Index the file if no models are available. + self.do_index() + self.indexed = True def get_tag_directory_paths_map(self) -> dict[pathlib.Path, str]: """Return all links that should exist for this FileGroup in the Tags Directory.""" diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 0a5b33e0..a266b176 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -526,6 +526,31 @@ def test_post_upload(test_session, test_client, test_directory, make_files_struc assert not video.channel and not video.channel_id +def test_post_upload_text(test_session, test_client, test_directory, make_files_structure, make_multipart_form): + """A file that cannot be modeled can still be uploaded, and is indexed.""" + make_files_structure(['uploads/']) + + contents = 'hello' + forms = [ + dict(name='chunkNumber', value='0'), + dict(name='filename', value='the title.txt'), + dict(name='totalChunks', value='0'), + dict(name='destination', value='uploads'), + dict(name='chunkSize', value=5), + dict(name='chunk', value=contents, filename='chunk'), + ] + body = make_multipart_form(forms) + headers = {'Content-Type': 'multipart/form-data; boundary=-----------------------------sanic'} + request, response = test_client.post('/api/files/upload', content=body, headers=headers) + assert response.status_code == HTTPStatus.CREATED, response.content.decode() + + file_group: FileGroup = test_session.query(FileGroup).one() + assert file_group.indexed is True + assert file_group.size == 5 + assert file_group.a_text == 'the title txt' + assert file_group.d_text == 'hello' + + @pytest.mark.asyncio async def test_directory_crud(test_session, test_async_client, test_directory, assert_directories, assert_files): """A directory can be created in a subdirectory. Errors are returned if there are conflicts."""