diff --git a/alembic/versions/26c5a62ec683_make_filegroup_directory_not_null.py b/alembic/versions/26c5a62ec683_make_filegroup_directory_not_null.py new file mode 100644 index 00000000..9e61fe98 --- /dev/null +++ b/alembic/versions/26c5a62ec683_make_filegroup_directory_not_null.py @@ -0,0 +1,58 @@ +"""make_filegroup_directory_not_null + +Revision ID: 26c5a62ec683 +Revises: af4527503bdf +Create Date: 2025-12-23 20:47:11.549264 + +This migration makes the `directory` column NOT NULL after the previous migration +has populated it for all existing FileGroups. +""" +import os + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.orm import Session + +# revision identifiers, used by Alembic. +revision = '26c5a62ec683' +down_revision = 'af4527503bdf' +branch_labels = None +depends_on = None + +DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False + + +def upgrade(): + bind = op.get_bind() + session = Session(bind=bind) + + # Safety check: ensure no NULL directory values remain + result = session.execute(sa.text( + "SELECT COUNT(*) FROM file_group WHERE directory IS NULL" + )) + null_count = result.scalar() + if null_count > 0: + # Fill any remaining NULL values (shouldn't happen if previous migration ran) + print(f"Warning: Found {null_count} FileGroups with NULL directory, filling from primary_path...") + session.execute(sa.text(""" + UPDATE file_group + SET directory = regexp_replace(primary_path, '/[^/]+$', '') + WHERE directory IS NULL AND primary_path IS NOT NULL + """)) + session.commit() + + # Make the column NOT NULL + op.alter_column('file_group', 'directory', nullable=False) + + # Create index on directory column for efficient directory lookups + op.create_index('file_group_directory_idx', 'file_group', ['directory']) + + if not DOCKERIZED: + session.execute(sa.text('ALTER TABLE public.file_group OWNER TO wrolpi')) + + +def downgrade(): + # Drop the index + op.drop_index('file_group_directory_idx', 'file_group') + # Make the column nullable again + op.alter_column('file_group', 'directory', nullable=True) diff --git a/alembic/versions/af4527503bdf_add_filegroup_directory_column.py b/alembic/versions/af4527503bdf_add_filegroup_directory_column.py new file mode 100644 index 00000000..2e3691f7 --- /dev/null +++ b/alembic/versions/af4527503bdf_add_filegroup_directory_column.py @@ -0,0 +1,192 @@ +"""add_filegroup_directory_column + +Revision ID: af4527503bdf +Revises: 577e414f1bc4 +Create Date: 2025-12-23 19:35:18.776018 + +This migration: +1. Adds `directory` column to file_group (stores parent directory of primary_path) +2. Converts paths in `files` JSON from absolute to relative (filename only) +3. Converts paths in `data` JSON from absolute to relative (filename only) + +After this migration: +- directory: /media/wrolpi/videos/channel1 (absolute) +- primary_path: /media/wrolpi/videos/channel1/video.mp4 (absolute, unchanged for now) +- files: [{path: "video.mp4", ...}] (relative filenames) +- data: {poster_path: "video.jpg", ...} (relative filenames) + +Processing is done in batches to handle large databases (hundreds of thousands of FileGroups) +on memory-constrained devices like Raspberry Pi. +""" +import os + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.orm import Session + +import wrolpi.media_path + +# revision identifiers, used by Alembic. +revision = 'af4527503bdf' +down_revision = '577e414f1bc4' +branch_labels = None +depends_on = None + +DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False + +# Batch size for processing - balances memory usage vs. migration speed +BATCH_SIZE = 1000 + + +def upgrade(): + bind = op.get_bind() + session = Session(bind=bind) + + # Add the directory column (nullable initially) + # Index is created in the next migration (26c5a62ec683) AFTER data is populated for efficiency. + op.add_column('file_group', sa.Column('directory', wrolpi.media_path.MediaPathType(), nullable=True)) + + # Phase 1: Populate directory from existing primary_path (batched) + # Uses regexp_replace to remove the filename (everything after the last /). + print("Phase 1: Populating directory column...") + total_updated = 0 + while True: + result = session.execute(sa.text(""" + UPDATE file_group + SET directory = regexp_replace(primary_path, '/[^/]+$', '') + WHERE id IN ( + SELECT id FROM file_group + WHERE directory IS NULL + AND primary_path IS NOT NULL + LIMIT :batch_size + ) + """), {'batch_size': BATCH_SIZE}) + session.commit() + if result.rowcount == 0: + break + total_updated += result.rowcount + print(f" Processed {total_updated} directories...") + print(f"Phase 1 complete: {total_updated} directories populated.") + + # Phase 2: Convert files JSON paths from absolute to relative (batched) + # Only processes rows where at least one path is still absolute (starts with /) + print("Phase 2: Converting files JSON to relative paths...") + total_updated = 0 + while True: + result = session.execute(sa.text(""" + UPDATE file_group + SET files = ( + SELECT jsonb_agg( + jsonb_set( + elem, + '{path}', + to_jsonb(regexp_replace(elem->>'path', '.+/', '')) + ) + ) + FROM jsonb_array_elements(files::jsonb) AS elem + ) + WHERE id IN ( + SELECT id FROM file_group + WHERE files IS NOT NULL + AND jsonb_array_length(files::jsonb) > 0 + AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(files::jsonb) AS elem + WHERE elem->>'path' LIKE '/%' + ) + LIMIT :batch_size + ) + """), {'batch_size': BATCH_SIZE}) + session.commit() + if result.rowcount == 0: + break + total_updated += result.rowcount + print(f" Converted {total_updated} files arrays...") + print(f"Phase 2 complete: {total_updated} files arrays converted.") + + # Phase 3: Convert data JSON paths from absolute to relative (batched) + # Handle known path fields: video_path, info_json_path, poster_path, ebook_path, cover_path, screenshot_path + # Only processes rows where data contains at least one absolute path + print("Phase 3: Converting data JSON to relative paths...") + total_updated = 0 + while True: + result = session.execute(sa.text(""" + UPDATE file_group + SET data = ( + SELECT COALESCE( + jsonb_object_agg( + key, + CASE + -- Handle path fields that are strings starting with / + -- Use ::jsonb cast instead of to_jsonb() since value::text already has JSON quotes + WHEN key IN ('video_path', 'info_json_path', 'poster_path', 'ebook_path', 'cover_path', 'screenshot_path', + 'readability_json_path', 'readability_path', 'readability_txt_path', 'singlefile_path') + AND jsonb_typeof(value) = 'string' + AND value::text LIKE '"/%%' + THEN regexp_replace(value::text, '^".+/', '"')::jsonb + + -- Handle caption_paths which is an array of strings + WHEN key = 'caption_paths' AND jsonb_typeof(value) = 'array' + THEN ( + SELECT jsonb_agg( + CASE + WHEN jsonb_typeof(elem) = 'string' AND elem::text LIKE '"/%%' + THEN regexp_replace(elem::text, '^".+/', '"')::jsonb + ELSE elem + END + ) + FROM jsonb_array_elements(value) AS elem + ) + + -- Keep other values unchanged + ELSE value + END + ), + '{}'::jsonb + ) + FROM jsonb_each(data::jsonb) + ) + WHERE id IN ( + SELECT id FROM file_group + WHERE data IS NOT NULL + AND data::text != 'null' + AND data::text != '{}' + AND ( + -- Check if any known path field contains an absolute path + data->>'video_path' LIKE '/%' + OR data->>'info_json_path' LIKE '/%' + OR data->>'poster_path' LIKE '/%' + OR data->>'ebook_path' LIKE '/%' + OR data->>'cover_path' LIKE '/%' + OR data->>'screenshot_path' LIKE '/%' + OR data->>'readability_json_path' LIKE '/%' + OR data->>'readability_path' LIKE '/%' + OR data->>'readability_txt_path' LIKE '/%' + OR data->>'singlefile_path' LIKE '/%' + OR EXISTS ( + SELECT 1 FROM jsonb_array_elements_text( + CASE WHEN data->>'caption_paths' IS NOT NULL THEN (data->'caption_paths')::jsonb ELSE '[]'::jsonb END + ) AS elem + WHERE elem LIKE '/%' + ) + ) + LIMIT :batch_size + ) + """), {'batch_size': BATCH_SIZE}) + session.commit() + if result.rowcount == 0: + break + total_updated += result.rowcount + print(f" Converted {total_updated} data objects...") + print(f"Phase 3 complete: {total_updated} data objects converted.") + + print("Migration complete!") + + if not DOCKERIZED: + session.execute(sa.text('ALTER TABLE public.file_group OWNER TO wrolpi')) + + +def downgrade(): + # Note: Downgrade does not restore absolute paths in files/data columns. + # This would require knowing the original directory for each record. + # Index is dropped in the previous downgrade (26c5a62ec683). + op.drop_column('file_group', 'directory') diff --git a/modules/archive/__init__.py b/modules/archive/__init__.py index b64efd55..6876b9a5 100644 --- a/modules/archive/__init__.py +++ b/modules/archive/__init__.py @@ -233,15 +233,16 @@ def model_archive(session: Session, file_group: FileGroup) -> Archive: file_group.title = file_group.a_text = title or archive.file_group.title file_group.d_text = contents + # Store paths as filenames only (relative to directory), resolved via file_group.resolve_path() file_group.data = { 'id': archive.id, 'domain': archive.domain, - 'readability_json_path': archive.readability_json_path, - 'readability_path': archive.readability_path, - 'readability_txt_path': archive.readability_txt_path, - 'screenshot_path': archive.screenshot_path, - 'singlefile_path': archive.singlefile_path, - 'info_json_path': archive.info_json_path, + 'readability_json_path': archive.readability_json_path.name if archive.readability_json_path else None, + 'readability_path': archive.readability_path.name if archive.readability_path else None, + 'readability_txt_path': archive.readability_txt_path.name if archive.readability_txt_path else None, + 'screenshot_path': archive.screenshot_path.name if archive.screenshot_path else None, + 'singlefile_path': archive.singlefile_path.name if archive.singlefile_path else None, + 'info_json_path': archive.info_json_path.name if archive.info_json_path else None, } return archive diff --git a/modules/archive/models.py b/modules/archive/models.py index 1990b43c..4472f6f2 100644 --- a/modules/archive/models.py +++ b/modules/archive/models.py @@ -235,9 +235,9 @@ class Archive(Base, ModelHelper): self.file_group.append_files(screenshot_path) # Update FileGroup.data for quick lookup (similar to ebook cover_path pattern) - # Create new dict and reassign (like append_files does) to ensure SQLAlchemy detects the change + # Store as filename only (relative to directory), resolved via file_group.resolve_path() data = dict(self.file_group.data) if self.file_group.data else {} - data['screenshot_path'] = str(screenshot_path) + data['screenshot_path'] = screenshot_path.name # Store filename only self.file_group.data = data # Validate the archive diff --git a/modules/archive/test/test_api.py b/modules/archive/test/test_api.py index 1645f858..76f55afd 100644 --- a/modules/archive/test/test_api.py +++ b/modules/archive/test/test_api.py @@ -302,11 +302,12 @@ async def test_archive_upload_file_tracking(test_session, async_client, archive_ # Assert screenshot properties exist assert archive.screenshot_path is not None, 'Archive.screenshot_path should exist' assert archive.screenshot_file is not None, 'Archive.screenshot_file should exist' + # data['screenshot_path'] stores just the filename, screenshot_path resolves to absolute assert archive.file_group.data.get( - 'screenshot_path') == archive.screenshot_path, 'Archive screenshot should be in FileGroup.data' + 'screenshot_path') == archive.screenshot_path.name, 'Archive screenshot should be in FileGroup.data' - # Assert image is in FileGroup.files - file_paths = [f['path'] for f in archive.file_group.files] + # Assert image is in FileGroup.files (use my_files() to get resolved absolute paths) + file_paths = [f['path'] for f in archive.file_group.my_files()] assert archive.screenshot_path in file_paths, 'Screenshot should be in FileGroup.files' # Assert FileGroup has correct number of files diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index 3b6d5e97..af7493e2 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -573,11 +573,12 @@ async def test_refresh_archives(test_session, test_directory, async_client, make assert response.status_code == HTTPStatus.OK assert response.json['file_groups'], 'No files matched "text"' assert response.json['file_groups'][0]['model'] == 'archive', 'Returned file was not an archive' + # data now stores just filenames (relative paths), not full paths assert response.json['file_groups'][0]['data'].get('readability_path') == \ - 'archive/example.com/2021-10-05-16-20-10_NA.readability.html', \ + '2021-10-05-16-20-10_NA.readability.html', \ 'Could not find readability html file' assert response.json['file_groups'][0]['data'].get('readability_txt_path') == \ - 'archive/example.com/2021-10-05-16-20-10_NA.readability.txt', \ + '2021-10-05-16-20-10_NA.readability.txt', \ 'Could not find readability text file containing "text"' assert response.json['file_groups'][0]['download_datetime'], 'Archive has no datetime' diff --git a/modules/archive/test/test_models.py b/modules/archive/test/test_models.py index d41cce9e..4a74aae1 100644 --- a/modules/archive/test/test_models.py +++ b/modules/archive/test/test_models.py @@ -77,8 +77,8 @@ async def test_set_screenshot(async_client, test_session, archive_factory, image # Set the screenshot archive.set_screenshot(screenshot_path) - # Verify data was set before commit - assert archive.file_group.data['screenshot_path'] == str(screenshot_path), \ + # Verify data was set before commit (stores filename only, not absolute path) + assert archive.file_group.data['screenshot_path'] == screenshot_path.name, \ f"Data not set correctly before commit: {archive.file_group.data.get('screenshot_path')}" test_session.commit() @@ -87,12 +87,12 @@ async def test_set_screenshot(async_client, test_session, archive_factory, image test_session.expire_all() archive = test_session.query(Archive).filter_by(id=archive.id).one() - # Verify screenshot was set + # Verify screenshot was set (screenshot_path property resolves to absolute via my_files()) assert archive.screenshot_path == screenshot_path assert archive.screenshot_file is not None - # Verify FileGroup.data was persisted to DB (FancyJSON converts strings back to Path objects) + # Verify FileGroup.data was persisted to DB (now stores filename only) assert 'screenshot_path' in archive.file_group.data - assert str(archive.file_group.data['screenshot_path']) == str(screenshot_path) + assert archive.file_group.data['screenshot_path'] == screenshot_path.name # Verify file is tracked in FileGroup.files screenshot_files = archive.file_group.my_files('image/') diff --git a/modules/videos/__init__.py b/modules/videos/__init__.py index 048645af..76ec6010 100644 --- a/modules/videos/__init__.py +++ b/modules/videos/__init__.py @@ -87,7 +87,8 @@ def video_cleanup(): SET channel_id = c.id FROM channel c INNER JOIN collection col ON col.id = c.collection_id - LEFT JOIN file_group fg ON fg.primary_path LIKE col.directory || '/%'::VARCHAR + LEFT JOIN file_group fg ON fg.directory = col.directory + OR fg.directory LIKE col.directory || '/%' WHERE v.channel_id IS NULL AND fg.id = v.file_group_id ''') @@ -109,13 +110,13 @@ def claim_videos_for_channels(channel_ids: List[int]): logger.info(f'Claiming Videos for {len(channel_ids)} channel(s)') with get_db_curs(commit=True) as curs: - # Note: %% is escaped to % in psycopg2 when parameters are used curs.execute(''' UPDATE video v SET channel_id = c.id FROM channel c INNER JOIN collection col ON col.id = c.collection_id - LEFT JOIN file_group fg ON fg.primary_path LIKE col.directory || '/%%'::VARCHAR + LEFT JOIN file_group fg ON fg.directory = col.directory + OR fg.directory LIKE col.directory || '/%%' WHERE v.channel_id IS NULL AND fg.id = v.file_group_id AND c.id = ANY (%s) diff --git a/modules/videos/lib.py b/modules/videos/lib.py index ae4cafe0..425b1e52 100644 --- a/modules/videos/lib.py +++ b/modules/videos/lib.py @@ -820,17 +820,25 @@ def find_orphaned_video_files(directory: pathlib.Path) -> Generator[pathlib.Path if not directory.is_dir(): raise UnknownDirectory() - directory = str(directory).rstrip('/') + directory_str = str(directory).rstrip('/') + # Query returns directory and files - files may contain relative or absolute paths + # Use indexed directory column for efficient lookup curs.execute(f''' - SELECT files + SELECT directory, files FROM file_group WHERE - mimetype NOT LIKE 'video%' - AND primary_path LIKE '{directory}/%' + mimetype NOT LIKE 'video%%' + AND (directory = '{directory_str}' OR directory LIKE '{directory_str}/%%') ''') - results = (pathlib.Path(j['path']) for i in curs.fetchall() for j in i[0]) - yield from results + for row in curs.fetchall(): + fg_directory = pathlib.Path(row[0]) if row[0] else None + for file_info in row[1]: + path = pathlib.Path(file_info['path']) + if not path.is_absolute() and fg_directory: + # Resolve relative path using directory + path = fg_directory / path + yield path def format_videos_destination(channel_name: str = None, channel_tag: str = None, channel_url: str = None) \ diff --git a/modules/videos/models.py b/modules/videos/models.py index 74edcdd5..f344eea6 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -243,13 +243,14 @@ class Video(ModelHelper, Base): self.channel = channel logger.debug(f'{self} has Channel {channel}') - # Set FileGroup.data with cached file paths for consistency with Archive + # Set FileGroup.data with cached file paths (stored as relative filenames) + # Paths are resolved to absolute when accessed via file_group.resolve_path() self.file_group.data = { 'id': self.id, - 'video_path': self.video_path, - 'info_json_path': self.info_json_path, - 'poster_path': self.poster_path, - 'caption_paths': self.caption_paths, + 'video_path': self.video_path.name if self.video_path else None, + 'info_json_path': self.info_json_path.name if self.info_json_path else None, + 'poster_path': self.poster_path.name if self.poster_path else None, + 'caption_paths': [p.name for p in self.caption_paths] if self.caption_paths else [], } @staticmethod diff --git a/modules/videos/test/test_api.py b/modules/videos/test/test_api.py index 0dd5cfc7..64711ce6 100644 --- a/modules/videos/test/test_api.py +++ b/modules/videos/test/test_api.py @@ -71,12 +71,12 @@ async def test_refresh_videos(async_client, test_session, test_directory, simple orphan_poster = Path(test_directory / 'channel name_20000104_defghijklmn_title.jpg') orphan_poster.write_bytes(image_bytes_factory()) - # Create a bogus video in the channel. + # Create a bogus video in the channel (file doesn't exist, should be removed during refresh). video_file = test_directory / 'foo.mp4' with get_db_curs(commit=True) as curs: - stmt = "INSERT INTO file_group (mimetype, primary_path, indexed, files, model)" \ - " values ('video/mp4', %(primary_path)s, true, %(files)s, 'video') RETURNING id" - params = {'primary_path': str(video_file), 'files': list()} + stmt = "INSERT INTO file_group (mimetype, directory, primary_path, indexed, files, model)" \ + " values ('video/mp4', %(directory)s, %(primary_path)s, true, %(files)s, 'video') RETURNING id" + params = {'directory': str(test_directory), 'primary_path': str(video_file), 'files': list()} curs.execute(stmt, params) video4_id = curs.fetchall()[0][0] stmt = "INSERT INTO video (file_group_id) values (%(video_id)s)" @@ -480,10 +480,11 @@ async def test_video_upload_file_tracking(test_session, async_client, video_fact # Assert poster properties exist assert video.poster_path is not None, 'Video.poster_path should exist' assert video.poster_file is not None, 'Video.poster_file should exist' - assert video.file_group.data.get('poster_path') == video.poster_path, 'Video poster should be in FileGroup.data' + # data['poster_path'] stores just the filename, poster_path resolves to absolute + assert video.file_group.data.get('poster_path') == video.poster_path.name, 'Video poster should be in FileGroup.data' - # Assert poster is in FileGroup.files - file_paths = [f['path'] for f in video.file_group.files] + # Assert poster is in FileGroup.files (use my_files() to get resolved absolute paths) + file_paths = [f['path'] for f in video.file_group.my_files()] assert video.poster_path in file_paths, 'Poster should be in FileGroup.files' # Assert FileGroup has correct number of files @@ -532,8 +533,8 @@ Another line of captions. assert video.caption_files, 'Video.caption_files should exist' assert video.file_group.data.get('caption_paths'), 'Video captions should be in FileGroup.data' - # Assert caption is in FileGroup.files - file_paths = [f['path'] for f in video.file_group.files] + # Assert caption is in FileGroup.files (use my_files() to get resolved absolute paths) + file_paths = [f['path'] for f in video.file_group.my_files()] assert video.caption_paths[0] in file_paths, 'Caption should be in FileGroup.files' # Assert FileGroup has correct number of files diff --git a/wrolpi/collections/models.py b/wrolpi/collections/models.py index b8eac1bc..a792f2e0 100644 --- a/wrolpi/collections/models.py +++ b/wrolpi/collections/models.py @@ -1,7 +1,7 @@ import pathlib from typing import Optional, List -from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime, Index, UniqueConstraint, func, BigInteger +from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime, Index, UniqueConstraint, func, BigInteger, or_ from sqlalchemy.orm import relationship, Session from sqlalchemy.orm.collections import InstrumentedList @@ -471,8 +471,13 @@ class Collection(ModelHelper, Base): return # Find all FileGroups in this directory tree + # Use indexed directory column for efficient lookup + directory_str = str(self.directory) file_groups = session.query(FileGroup).filter( - FileGroup.primary_path.like(f'{self.directory}/%') + or_( + FileGroup.directory == directory_str, + FileGroup.directory.like(f'{directory_str}/%') + ) ).all() if not file_groups: diff --git a/wrolpi/collections/test/test_api.py b/wrolpi/collections/test/test_api.py index 052e46c2..e2164a77 100644 --- a/wrolpi/collections/test/test_api.py +++ b/wrolpi/collections/test/test_api.py @@ -340,9 +340,12 @@ class TestCollectionDeletion: test_session.flush() # Create file groups and archives for this domain - fg1 = FileGroup(primary_path=test_directory / 'archive' / 'example.com' / 'page1.html', + archive_dir = test_directory / 'archive' / 'example.com' + fg1 = FileGroup(directory=archive_dir, + primary_path=archive_dir / 'page1.html', url='https://example.com/page1') - fg2 = FileGroup(primary_path=test_directory / 'archive' / 'example.com' / 'page2.html', + fg2 = FileGroup(directory=archive_dir, + primary_path=archive_dir / 'page2.html', url='https://example.com/page2') test_session.add_all([fg1, fg2]) test_session.flush() diff --git a/wrolpi/collections/test/test_domain_moving.py b/wrolpi/collections/test/test_domain_moving.py index 092534d2..0f0501df 100644 --- a/wrolpi/collections/test/test_domain_moving.py +++ b/wrolpi/collections/test/test_domain_moving.py @@ -87,16 +87,21 @@ async def test_tag_domain_collection_moves_archives( if src_dir.exists(): assert not list(src_dir.iterdir()), f'Old directory {src_dir} should be empty' - # Verify FileGroup.data paths were also updated (the bug we're fixing) + # Verify FileGroup paths were updated correctly for archive in [archive1, archive2]: test_session.refresh(archive) data = archive.file_group.data assert data is not None, f"Archive {archive.id} should have FileGroup.data" - # All path fields in data should point to new directory + # FileGroup.directory should point to new location + assert str(dest_dir) in str(archive.file_group.directory), \ + f"FileGroup.directory should be in {dest_dir}, got {archive.file_group.directory}" + # Paths in data are now relative filenames, they don't need to change on move. + # The key is that directory + filename resolves to the correct absolute path. for key, value in data.items(): - if isinstance(value, (str, pathlib.Path)) and 'archive' in str(value): - assert str(dest_dir) in str(value), \ - f"FileGroup.data['{key}'] should be in {dest_dir}, got {value}" + if key.endswith('_path') and value: + resolved = archive.file_group.resolve_path(value) + assert str(dest_dir) in str(resolved), \ + f"FileGroup.data['{key}'] resolved to {resolved}, should be in {dest_dir}" @pytest.mark.asyncio diff --git a/wrolpi/conftest.py b/wrolpi/conftest.py index 5ea52591..2538395c 100644 --- a/wrolpi/conftest.py +++ b/wrolpi/conftest.py @@ -668,14 +668,17 @@ def insert_file_group(test_session, test_directory): """Inserts a FileGroup based on the provided paths. Does not verify if the files exist.""" def _(paths: List[pathlib.Path]): - files = [dict(path=str(i), mimetype='fake') for i in paths] + # Store relative filenames in files (new schema) + files = [dict(path=i.name, mimetype='fake') for i in paths] + primary_path = paths[0] params = dict( - primary_path=str(paths[0]), + directory=str(primary_path.parent), + primary_path=str(primary_path), files=json.dumps(files), ) test_session.execute('INSERT INTO file_group ' - '(indexed, primary_path, files) VALUES ' - '(true, :primary_path, :files)', params) + '(indexed, directory, primary_path, files) VALUES ' + '(true, :directory, :primary_path, :files)', params) return _ diff --git a/wrolpi/files/ebooks.py b/wrolpi/files/ebooks.py index 18877b2e..3fe91fdd 100644 --- a/wrolpi/files/ebooks.py +++ b/wrolpi/files/ebooks.py @@ -164,10 +164,12 @@ class EBook(ModelHelper, Base): return f'' def __json__(self) -> dict: - # Convert this eBook's paths to pathlib.Paths. + # Convert this eBook's paths to pathlib.Paths, resolving relative to directory. d = self.file_group.__json__() - d['data']['ebook_path'] = pathlib.Path(d['data']['ebook_path']) - d['data']['cover_path'] = pathlib.Path(d['data']['cover_path']) if 'cover_path' in d['data'] else None + if d.get('data') and d['data'].get('ebook_path'): + d['data']['ebook_path'] = self.file_group.resolve_path(d['data']['ebook_path']) + if d.get('data') and d['data'].get('cover_path'): + d['data']['cover_path'] = self.file_group.resolve_path(d['data']['cover_path']) return d @staticmethod @@ -267,19 +269,23 @@ def model_ebook(file_group: FileGroup, session: Session) -> EBook: # All text is d_text. ebook.file_group.d_text = data.text d: dict = data.__json__() - d['ebook_path'] = str(d['ebook_path']) + # Store ebook_path as filename only (relative to directory) + d['ebook_path'] = ebook_file.name ebook.file_group.data = d except Exception as e: logger.error(f'Failed to extract epub book data', exc_info=e) if ebook.file_group.my_poster_files(): - ebook.file_group.data['cover_path'] = ebook.file_group.my_poster_files()[0]['path'] + # Store cover_path as filename only (relative to directory) + cover_path = ebook.file_group.my_poster_files()[0]['path'] + ebook.file_group.data['cover_path'] = cover_path.name else: # Extract cover because there is no cover file. cover_path = ebook.generate_cover() if cover_path: ebook.file_group.append_files(cover_path) - ebook.file_group.data['cover_path'] = str(cover_path) + # Store cover_path as filename only (relative to directory) + ebook.file_group.data['cover_path'] = cover_path.name if not ebook.file_group.title: # Book was not indexed above (probably a MOBI), use the file data. diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 7462a315..2ecefe6a 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -17,7 +17,7 @@ from typing import List, Tuple, Union, Dict, Generator, Iterable, Set import cachetools.func import psycopg2 -from sqlalchemy import asc +from sqlalchemy import asc, or_ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session @@ -236,7 +236,12 @@ async def delete(*paths: Union[str, pathlib.Path]): query = query.filter(FileGroup.primary_path.like(f'{path.parent}/{stem}%')) else: # Search for any FileGroups that have been tagged under this directory. - query = query.filter(FileGroup.primary_path.like(f'{path}/%')) + # Use indexed directory column for efficient lookup + path_str = str(path) + query = query.filter(or_( + FileGroup.directory == path_str, + FileGroup.directory.like(f'{path_str}/%') + )) for (file_group, tag_file) in query: if any(i for i in paths if i in file_group.my_paths()): # File that will be deleted is in a Tagged FileGroup. @@ -404,7 +409,10 @@ refresh_logger = logger.getChild('refresh') def _paths_to_files_dict(group: List[pathlib.Path]) -> List[dict]: - """This generates `FileGroup.files` from a list of files.""" + """This generates `FileGroup.files` from a list of files. + + Paths are stored as filenames only (relative to FileGroup.directory). + """ files = list() for file in group: mimetype = get_mimetype(file) @@ -413,7 +421,7 @@ def _paths_to_files_dict(group: List[pathlib.Path]) -> List[dict]: _, suffix = split_path_stem_and_suffix(file) size = stat.st_size files.append(dict( - path=str(file), + path=file.name, # Store filename only, not full path mimetype=mimetype, modification_datetime=modification_datetime, size=size, @@ -512,16 +520,18 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime): values[primary_path] = (modification_datetime, mimetype, size, files) values = [(str(primary_path), + str(primary_path.parent), # directory False, # `indexed` is false to force indexing by default. idempotency, *i) for primary_path, i in values.items()] with get_db_curs(commit=True) as curs: values = mogrify(curs, values) stmt = f''' INSERT INTO file_group - (primary_path, indexed, idempotency, modification_datetime, mimetype, size, files) + (primary_path, directory, indexed, idempotency, modification_datetime, mimetype, size, files) VALUES {values} ON CONFLICT (primary_path) DO UPDATE SET + directory=EXCLUDED.directory, idempotency=EXCLUDED.idempotency, modification_datetime=EXCLUDED.modification_datetime, mimetype=EXCLUDED.mimetype, @@ -639,8 +649,13 @@ async def refresh_discover_paths(paths: List[pathlib.Path], idempotency: datetim with get_db_curs(commit=True) as curs: wheres = '' if paths: - # Use LIKE to delete any children of directories that are deleted. - wheres = ' OR '.join([curs.mogrify('primary_path LIKE %s', (f'{i}/%',)).decode() for i in paths]) + # Use indexed directory column to delete any children of directories that are deleted. + # Match exact directory or subdirectories + conditions = [] + for p in paths: + p_str = str(p) + conditions.append(curs.mogrify('(directory = %s OR directory LIKE %s)', (p_str, f'{p_str}/%')).decode()) + wheres = ' OR '.join(conditions) deleted_files = '' if deleted: # Delete any paths that do not exist. @@ -1393,8 +1408,13 @@ async def _move(session: Session, destination: pathlib.Path, *sources: pathlib.P # Sleep to catch cancel. await asyncio.sleep(0) elif source.is_dir(): - stmt = 'SELECT primary_path FROM file_group WHERE primary_path LIKE :like' - for (primary_path,) in session.execute(stmt, dict(like=f'{source}%')): + # Use indexed directory column for efficient lookup + # Match exact directory or subdirectories + stmt = '''SELECT primary_path FROM file_group + WHERE directory = :dir OR directory LIKE :dir_pattern''' + source_str = str(source) + for (primary_path,) in session.execute( + stmt, dict(dir=source_str, dir_pattern=f'{source_str}/%')): primary_path = pathlib.Path(primary_path) if primary_path not in plan: new_primary_path = destination / source.name / primary_path.relative_to(source) @@ -1446,6 +1466,11 @@ async def _move(session: Session, destination: pathlib.Path, *sources: pathlib.P """Apply the move plan to all the FileGroups. @warning: Cannot be cancelled!""" + nonlocal new_directories + # Query existing directories ONCE before processing chunks (not per-chunk). + existing_directories = {i[0] for i in session.query(Directory.path)} + inserted_directories = set() + # Move FileGroups in groups. for chunk in chunks(plan_.items(), MOVE_CHUNK_SIZE): old_paths = [i for i, j in chunk] @@ -1467,10 +1492,11 @@ async def _move(session: Session, destination: pathlib.Path, *sources: pathlib.P for directory_ in old_directories_: delete_directory(directory_) - existing_directories = {i[0] for i in session.query(Directory.path)} - missing_directories = new_directories - existing_directories - for directory_ in missing_directories: - session.add(Directory(path=directory_, name=directory_.name)) + # Find directories that need to be inserted (not existing and not already inserted). + missing_directories = new_directories - existing_directories - inserted_directories + if missing_directories: + session.add_all([Directory(path=d, name=d.name) for d in missing_directories]) + inserted_directories.update(missing_directories) # Don't forget what has moved. session.flush(file_groups_) @@ -1514,8 +1540,13 @@ def delete_directory(directory: pathlib.Path, recursive: bool = False): Will refuse to delete a directory if it contains Tagged Files.""" if recursive: with get_db_session() as session: + # Use indexed directory column for efficient lookup + directory_str = str(directory) tagged = session.query(FileGroup) \ - .filter(FileGroup.primary_path.like(f'{directory}/%')) \ + .filter(or_( + FileGroup.directory == directory_str, + FileGroup.directory.like(f'{directory_str}/%') + )) \ .join(TagFile, TagFile.file_group_id == FileGroup.id) \ .limit(1).one_or_none() if tagged: diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index 352e327a..f7796e40 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -67,6 +67,7 @@ class FileGroup(ModelHelper, Base): __tablename__ = 'file_group' __table_args__ = ( Index('file_group_author_idx', 'author'), + Index('file_group_directory_idx', 'directory'), Index('file_group_download_datetime_idx', 'download_datetime'), Index('file_group_effective_datetime_idx', 'effective_datetime'), Index('file_group_length_idx', 'length'), @@ -82,6 +83,10 @@ class FileGroup(ModelHelper, Base): ) id: int = Column(BigInteger, primary_key=True) + # Directory containing all files in this group (absolute path). + # All paths in `files` and `data` are relative to this directory. + directory: pathlib.Path = Column(MediaPathType, nullable=False) + author = Column(String) # name of the author, maybe even a URL censored = Column(Boolean) # the file is no longer available for download data = Column(FancyJSON) # populated by the modeler @@ -144,7 +149,7 @@ class FileGroup(ModelHelper, Base): author=self.author, censored=self.censored, data=self.data, - directory=self.primary_path.parent, + directory=self.directory, download_datetime=self.download_datetime, files=self.my_files(), id=self.id, @@ -172,6 +177,35 @@ class FileGroup(ModelHelper, Base): return self.title return self.primary_path.name + @property + def full_primary_path(self) -> pathlib.Path: + """Returns the complete absolute path to the primary file. + + Handles both old format (primary_path is absolute) and new format (directory + relative primary_path). + """ + if self.directory: + # New format: directory + relative filename + return self.directory / self.primary_path + # Old format: primary_path is already absolute + return self.primary_path + + def resolve_path(self, relative_path: str | pathlib.Path) -> pathlib.Path: + """Convert a relative filename to an absolute path using this FileGroup's directory. + + Handles both old format (path is already absolute) and new format (relative to directory). + """ + if relative_path is None: + return None + path = pathlib.Path(relative_path) if isinstance(relative_path, str) else relative_path + if path.is_absolute(): + # Old format: already absolute + return path + if self.directory: + # New format: resolve relative to directory + return self.directory / path + # Fallback: use primary_path's parent as directory + return self.primary_path.parent / path + def set_viewed(self, viewed: datetime = None) -> datetime: """ :param viewed: Used only for testing! @@ -226,35 +260,52 @@ class FileGroup(ModelHelper, Base): self.set_tags(session, tags) def append_files(self, *paths: pathlib.Path): - """Add all `paths` to this FileGroup.files.""" + """Add all `paths` to this FileGroup.files. + + Paths are stored as filenames only (relative to directory). + """ from wrolpi.files.lib import get_mimetype new_files = list(self.files) if self.files else list() - new_files.extend([dict(path=path, mimetype=get_mimetype(path)) for path in paths]) + for path in paths: + # Store just the filename, not the full path + new_files.append(dict(path=path.name, mimetype=get_mimetype(path))) self.files = unique_by_predicate(new_files, lambda i: i['path']) def my_files(self, *mimetypes: str) -> List[dict]: """Return all files related to this group that match any of the provided mimetypes. + Paths are resolved to absolute paths using directory. + Returns a new list (does not modify self.files in place). + >>> FileGroup().my_files() >>> FileGroup().my_files('application/pdf') >>> FileGroup().my_files('video/') """ - files = self.files - if not files: + if not self.files: logger.error(f'{self} has no files!') raise ValueError(f'{self} has no files!') - # Convert path strings to Paths. - for i in range(len(files)): - files[i]['path'] = pathlib.Path(files[i]['path']) + # Create a new list with resolved paths (don't modify self.files in place) + result = [] + for file_info in self.files: + # Make a copy of each dict to avoid modifying the original + file_copy = dict(file_info) + path = pathlib.Path(file_info['path']) + if not path.is_absolute() and self.directory: + # New format: relative path, resolve using directory + file_copy['path'] = self.directory / path + else: + # Old format or already absolute: keep as-is + file_copy['path'] = path + result.append(file_copy) if mimetypes: - files = list(filter(lambda j: any(j['mimetype'].startswith(m) for m in mimetypes), files)) + result = list(filter(lambda j: any(j['mimetype'].startswith(m) for m in mimetypes), result)) if PYTEST: # Sort files to avoid random order during testing. - return sorted(files, key=lambda j: j['path']) - return files + return sorted(result, key=lambda j: j['path']) + return result def my_paths(self, *mimetypes: str) -> List[pathlib.Path]: return [i['path'] for i in self.my_files(*mimetypes)] @@ -368,6 +419,7 @@ class FileGroup(ModelHelper, Base): if not isinstance(primary_path, pathlib.Path): raise ValueError('Cannot create FileGroup without a primary path.') + file_group.directory = primary_path.parent file_group.primary_path = primary_path file_group.modification_datetime = from_timestamp(max(i.stat().st_mtime for i in paths)) file_group.size = sum(i.stat().st_size for i in paths) @@ -395,6 +447,20 @@ class FileGroup(ModelHelper, Base): raise UnknownFile(f'Unable to find FileGroup with path {path}') return file_group + @classmethod + def find_by_directory(cls, session: Session, directory: pathlib.Path, recursive: bool = False) -> List['FileGroup']: + """Find all FileGroups in a directory (optionally recursive). + + Uses the indexed `directory` column for efficient lookups. + """ + from sqlalchemy import or_ + directory_str = str(directory) + if recursive: + return session.query(cls).filter( + or_(cls.directory == directory_str, cls.directory.like(f'{directory_str}/%')) + ).all() + return session.query(cls).filter(cls.directory == directory_str).all() + @property def tag_names(self) -> List[str]: result = [] @@ -434,7 +500,15 @@ class FileGroup(ModelHelper, Base): self.files = collected_files def move(self, new_primary_path: pathlib.Path): - """Move all files in this group to a new location.""" + """Move all files in this group to a new location. + + With relative paths stored in `files` and `data`, we only need to: + 1. Move physical files to new location + 2. Update `directory` to point to new parent + 3. Update `primary_path` to the new path + + The relative filenames in `files` and `data` remain unchanged. + """ from wrolpi.files.lib import split_path_stem_and_suffix, glob_shared_stem, split_file_name_words if new_primary_path.exists(): @@ -445,71 +519,47 @@ class FileGroup(ModelHelper, Base): self.append_files(*glob_shared_stem(self.primary_path)) new_name, _ = split_path_stem_and_suffix(new_primary_path, full=True) - # Need a deepcopy because changes to self.files are ignored otherwise. - new_files = copy.deepcopy(self.files) + new_directory = new_primary_path.parent + + # Get current files with resolved absolute paths for moving + current_files = self.my_files() + # Ensure that all destination files do not yet exist before move. - for file in new_files: + for file in current_files: _, suffix = split_path_stem_and_suffix(file['path']) new_path = pathlib.Path(f'{new_name}{suffix}') if new_path.exists(): raise FileExistsError(f'Cannot move {self} to {new_path} because it already exists.') - # Collect all files that exist and move them. - existing_files = list() - for idx, file in enumerate(new_files): - _, suffix = split_path_stem_and_suffix(file['path']) + # Move physical files and collect new relative file entries + new_files = [] + for file in current_files: + old_path = file['path'] # Already resolved to absolute by my_files() + _, suffix = split_path_stem_and_suffix(old_path) new_path = pathlib.Path(f'{new_name}{suffix}') - if pathlib.Path(file['path']).is_file(): - shutil.move(file['path'], new_path) - existing_files.append({'path': new_path, 'mimetype': file['mimetype']}) + if old_path.is_file(): + shutil.move(old_path, new_path) + # Store just the filename (relative path) + new_files.append({'path': new_path.name, 'mimetype': file['mimetype']}) logger.debug(f'Moved FileGroup: {self.primary_path} -> {new_primary_path}') - self.files = existing_files - # Update paths in self.data to match new file locations - if self.data: - old_parent = str(self.primary_path.parent) - new_parent = str(new_primary_path.parent) - updated_data = {} - for key, value in self.data.items(): - if value is None: - updated_data[key] = value - elif isinstance(value, pathlib.Path): - str_value = str(value) - if str_value.startswith(old_parent): - updated_data[key] = pathlib.Path(str_value.replace(old_parent, new_parent, 1)) - else: - updated_data[key] = value - elif isinstance(value, str) and value.startswith(old_parent): - updated_data[key] = value.replace(old_parent, new_parent, 1) - elif isinstance(value, list): - # Handle lists (like Video.caption_paths) - new_list = [] - for item in value: - if isinstance(item, pathlib.Path): - str_item = str(item) - if str_item.startswith(old_parent): - new_list.append(pathlib.Path(str_item.replace(old_parent, new_parent, 1))) - else: - new_list.append(item) - elif isinstance(item, str) and item.startswith(old_parent): - new_list.append(item.replace(old_parent, new_parent, 1)) - else: - new_list.append(item) - updated_data[key] = new_list - else: - updated_data[key] = value - self.data = updated_data + # Update the FileGroup with new directory and relative files + self.files = new_files + self.directory = new_directory + self.primary_path = new_primary_path + # Update title if it was based on the filename if self.title == self.primary_path.name: - # Do not overwrite title from modeler. self.title = new_primary_path.name self.a_text = split_file_name_words(new_primary_path.name) - self.primary_path = new_primary_path - # Data paths are updated in-place above, no need to re-index for existing data. + + # Note: `data` now contains relative paths that don't need updating! + # The filenames stay the same, only the directory changes. # Only re-index if there's no data yet (new file that hasn't been modeled). if not self.data: self.indexed = False + # Flush the changes to the FileGroup. self.flush() @@ -524,7 +574,7 @@ class FileGroup(ModelHelper, Base): if instance and hasattr(instance, 'location'): return instance.location - parent = str(get_relative_to_media_directory(self.primary_path.parent)) + parent = str(get_relative_to_media_directory(self.directory)) preview = str(get_relative_to_media_directory(self.primary_path)) if parent == '.': # File is in the top of the media directory, App already shows top directory open. diff --git a/wrolpi/files/test/test_ebooks.py b/wrolpi/files/test/test_ebooks.py index ba1adf08..13046f35 100644 --- a/wrolpi/files/test/test_ebooks.py +++ b/wrolpi/files/test/test_ebooks.py @@ -23,9 +23,10 @@ async def test_index(async_client, test_session, test_directory, example_epub, e assert ebook.file_group.mimetype.startswith(EPUB_MIMETYPE) assert ebook.file_group.author == 'roland' assert ebook.size == 292579 + # data now stores relative filenames only (not absolute paths) assert ebook.file_group.data == {'author': 'roland', 'title': 'WROLPi Test Book', - 'cover_path': test_directory / 'ebook example.jpeg', - 'ebook_path': test_directory / 'ebook example.epub', + 'cover_path': 'ebook example.jpeg', + 'ebook_path': 'ebook example.epub', } assert ebook.file_group.a_text, 'Book title was not indexed' @@ -129,7 +130,8 @@ async def test_discover_calibre_cover(test_session, async_client, test_directory ebook: EBook = test_session.query(EBook).one() assert ebook.file_group.title == 'WROLPi Test Book' assert ebook.cover_file['path'] == test_directory / 'cover.jpg' - assert {i['path'].name for i in ebook.file_group.files} == {'ebook example.epub', 'ebook example.mobi', 'cover.jpg'} + # Use my_files() to get resolved Path objects + assert {i['path'].name for i in ebook.file_group.my_files()} == {'ebook example.epub', 'ebook example.mobi', 'cover.jpg'} # Cover is not the first image from the EPUB. assert ebook.cover_path.stat().st_size != 292579 # Metadata and cover were deleted from the FileGroups. @@ -146,7 +148,8 @@ async def test_move_ebook(async_client, test_session, test_directory, example_ep ebook: EBook = test_session.query(EBook).one() assert ebook.cover_path assert_dict_contains(ebook.file_group.data, dict(author='roland')) - assert sorted([i['path'] for i in ebook.file_group.files]) == [ + # Use my_files() to get resolved absolute Path objects + assert sorted([i['path'] for i in ebook.file_group.my_files()]) == [ test_directory / 'ebook example.epub', test_directory / 'ebook example.jpg', ] @@ -161,7 +164,8 @@ async def test_move_ebook(async_client, test_session, test_directory, example_ep assert ebook.file_group.primary_path == test_directory / 'new/ebook example.epub' assert ebook.cover_path assert_dict_contains(ebook.file_group.data, dict(author='roland')) - assert sorted([i['path'] for i in ebook.file_group.files]) == [ + # Use my_files() to get resolved absolute Path objects + assert sorted([i['path'] for i in ebook.file_group.my_files()]) == [ test_directory / 'new/ebook example.epub', test_directory / 'new/ebook example.jpg', ] diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index 708d78db..23cc18c7 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -251,17 +251,18 @@ async def test__upsert_files(test_session, make_files_structure, test_directory, # All files are found because they are in this refresh request, or in the `dir1` directory. idempotency = now() lib._upsert_files([video_file, srt_file3, bar, baz], idempotency) + # Note: files now store relative filenames only (not absolute paths) assert_file_groups([ {'primary_path': video_file, 'idempotency': idempotency, 'indexed': False, 'files': [ - {'path': srt_file3, 'size': 951, 'suffix': '.en.srt', 'mimetype': 'text/srt'}, - {'path': video_file, 'size': 1056318, 'suffix': '.mp4', 'mimetype': 'video/mp4'}, + {'path': srt_file3.name, 'size': 951, 'suffix': '.en.srt', 'mimetype': 'text/srt'}, + {'path': video_file.name, 'size': 1056318, 'suffix': '.mp4', 'mimetype': 'video/mp4'}, ]}, {'primary_path': bar, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': bar, 'size': 0, 'suffix': '.txt', 'mimetype': 'inode/x-empty'}] + 'files': [{'path': bar.name, 'size': 0, 'suffix': '.txt', 'mimetype': 'inode/x-empty'}] }, {'primary_path': baz, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': baz, 'size': 8, 'suffix': '.txt', 'mimetype': 'text/plain'}] + 'files': [{'path': baz.name, 'size': 8, 'suffix': '.txt', 'mimetype': 'text/plain'}] }, ]) @@ -278,17 +279,18 @@ async def test__upsert_files(test_session, make_files_structure, test_directory, # Only modified files need to be re-indexed. lib._upsert_files([video_file, srt_file3, bar, baz], idempotency) + # Note: files now store relative filenames only (not absolute paths) assert_file_groups([ {'primary_path': video_file, 'idempotency': idempotency, 'indexed': True, 'files': [ - {'path': srt_file3, 'size': 951, 'suffix': '.en.srt', 'mimetype': 'text/srt'}, - {'path': video_file, 'size': 1056318, 'suffix': '.mp4', 'mimetype': 'video/mp4'}, + {'path': srt_file3.name, 'size': 951, 'suffix': '.en.srt', 'mimetype': 'text/srt'}, + {'path': video_file.name, 'size': 1056318, 'suffix': '.mp4', 'mimetype': 'video/mp4'}, ]}, {'primary_path': bar, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': bar, 'size': 0, 'suffix': '.txt', 'mimetype': 'inode/x-empty'}], + 'files': [{'path': bar.name, 'size': 0, 'suffix': '.txt', 'mimetype': 'inode/x-empty'}], }, {'primary_path': baz, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': baz, 'size': 7, 'suffix': '.txt', 'mimetype': 'text/plain'}], + 'files': [{'path': baz.name, 'size': 7, 'suffix': '.txt', 'mimetype': 'text/plain'}], }, ]) @@ -297,15 +299,16 @@ async def test__upsert_files(test_session, make_files_structure, test_directory, lib._upsert_files([video_file, bar, baz], idempotency) video_file_group: FileGroup = test_session.query(FileGroup).filter_by(primary_path=str(video_file)).one() assert len(video_file_group.files) == 1, 'SRT file was not removed from files' + # Note: files now store relative filenames only (not absolute paths) assert_file_groups([ # Video is no longer indexed because SRT was removed. {'primary_path': video_file, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': video_file, 'size': 1056318, 'suffix': '.mp4', 'mimetype': 'video/mp4'}]}, + 'files': [{'path': video_file.name, 'size': 1056318, 'suffix': '.mp4', 'mimetype': 'video/mp4'}]}, {'primary_path': bar, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': bar, 'size': 0, 'suffix': '.txt', 'mimetype': 'inode/x-empty'}], + 'files': [{'path': bar.name, 'size': 0, 'suffix': '.txt', 'mimetype': 'inode/x-empty'}], }, {'primary_path': baz, 'idempotency': idempotency, 'indexed': False, - 'files': [{'path': baz, 'size': 7, 'suffix': '.txt', 'mimetype': 'text/plain'}], + 'files': [{'path': baz.name, 'size': 7, 'suffix': '.txt', 'mimetype': 'text/plain'}], }, ]) @@ -766,11 +769,12 @@ async def test_file_group_merge(async_client, test_session, test_directory, make # Both FileGroups are merged. vid = FileGroup.from_paths(test_session, vid, srt) test_session.commit() - assert {i['path'].name for i in vid.files} == {'vid.mp4', 'vid.srt'} + # files now stores relative filenames as strings, use my_files() to get resolved Paths + assert {i['path'].name for i in vid.my_files()} == {'vid.mp4', 'vid.srt'} assert test_session.query(FileGroup).count() == 1 assert set(vid.tag_names) == {'one', 'two'} - assert {i['path'].name for i in vid.files} == {'vid.mp4', 'vid.srt'} + assert {i['path'].name for i in vid.my_files()} == {'vid.mp4', 'vid.srt'} # TagFile.created_at is preserved. assert [i for i in vid.tag_files if i.tag.name == 'one'][0].created_at == tag_file_created_at assert [i for i in vid.tag_files if i.tag.name == 'two'][0].created_at == srt_file_created_at @@ -985,13 +989,16 @@ async def test_move_tagged(async_client, test_session, test_directory, make_file assert not (test_directory / 'foo/bar.txt').exists() # Tag was moved. bar_file_group, foo_file_group = test_session.query(FileGroup).order_by(FileGroup.primary_path) - assert bar_file_group.primary_path == new_bar == bar_file_group.files[0]['path'] + assert bar_file_group.primary_path == new_bar + # files now stores relative filenames; use my_files() to get resolved absolute paths + assert bar_file_group.my_files()[0]['path'] == new_bar assert bar_file_group.primary_path.is_file() assert bar_file_group.tag_files # foo.txt was not tagged, but was moved. assert not foo_file_group.tag_files assert foo_file_group.primary_path.is_file() - assert foo_file_group.primary_path == new_foo == foo_file_group.files[0]['path'] + assert foo_file_group.primary_path == new_foo + assert foo_file_group.my_files()[0]['path'] == new_foo assert bar_file_group.title == 'custom title', 'Custom title should not have been overwritten.' # Rename "bar.txt" to "baz.txt" @@ -1306,7 +1313,8 @@ async def test_process_bulk_tag_job_add_tags(test_case, expected_fg_count, async # Additional assertion for multi-file FileGroup if test_case == 'multi_file_filegroup': - file_paths = {f['path'].name for f in fgs[0].files} + # files now stores relative filenames as strings; use my_files() to get resolved Paths + file_paths = {f['path'].name for f in fgs[0].my_files()} assert file_paths == {'video.mp4', 'video.srt', 'video.info.json'}