Debian Codegraph @

beetsplug/bpsync.py

raw
1 """Update library's tags using Beatport."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING, Literal, Protocol
6
7 from beets import library, ui, util
8 from beets.autotag import AlbumMatch, Distance, TrackMatch
9 from beets.plugins import BeetsPlugin, apply_item_changes
10 from beets.util.deprecation import deprecate_for_user
11
12 from .beatport import BeatportPlugin
13
14 if TYPE_CHECKING:
15 from collections.abc import Sequence
16
17 from beets.library import Album, Item, Library
18
19
20 class BPSyncCLIOpts(Protocol):
21 move: bool | None
22 pretend: bool
23 write: bool | None
24
25
26 class BPSyncPlugin(BeetsPlugin):
27 def __init__(self) -> None:
28 super().__init__()
29 deprecate_for_user(self._log, "The 'bpsync' plugin")
30 self.beatport_plugin = BeatportPlugin()
31 # this would cause an error but this plugin is dead
32 self.beatport_plugin.setup()
33
34 def commands(self) -> list[ui.Subcommand]:
35 cmd = ui.Subcommand("bpsync", help="update metadata from Beatport")
36 cmd.parser.add_option(
37 "-p",
38 "--pretend",
39 action="store_true",
40 default=False,
41 help="show all changes but do nothing",
42 )
43 cmd.parser.add_option(
44 "-m",
45 "--move",
46 action="store_true",
47 dest="move",
48 help="move files in the library directory",
49 )
50 cmd.parser.add_option(
51 "-M",
52 "--nomove",
53 action="store_false",
54 dest="move",
55 help="don't move files in library",
56 )
57 cmd.parser.add_option(
58 "-W",
59 "--nowrite",
60 action="store_false",
61 default=None,
62 dest="write",
63 help="don't write updated metadata to files",
64 )
65 cmd.parser.add_format_option()
66 cmd.func = self.func
67 return [cmd]
68
69 def func(self, lib: Library, opts: BPSyncCLIOpts, args: list[str]) -> None:
70 """Command handler for the bpsync function."""
71 move = ui.should_move(opts.move)
72 pretend = opts.pretend
73 write = ui.should_write(opts.write)
74
75 self.singletons(lib, args, move, pretend, write)
76 self.albums(lib, args, move, pretend, write)
77
78 def singletons(
79 self,
80 lib: Library,
81 query: Sequence[str],
82 move: bool,
83 pretend: bool,
84 write: bool,
85 ) -> None:
86 """Retrieve and apply info from the autotagger for items matched by
87 query.
88 """
89 for item in lib.items([*query, "singleton:true"]):
90 if not item.mb_trackid:
91 self._log.info(
92 "Skipping singleton with no mb_trackid: {}", item
93 )
94 continue
95
96 if not self.is_beatport_track(item):
97 self._log.info(
98 "Skipping non-{.beatport_plugin.data_source} singleton: {}",
99 self,
100 item,
101 )
102 continue
103
104 # Apply.
105 if trackinfo := self.beatport_plugin.track_for_id(item.mb_trackid):
106 with lib.transaction():
107 TrackMatch(Distance(), trackinfo, item).apply_metadata(
108 from_scratch=False
109 )
110 apply_item_changes(lib, item, move, pretend, write)
111
112 @staticmethod
113 def is_beatport_track(item: Item) -> bool:
114 return (
115 item.get("data_source") == BeatportPlugin.data_source
116 and item.mb_trackid.isnumeric()
117 )
118
119 def get_album_tracks(self, album: Album) -> list[Item] | Literal[False]:
120 if not album.mb_albumid:
121 self._log.info("Skipping album with no mb_albumid: {}", album)
122 return False
123 if not album.mb_albumid.isnumeric():
124 self._log.info(
125 "Skipping album with invalid {.beatport_plugin.data_source} ID: {}",
126 self,
127 album,
128 )
129 return False
130 items = list(album.items())
131 if album.get("data_source") == self.beatport_plugin.data_source:
132 return items
133 if not all(self.is_beatport_track(item) for item in items):
134 self._log.info(
135 "Skipping non-{.beatport_plugin.data_source} release: {}",
136 self,
137 album,
138 )
139 return False
140 return items
141
142 def albums(
143 self,
144 lib: Library,
145 query: Sequence[str],
146 move: bool,
147 pretend: bool,
148 write: bool,
149 ) -> None:
150 """Retrieve and apply info from the autotagger for albums matched by
151 query and their items.
152 """
153 # Process matching albums.
154 for album in lib.albums(query):
155 # Do we have a valid Beatport album?
156 items = self.get_album_tracks(album)
157 if not items:
158 continue
159
160 # Get the Beatport album information.
161 albuminfo = self.beatport_plugin.album_for_id(album.mb_albumid)
162 if not albuminfo:
163 self._log.info(
164 "Release ID {0.mb_albumid} not found for album {0}", album
165 )
166 continue
167
168 beatport_trackid_to_trackinfo = {
169 track.track_id: track for track in albuminfo.tracks
170 }
171 library_trackid_to_item = {item.mb_trackid: item for item in items}
172 item_info_pairs = [
173 (item, beatport_trackid_to_trackinfo[track_id])
174 for track_id, item in library_trackid_to_item.items()
175 ]
176
177 self._log.info("applying changes to {}", album)
178 with lib.transaction():
179 AlbumMatch(
180 Distance(), albuminfo, dict(item_info_pairs)
181 ).apply_metadata(from_scratch=False)
182 changed = False
183 # Find any changed item to apply Beatport changes to album.
184 any_changed_item = items[0]
185 for item in items:
186 item_changed = ui.show_model_changes(item)
187 changed |= item_changed
188 if item_changed:
189 any_changed_item = item
190 apply_item_changes(lib, item, move, pretend, write)
191
192 if pretend or not changed:
193 continue
194
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()