| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import shutil |
| 4 |
from pathlib import Path |
| 5 |
from typing import TYPE_CHECKING |
| 6 |
|
| 7 |
import mediafile |
| 8 |
|
| 9 |
from beets import ui, util |
| 10 |
from beets.exceptions import UserError |
| 11 |
from beets.plugins import BeetsPlugin |
| 12 |
|
| 13 |
if TYPE_CHECKING: |
| 14 |
import optparse |
| 15 |
from collections.abc import Sequence |
| 16 |
|
| 17 |
from beets.library import Item, Library |
| 18 |
|
| 19 |
|
| 20 |
class ReplacePlugin(BeetsPlugin): |
| 21 |
def commands(self) -> list[ui.Subcommand]: |
| 22 |
cmd = ui.Subcommand( |
| 23 |
"replace", help="replace audio file while keeping tags" |
| 24 |
) |
| 25 |
cmd.func = self.run |
| 26 |
return [cmd] |
| 27 |
|
| 28 |
def run( |
| 29 |
self, lib: Library, _opts: optparse.Values, args: list[str] |
| 30 |
) -> None: |
| 31 |
if len(args) < 2: |
| 32 |
raise UserError("Usage: beet replace <query> <new_file_path>") |
| 33 |
|
| 34 |
new_file_path: Path = Path(args[-1]) |
| 35 |
item_query: list[str] = args[:-1] |
| 36 |
|
| 37 |
self.file_check(new_file_path) |
| 38 |
|
| 39 |
item_list = list(lib.items(item_query)) |
| 40 |
|
| 41 |
if not item_list: |
| 42 |
raise UserError("No matching songs found.") |
| 43 |
|
| 44 |
song = self.select_song(item_list) |
| 45 |
|
| 46 |
if not song: |
| 47 |
ui.print_("Operation cancelled.") |
| 48 |
return |
| 49 |
|
| 50 |
if not self.confirm_replacement(new_file_path, song): |
| 51 |
ui.print_("Aborting replacement.") |
| 52 |
return |
| 53 |
|
| 54 |
self.replace_file(new_file_path, song) |
| 55 |
|
| 56 |
def file_check(self, filepath: Path) -> None: |
| 57 |
"""Check if the file exists and is supported""" |
| 58 |
if not filepath.is_file(): |
| 59 |
raise UserError( |
| 60 |
f"'{util.displayable_path(filepath)}' is not a valid file." |
| 61 |
) |
| 62 |
|
| 63 |
try: |
| 64 |
mediafile.MediaFile(util.syspath(filepath)) |
| 65 |
except mediafile.FileTypeError as fte: |
| 66 |
raise UserError(fte) |
| 67 |
|
| 68 |
def select_song(self, items: Sequence[Item]) -> Item | None: |
| 69 |
"""Present a menu of matching songs and get user selection.""" |
| 70 |
ui.print_("\nMatching songs:") |
| 71 |
for i, item in enumerate(items, 1): |
| 72 |
ui.print_(f"{i}. {util.displayable_path(item)}") |
| 73 |
|
| 74 |
while True: |
| 75 |
try: |
| 76 |
index = int( |
| 77 |
input( |
| 78 |
f"Which song would you like to replace? " |
| 79 |
f"[1-{len(items)}] (0 to cancel): " |
| 80 |
) |
| 81 |
) |
| 82 |
if index == 0: |
| 83 |
return None |
| 84 |
if 1 <= index <= len(items): |
| 85 |
return items[index - 1] |
| 86 |
ui.print_( |
| 87 |
f"Invalid choice. Please enter a number " |
| 88 |
f"between 1 and {len(items)}." |
| 89 |
) |
| 90 |
except ValueError: |
| 91 |
ui.print_("Invalid input. Please type in a number.") |
| 92 |
|
| 93 |
def confirm_replacement(self, new_file_path: Path, song: Item) -> bool: |
| 94 |
"""Get user confirmation for the replacement.""" |
| 95 |
original_file_path: Path = Path(song.path.decode()) |
| 96 |
|
| 97 |
if not original_file_path.exists(): |
| 98 |
raise UserError("The original song file was not found.") |
| 99 |
|
| 100 |
ui.print_( |
| 101 |
f"\nReplacing: {util.displayable_path(new_file_path)} " |
| 102 |
f"-> {util.displayable_path(original_file_path)}" |
| 103 |
) |
| 104 |
decision: str = ( |
| 105 |
input("Are you sure you want to replace this track? (y/N): ") |
| 106 |
.strip() |
| 107 |
.casefold() |
| 108 |
) |
| 109 |
return decision in {"yes", "y"} |
| 110 |
|
| 111 |
def replace_file(self, new_file_path: Path, song: Item) -> None: |
| 112 |
"""Replace the existing file with the new one.""" |
| 113 |
original_file_path = Path(song.path.decode()) |
| 114 |
dest = original_file_path.with_suffix(new_file_path.suffix) |
| 115 |
|
| 116 |
try: |
| 117 |
shutil.move(util.syspath(new_file_path), util.syspath(dest)) |
| 118 |
except Exception as e: |
| 119 |
raise UserError(f"Error replacing file: {e}") |
| 120 |
|
| 121 |
if ( |
| 122 |
new_file_path.suffix != original_file_path.suffix |
| 123 |
and original_file_path.exists() |
| 124 |
): |
| 125 |
try: |
| 126 |
original_file_path.unlink() |
| 127 |
except Exception as e: |
| 128 |
raise UserError(f"Could not delete original file: {e}") |
| 129 |
|
| 130 |
song.path = str(dest).encode() |
| 131 |
song.store() |
| 132 |
|
| 133 |
ui.print_("Replacement successful.") |