From 0ec6eee7e9ef4b37036679b502050f8450f272aa Mon Sep 17 00:00:00 2001 From: Parsa Sadeghi Asl Date: Thu, 3 Apr 2025 19:26:55 +0330 Subject: [PATCH] implement playlist image cleaner --- app/api/playlist.py | 2 ++ app/lib/playlistlib.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/app/api/playlist.py b/app/api/playlist.py index 80ddf137..73280acb 100644 --- a/app/api/playlist.py +++ b/app/api/playlist.py @@ -318,6 +318,7 @@ def update_playlist_info(path: PlaylistIDPath, form: UpdatePlaylistForm): p_tuple = (*playlist.values(),) PlaylistTable.update_one(playlistid, playlist) + playlistlib.cleanup_playlist_images() playlist = models.Playlist(*p_tuple) playlist.last_updated = date_string_to_time_passed(playlist.last_updated) @@ -377,6 +378,7 @@ def remove_playlist(path: PlaylistIDPath): Delete playlist """ PlaylistTable.remove_one(path.playlistid) + playlistlib.cleanup_playlist_images() return {"msg": "Done"}, 200 diff --git a/app/lib/playlistlib.py b/app/lib/playlistlib.py index a1a33151..e1fe682b 100644 --- a/app/lib/playlistlib.py +++ b/app/lib/playlistlib.py @@ -135,3 +135,37 @@ def get_first_4_images( return images return duplicate_images(images) + + +def cleanup_playlist_images(): + """ + Cleans up unlinked playlist images by comparing files in the playlist image directory + against the .image property of all playlists. + """ + # Import here to avoid circular import + from app.db.userdata import PlaylistTable + + playlists = PlaylistTable.get_all() + linked_images = {p.image for p in playlists if p.image and p.image != "None"} + + playlist_dir = settings.Paths.get_playlist_img_path() + all_files = os.listdir(playlist_dir) + + # Find unlinked images (including thumbnails) + unlinked_files = [] + for file in all_files: + if file.startswith("thumb_"): + base_file = file[6:] # Remove "thumb_" prefix + if base_file not in linked_images: + unlinked_files.append(file) + + elif file not in linked_images: + unlinked_files.append(file) + + + for file in unlinked_files: + try: + os.remove(os.path.join(playlist_dir, file)) + except OSError: + # Skip if file doesn't exist or can't be deleted + pass