| 1 |
"""Synchronise library metadata with metadata source backends.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections import defaultdict |
| 6 |
from typing import TYPE_CHECKING, Protocol |
| 7 |
|
| 8 |
from beets import library, metadata_plugins, ui, util |
| 9 |
from beets.autotag import AlbumMatch, Distance, TrackMatch |
| 10 |
from beets.plugins import BeetsPlugin, apply_item_changes |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from collections.abc import Sequence |
| 14 |
|
| 15 |
from beets.library import Library |
| 16 |
|
| 17 |
|
| 18 |
class MBSyncCLIOpts(Protocol): |
| 19 |
move: bool | None |
| 20 |
pretend: bool |
| 21 |
write: bool | None |
| 22 |
|
| 23 |
|
| 24 |
class MBSyncPlugin(BeetsPlugin): |
| 25 |
def __init__(self) -> None: |
| 26 |
super().__init__() |
| 27 |
|
| 28 |
def commands(self) -> list[ui.Subcommand]: |
| 29 |
cmd = ui.Subcommand("mbsync", help="update metadata from musicbrainz") |
| 30 |
cmd.parser.add_option( |
| 31 |
"-p", |
| 32 |
"--pretend", |
| 33 |
action="store_true", |
| 34 |
default=False, |
| 35 |
help="show all changes but do nothing", |
| 36 |
) |
| 37 |
cmd.parser.add_option( |
| 38 |
"-m", |
| 39 |
"--move", |
| 40 |
action="store_true", |
| 41 |
dest="move", |
| 42 |
help="move files in the library directory", |
| 43 |
) |
| 44 |
cmd.parser.add_option( |
| 45 |
"-M", |
| 46 |
"--nomove", |
| 47 |
action="store_false", |
| 48 |
dest="move", |
| 49 |
help="don't move files in library", |
| 50 |
) |
| 51 |
cmd.parser.add_option( |
| 52 |
"-W", |
| 53 |
"--nowrite", |
| 54 |
action="store_false", |
| 55 |
default=None, |
| 56 |
dest="write", |
| 57 |
help="don't write updated metadata to files", |
| 58 |
) |
| 59 |
cmd.parser.add_format_option() |
| 60 |
cmd.func = self.func |
| 61 |
return [cmd] |
| 62 |
|
| 63 |
def func(self, lib: Library, opts: MBSyncCLIOpts, args: list[str]) -> None: |
| 64 |
"""Command handler for the mbsync function.""" |
| 65 |
move = ui.should_move(opts.move) |
| 66 |
pretend = opts.pretend |
| 67 |
write = ui.should_write(opts.write) |
| 68 |
|
| 69 |
self.singletons(lib, args, move, pretend, write) |
| 70 |
self.albums(lib, args, move, pretend, write) |
| 71 |
|
| 72 |
def singletons( |
| 73 |
self, |
| 74 |
lib: Library, |
| 75 |
query: Sequence[str], |
| 76 |
move: bool, |
| 77 |
pretend: bool, |
| 78 |
write: bool, |
| 79 |
) -> None: |
| 80 |
"""Retrieve and apply info from the autotagger for items matched by |
| 81 |
query. |
| 82 |
""" |
| 83 |
for item in lib.items([*query, "singleton:true"]): |
| 84 |
if not (track_id := item.mb_trackid): |
| 85 |
self._log.info( |
| 86 |
"Skipping singleton with no mb_trackid: {}", item |
| 87 |
) |
| 88 |
continue |
| 89 |
|
| 90 |
if not ( |
| 91 |
track_info := metadata_plugins.track_for_id( |
| 92 |
track_id, item.get("data_source", "MusicBrainz") |
| 93 |
) |
| 94 |
): |
| 95 |
self._log.info( |
| 96 |
"Recording ID not found: {} for track {}", track_id, item |
| 97 |
) |
| 98 |
continue |
| 99 |
|
| 100 |
# Apply. |
| 101 |
with lib.transaction(): |
| 102 |
TrackMatch(Distance(), track_info, item).apply_metadata( |
| 103 |
from_scratch=False |
| 104 |
) |
| 105 |
apply_item_changes(lib, item, move, pretend, write) |
| 106 |
|
| 107 |
def albums( |
| 108 |
self, |
| 109 |
lib: Library, |
| 110 |
query: Sequence[str], |
| 111 |
move: bool, |
| 112 |
pretend: bool, |
| 113 |
write: bool, |
| 114 |
) -> None: |
| 115 |
"""Retrieve and apply info from the autotagger for albums matched by |
| 116 |
query and their items. |
| 117 |
""" |
| 118 |
# Process matching albums. |
| 119 |
for album in lib.albums(query): |
| 120 |
if not (album_id := album.mb_albumid): |
| 121 |
self._log.info("Skipping album with no mb_albumid: {}", album) |
| 122 |
continue |
| 123 |
|
| 124 |
data_source = album.get("data_source") or album.items()[0].get( |
| 125 |
"data_source", "MusicBrainz" |
| 126 |
) |
| 127 |
if not ( |
| 128 |
album_info := metadata_plugins.album_for_id( |
| 129 |
album_id, data_source |
| 130 |
) |
| 131 |
): |
| 132 |
self._log.info( |
| 133 |
"Release ID {} not found for album {}", album_id, album |
| 134 |
) |
| 135 |
continue |
| 136 |
|
| 137 |
# Map release track and recording MBIDs to their information. |
| 138 |
# Recordings can appear multiple times on a release, so each MBID |
| 139 |
# maps to a list of TrackInfo objects. |
| 140 |
releasetrack_index = {} |
| 141 |
track_index = defaultdict(list) |
| 142 |
for track_info in album_info.tracks: |
| 143 |
releasetrack_index[track_info.release_track_id] = track_info |
| 144 |
track_index[track_info.track_id].append(track_info) |
| 145 |
|
| 146 |
# Construct a track mapping according to MBIDs (release track MBIDs |
| 147 |
# first, if available, and recording MBIDs otherwise). This should |
| 148 |
# work for albums that have missing or extra tracks. |
| 149 |
item_info_pairs = [] |
| 150 |
items = list(album.items()) |
| 151 |
for item in items: |
| 152 |
if ( |
| 153 |
item.mb_releasetrackid |
| 154 |
and item.mb_releasetrackid in releasetrack_index |
| 155 |
): |
| 156 |
item_info_pairs.append( |
| 157 |
(item, releasetrack_index[item.mb_releasetrackid]) |
| 158 |
) |
| 159 |
else: |
| 160 |
candidates = track_index[item.mb_trackid] |
| 161 |
if len(candidates) == 1: |
| 162 |
item_info_pairs.append((item, candidates[0])) |
| 163 |
else: |
| 164 |
# If there are multiple copies of a recording, they are |
| 165 |
# disambiguated using their disc and track number. |
| 166 |
for c in candidates: |
| 167 |
if ( |
| 168 |
c.medium_index == item.track |
| 169 |
and c.medium == item.disc |
| 170 |
): |
| 171 |
item_info_pairs.append((item, c)) |
| 172 |
break |
| 173 |
|
| 174 |
# Apply. |
| 175 |
self._log.debug("applying changes to {}", album) |
| 176 |
with lib.transaction(): |
| 177 |
AlbumMatch( |
| 178 |
Distance(), album_info, dict(item_info_pairs) |
| 179 |
).apply_metadata(from_scratch=False) |
| 180 |
changed = False |
| 181 |
# Find any changed item to apply changes to album. |
| 182 |
any_changed_item = items[0] |
| 183 |
for item in items: |
| 184 |
item_changed = ui.show_model_changes(item) |
| 185 |
changed |= item_changed |
| 186 |
if item_changed: |
| 187 |
any_changed_item = item |
| 188 |
apply_item_changes(lib, item, move, pretend, write) |
| 189 |
|
| 190 |
if not changed: |
| 191 |
# No change to any item. |
| 192 |
continue |
| 193 |
|
| 194 |
if not pretend: |
| 195 |
# Update album structure to reflect an item in it. |
| 196 |
for key in library.Album.item_keys: |
| 197 |
album[key] = any_changed_item[key] |
| 198 |
album.store() |
| 199 |
|
| 200 |
# Move album art (and any inconsistent items). |
| 201 |
if move and lib.directory in util.ancestry(items[0].path): |
| 202 |
self._log.debug("moving album {}", album) |
| 203 |
album.move() |