add prune_dead_tracks()

This commit is contained in:
iou1name 2025-03-22 21:12:47 -04:00
parent d5c1a787f7
commit 7b06f62fe7

View File

@ -108,5 +108,38 @@ async def build_library(root_dir):
await cur.executemany(tracks_data) await cur.executemany(tracks_data)
print("Done") print("Done")
async def prune_dead_tracks(root_dir):
"""Removes tracks which exist in the database but not in the library."""
print("Scanning library...")
db_pool = await asyncpg.create_pool(**config.db)
lib_filepaths = []
for dir_path, sub_dirs, files in os.walk(root_dir):
for file in files:
if not os.path.splitext(file)[1] in MUSIC_EXT:
continue
filepath = os.path.join(root_dir, dir_path, file)
filepath = os.path.relpath(filepath, config.music_dir)
lib_filepaths.append(filepath)
async with db_pool.acquire() as conn:
db_filepaths = await conn.fetch("SELECT filepath FROM track")
db_filepaths = [track['filepath'] for track in db_filepaths]
filepaths_to_prune = []
for db_filepath in db_filepaths:
if db_filepath not in lib_filepaths:
filepaths_to_prune.append((db_filepath,))
print("Found", len(filepaths_to_prune), "dead tracks. Pruning...")
async with db_pool.acquire() as conn:
stmt = await conn.prepare("DELETE FROM track WHERE filepath = $1")
await stmt.executemany(filepaths_to_prune)
print("Done")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(build_library(config.music_dir)) #asyncio.run(build_library(config.music_dir))
asyncio.run(prune_dead_tracks(config.music_dir))