| 1 |
"""List missing tracks.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections import defaultdict |
| 6 |
from typing import TYPE_CHECKING, ClassVar |
| 7 |
|
| 8 |
import requests |
| 9 |
|
| 10 |
from beets import config, metadata_plugins |
| 11 |
from beets.dbcore import types |
| 12 |
from beets.library import Album, Item |
| 13 |
from beets.plugins import BeetsPlugin |
| 14 |
from beets.ui import Subcommand, print_ |
| 15 |
|
| 16 |
from ._utils.musicbrainz import MusicBrainzAPIMixin |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
import optparse |
| 20 |
from collections.abc import Iterator |
| 21 |
|
| 22 |
from beets.autotag import AlbumInfo, TrackInfo |
| 23 |
from beets.library import Library |
| 24 |
|
| 25 |
# Valid MusicBrainz release types for filtering release groups |
| 26 |
VALID_RELEASE_TYPES = [ |
| 27 |
"nat", |
| 28 |
"album", |
| 29 |
"single", |
| 30 |
"ep", |
| 31 |
"broadcast", |
| 32 |
"other", |
| 33 |
"compilation", |
| 34 |
"soundtrack", |
| 35 |
"spokenword", |
| 36 |
"interview", |
| 37 |
"audiobook", |
| 38 |
"live", |
| 39 |
"remix", |
| 40 |
"dj-mix", |
| 41 |
"mixtape/street", |
| 42 |
] |
| 43 |
|
| 44 |
MB_ARTIST_QUERY = r"mb_albumartistid::^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$" |
| 45 |
|
| 46 |
|
| 47 |
def _missing_count(album: Album) -> bool | int: |
| 48 |
"""Return number of missing items in `album`.""" |
| 49 |
return (album.albumtotal or 0) - len(album.items()) |
| 50 |
|
| 51 |
|
| 52 |
def _item( |
| 53 |
track_info: TrackInfo, album_info: AlbumInfo, album_id: int | None |
| 54 |
) -> Item: |
| 55 |
"""Build and return `item` from `track_info` and `album info` |
| 56 |
objects. `item` is missing what fields cannot be obtained from |
| 57 |
MusicBrainz alone (encoder, rg_track_gain, rg_track_peak, |
| 58 |
rg_album_gain, rg_album_peak, original_year, original_month, |
| 59 |
original_day, length, bitrate, format, samplerate, bitdepth, |
| 60 |
channels, mtime.) |
| 61 |
""" |
| 62 |
t = track_info |
| 63 |
a = album_info |
| 64 |
|
| 65 |
return Item( |
| 66 |
album_id=album_id, |
| 67 |
album=a.album, |
| 68 |
albumartist=a.artist, |
| 69 |
albumartist_credit=a.artist_credit, |
| 70 |
albumartist_sort=a.artist_sort, |
| 71 |
albumdisambig=a.albumdisambig, |
| 72 |
albumstatus=a.albumstatus, |
| 73 |
albumtype=a.albumtype, |
| 74 |
artist=t.artist, |
| 75 |
artist_credit=t.artist_credit, |
| 76 |
artist_sort=t.artist_sort, |
| 77 |
asin=a.asin, |
| 78 |
catalognum=a.catalognum, |
| 79 |
comp=a.va, |
| 80 |
country=a.country, |
| 81 |
day=a.day, |
| 82 |
disc=t.medium, |
| 83 |
disctitle=t.disctitle, |
| 84 |
disctotal=a.mediums, |
| 85 |
label=a.label, |
| 86 |
language=a.language, |
| 87 |
length=t.length, |
| 88 |
mb_albumid=a.album_id, |
| 89 |
mb_artistid=t.artist_id, |
| 90 |
mb_releasegroupid=a.releasegroup_id, |
| 91 |
mb_trackid=t.track_id, |
| 92 |
media=t.media, |
| 93 |
month=a.month, |
| 94 |
script=a.script, |
| 95 |
title=t.title, |
| 96 |
track=t.index, |
| 97 |
tracktotal=len(a.tracks), |
| 98 |
year=a.year, |
| 99 |
) |
| 100 |
|
| 101 |
|
| 102 |
class MissingPlugin(MusicBrainzAPIMixin, BeetsPlugin): |
| 103 |
"""List missing tracks""" |
| 104 |
|
| 105 |
album_types: ClassVar[dict[str, types.Type]] = {"missing": types.INTEGER} |
| 106 |
|
| 107 |
def __init__(self) -> None: |
| 108 |
super().__init__() |
| 109 |
|
| 110 |
self.config.add( |
| 111 |
{ |
| 112 |
"count": False, |
| 113 |
"total": False, |
| 114 |
"album": False, |
| 115 |
"release_types": ["album"], |
| 116 |
} |
| 117 |
) |
| 118 |
|
| 119 |
self.album_template_fields["missing"] = lambda a: str(_missing_count(a)) |
| 120 |
|
| 121 |
self._command = Subcommand("missing", help=__doc__, aliases=["miss"]) |
| 122 |
self._command.parser.add_option( |
| 123 |
"-c", |
| 124 |
"--count", |
| 125 |
dest="count", |
| 126 |
action="store_true", |
| 127 |
help="count missing tracks per album", |
| 128 |
) |
| 129 |
self._command.parser.add_option( |
| 130 |
"-t", |
| 131 |
"--total", |
| 132 |
dest="total", |
| 133 |
action="store_true", |
| 134 |
help="count total of missing tracks", |
| 135 |
) |
| 136 |
self._command.parser.add_option( |
| 137 |
"-a", |
| 138 |
"--album", |
| 139 |
dest="album", |
| 140 |
action="store_true", |
| 141 |
help=( |
| 142 |
"show missing album releases for artist instead of tracks; " |
| 143 |
"Defaults to only releases of type 'album'" |
| 144 |
), |
| 145 |
) |
| 146 |
self._command.parser.add_option( |
| 147 |
"--release-types", |
| 148 |
action="append", |
| 149 |
dest="release_types", |
| 150 |
help=( |
| 151 |
"comma-separated list of release types for missing albums " |
| 152 |
f"(valid: {', '.join(VALID_RELEASE_TYPES)})" |
| 153 |
), |
| 154 |
) |
| 155 |
self._command.parser.add_format_option() |
| 156 |
|
| 157 |
def commands(self) -> list[Subcommand]: |
| 158 |
def _miss(lib: Library, opts: optparse.Values, args: list[str]) -> None: |
| 159 |
self.config.set_args(opts) |
| 160 |
albms = self.config["album"].get() |
| 161 |
|
| 162 |
helper = self._missing_albums if albms else self._missing_tracks |
| 163 |
helper(lib, args) |
| 164 |
|
| 165 |
self._command.func = _miss |
| 166 |
return [self._command] |
| 167 |
|
| 168 |
def _missing_tracks(self, lib: Library, query: list[str]) -> None: |
| 169 |
"""Print a listing of tracks missing from each album in the library |
| 170 |
matching query. |
| 171 |
""" |
| 172 |
albums = lib.albums(query) |
| 173 |
|
| 174 |
count = self.config["count"].get() |
| 175 |
total = self.config["total"].get() |
| 176 |
fmt = config["format_album" if count else "format_item"].get() |
| 177 |
|
| 178 |
if total: |
| 179 |
print(sum([_missing_count(a) for a in albums])) |
| 180 |
return |
| 181 |
|
| 182 |
# Default format string for count mode. |
| 183 |
if count: |
| 184 |
fmt += ": $missing" |
| 185 |
|
| 186 |
for album in albums: |
| 187 |
if count: |
| 188 |
if _missing_count(album): |
| 189 |
print_(format(album, fmt)) |
| 190 |
|
| 191 |
else: |
| 192 |
for item in self._missing(album): |
| 193 |
print_(format(item, fmt)) |
| 194 |
|
| 195 |
def _missing_albums(self, lib: Library, query: list[str]) -> None: |
| 196 |
"""Print a listing of albums missing from each artist in the library |
| 197 |
matching query. |
| 198 |
""" |
| 199 |
query.append(MB_ARTIST_QUERY) |
| 200 |
|
| 201 |
# build dict mapping artist to set of their release group ids in library |
| 202 |
album_ids_by_artist = defaultdict(set) |
| 203 |
for album in lib.albums(query): |
| 204 |
# TODO(@snejus): Some releases have different `albumartist` for the |
| 205 |
# same `mb_albumartistid`. Since we're grouping by the combination |
| 206 |
# of these two fields, we end up processing the same |
| 207 |
# `mb_albumartistid` multiple times: calling MusicBrainz API and |
| 208 |
# reporting the same set of missing albums. Instead, we should |
| 209 |
# group by `mb_albumartistid` field only. |
| 210 |
artist = (album["albumartist"], album["mb_albumartistid"]) |
| 211 |
album_ids_by_artist[artist].add(album["mb_releasegroupid"]) |
| 212 |
|
| 213 |
total_missing = 0 |
| 214 |
release_types = [] |
| 215 |
for rt in self.config["release_types"].as_str_seq(): |
| 216 |
release_types.extend(rt.split(",")) |
| 217 |
calculating_total = self.config["total"].get() |
| 218 |
fmt = config["format_album"].get() |
| 219 |
for (artist, artist_id), album_ids in album_ids_by_artist.items(): |
| 220 |
try: |
| 221 |
resp = self.mb_api.browse_release_groups( |
| 222 |
artist=artist_id, type="|".join(release_types) |
| 223 |
) |
| 224 |
except requests.exceptions.RequestException: |
| 225 |
self._log.info( |
| 226 |
"Couldn't fetch info for artist '{}' ({})", |
| 227 |
artist, |
| 228 |
artist_id, |
| 229 |
exc_info=True, |
| 230 |
) |
| 231 |
continue |
| 232 |
|
| 233 |
missing_albums = [ |
| 234 |
Album( |
| 235 |
albumartist=artist, |
| 236 |
album=rg["title"], |
| 237 |
mb_releasegroupid=rg["id"], |
| 238 |
albumtype=(rg.get("primary_type") or "").lower(), |
| 239 |
) |
| 240 |
for rg in resp |
| 241 |
if rg["id"] not in album_ids |
| 242 |
] |
| 243 |
|
| 244 |
if calculating_total: |
| 245 |
total_missing += len(missing_albums) |
| 246 |
else: |
| 247 |
for album in missing_albums: |
| 248 |
print_(format(album, fmt)) |
| 249 |
|
| 250 |
if calculating_total: |
| 251 |
print(total_missing) |
| 252 |
|
| 253 |
def _missing(self, album: Album) -> Iterator[Item]: |
| 254 |
"""Query MusicBrainz to determine items missing from `album`.""" |
| 255 |
if len(album.items()) == album.albumtotal: |
| 256 |
return |
| 257 |
|
| 258 |
# fetch missing items |
| 259 |
# TODO: Implement caching that without breaking other stuff |
| 260 |
data_source = album.get("data_source") or album.items()[0].get( |
| 261 |
"data_source", "MusicBrainz" |
| 262 |
) |
| 263 |
if album_info := metadata_plugins.album_for_id( |
| 264 |
album.mb_albumid, data_source |
| 265 |
): |
| 266 |
item_mbids = {x.mb_trackid for x in album.items()} |
| 267 |
for track_info in album_info.tracks: |
| 268 |
if track_info.track_id not in item_mbids: |
| 269 |
self._log.debug( |
| 270 |
"track {.track_id} in album {.album_id}", |
| 271 |
track_info, |
| 272 |
album_info, |
| 273 |
) |
| 274 |
yield _item(track_info, album_info, album.id) |