Remove a file's Tags Directory links when WROLPi deletes it (#861)

* Remove a file's Tags Directory links when WROLPi deletes it

When WROLPi deleted a tagged file (a forced delete, duplicate Video cleanup, or a poster conversion), the
source was unlinked but its Tags Directory hardlink was not.  The link became the only copy, so the tags sync
refused to delete it and warned on every sync.  The links of a file are now removed before WROLPi removes it,
and only if the link is the same file as its source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove Tags Directory links on path deletes; keep a valid poster's link

The file browser deletes by path (`lib.delete`), which unlinks the sources before any FileGroup is
deleted, so its tagged files still left orphaned links.  It now removes the links of the files it is about
to delete, or of every FileGroup in a deleted directory.

A poster is no longer unlinked from the Tags Directory unless it is actually removed: a valid JPEG that is
not named .jpg is kept with its link, and a converted poster's links are removed only once the conversion
succeeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-10-23 14:34:51 -06:00 • committed by Roland
parent da3dadde07
commit 9bbef50ca1
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
7 changed files with 178 additions and 2 deletions

View file

@ -216,15 +216,20 @@ def convert_or_generate_poster(video: Video) -> Tuple[Optional[pathlib.Path], Op
if old != new and new.exists():
# Destination JPEG already exists (it may have the wrong format).
video.file_group.unlink_tag_directory_links(old)
old.unlink()
old = new
if not is_valid_poster(old):
# Poster is not valid, convert it and place it in the new location.
# Poster is not valid, convert it and place it in the new location. Conversion removes `old`, so its
# Tags Directory links are found now and removed only once the conversion succeeds.
old_links = video.file_group.get_tag_directory_links(old) if old != new else []
try:
convert_image(old, new)
if not new.is_file() or not new.stat().st_size:
raise FileNotFoundError(f'Failed to convert poster: {new}')
for link in old_links:
link.unlink(missing_ok=True)
logger.info(f'Converted invalid poster {repr(str(old))} to {repr(str(new))}')
return new, None
except Exception as e:

View file

@ -515,6 +515,8 @@ class Video(ModelHelper, Base):
def delete_video(video_: Video):
"""Delete a Video with any of its tags."""
# Untagging forgets which links are this Video's, so remove them first.
video_.file_group.unlink_tag_directory_links()
for tag_name_ in video_.file_group.tag_names:
video_.file_group.untag(session, tag_name_)
video_.delete()

View file

@ -593,3 +593,37 @@ def test_download_settings_codec_validation():
with pytest.raises(ValidationError):
DownloadSettings(audio_codecs=['wma'])
@pytest.mark.asyncio
async def test_convert_poster_removes_tags_directory_link(async_client, test_session, test_directory, video_factory,
tag_factory, await_switches):
"""Converting a tagged Video's poster removes the old poster's Tags Directory link."""
tag = await tag_factory()
video = video_factory(with_video_file=True, with_poster_ext='webp', tag_names=[tag.name])
test_session.commit()
await await_switches()
webp_link = test_directory / 'tags' / tag.name / video.poster_path.name
assert webp_link.is_file()
new_poster, _ = lib.convert_or_generate_poster(video)
assert new_poster.suffix == '.jpg'
assert not webp_link.exists(), 'The converted poster left its link behind'
@pytest.mark.asyncio
async def test_valid_poster_keeps_tags_directory_link(async_client, test_session, test_directory, video_factory,
tag_factory, await_switches):
"""A valid JPEG poster that is not named .jpg is not converted, so its Tags Directory link is kept."""
tag = await tag_factory()
video = video_factory(with_video_file=True, with_poster_ext='jpeg', tag_names=[tag.name])
test_session.commit()
await await_switches()
poster_link = test_directory / 'tags' / tag.name / video.poster_path.name
assert poster_link.is_file()
lib.convert_or_generate_poster(video)
assert video.poster_path.is_file()
assert poster_link.is_file() and poster_link.samefile(video.poster_path)

View file

@ -240,6 +240,33 @@ async def test_delete_duplicate_video_tagged_duplicate(async_client, test_sessio
assert video.file_group.tag_names == [tag.name, ]
@pytest.mark.asyncio
async def test_delete_duplicate_video_leaves_no_tags_directory_orphans(async_client, test_session, test_directory,
channel_factory, video_factory, tag_factory,
await_switches):
"""Deleting a tagged duplicate Video removes its Tags Directory links; only links to existing files remain."""
channel = channel_factory(name='Channel Name')
video_path = channel.directory / f'{channel.name}_20000101_ABC123456_The video title.mp4'
tag = await tag_factory()
for title in (f'{channel.name}_20000101_ABC123456_The video title',
f'{channel.name}_20000101_ABC123456_The video title '):
video = video_factory(channel_id=channel.id, title=title, upload_date=datetime(2000, 1, 1, tzinfo=timezone.utc),
source_id='ABC123456', with_video_file=True, with_info_json=True, tag_names=[tag.name])
video.file_group.url = 'https://example.com/video'
test_session.commit()
await await_switches()
tags_directory = test_directory / 'tags'
assert len([i for i in tags_directory.rglob('*.mp4')]) == 2
assert await Video.delete_duplicate_videos(test_session, 'https://example.com/video', 'ABC123456', video_path)
test_session.commit()
await await_switches()
links = [i for i in tags_directory.rglob('*') if i.is_file() and i.name != 'README.txt']
assert links, 'The kept Video is still linked'
assert all(i.stat().st_nlink > 1 for i in links), 'A link was left behind with no source file'
@pytest.mark.asyncio
async def test_delete_duplicate_video_smaller_copy_at_destination(async_client, test_session, channel_factory,
video_factory):