Debian Codegraph @

beetsplug/parentwork.py

raw
1 """Gets parent work, its disambiguation and id, composer, composer sort name
2 and work composition date
3 """
4
5 from __future__ import annotations
6
7 from typing import TYPE_CHECKING
8
9 import requests
10
11 from beets import ui
12 from beets.plugins import BeetsPlugin
13
14 from ._utils.musicbrainz import MusicBrainzAPIMixin
15
16 if TYPE_CHECKING:
17 import optparse
18
19 from beets.importer import ImportSession, ImportTask
20 from beets.library import Item, Library
21 from beetsplug._utils.musicbrainz import Work
22
23 from ._typing import JSONDict
24
25
26 class ParentWorkPlugin(MusicBrainzAPIMixin, BeetsPlugin):
27 def __init__(self) -> None:
28 super().__init__()
29
30 self.config.add({"auto": False, "force": False})
31
32 if self.config["auto"]:
33 self.import_stages = [self.imported]
34
35 def commands(self) -> list[ui.Subcommand]:
36 def func(lib: Library, opts: optparse.Values, args: list[str]) -> None:
37 self.config.set_args(opts)
38 force_parent = self.config["force"].get(bool)
39 write = ui.should_write()
40
41 for item in lib.items(args):
42 changed = self.find_work(item, force_parent, verbose=True)
43 if changed:
44 item.store()
45 if write:
46 item.try_write()
47
48 command = ui.Subcommand(
49 "parentwork", help="fetch parent works, composers and dates"
50 )
51
52 command.parser.add_option(
53 "-f",
54 "--force",
55 dest="force",
56 action="store_true",
57 default=None,
58 help="re-fetch when parent work is already present",
59 )
60
61 command.func = func
62 return [command]
63
64 def imported(self, session: ImportSession, task: ImportTask) -> None:
65 """Import hook for fetching parent works automatically."""
66 force_parent = self.config["force"].get(bool)
67
68 for item in task.imported_items():
69 self.find_work(item, force_parent, verbose=False)
70 item.store()
71
72 def get_info(self, item: Item, work_info: Work) -> JSONDict:
73 """Given the parent work info dict, fetch parent_composer,
74 parent_composer_sort, parentwork, parentwork_disambig, mb_workid and
75 composer_ids.
76 """
77
78 parent_composer = []
79 parent_composer_sort = []
80 parentwork_info = {}
81
82 composer_exists = False
83 for artist in work_info.get("artist_relations", []):
84 if artist["type"] == "composer":
85 composer_exists = True
86 parent_composer.append(artist["artist"]["name"])
87 parent_composer_sort.append(artist["artist"]["sort_name"])
88 if "end" in artist.keys():
89 parentwork_info["parentwork_date"] = artist["end"]
90
91 parentwork_info["parent_composer"] = ", ".join(parent_composer)
92 parentwork_info["parent_composer_sort"] = ", ".join(
93 parent_composer_sort
94 )
95
96 if not composer_exists:
97 self._log.debug(
98 "no composer for {}; add one at "
99 "https://musicbrainz.org/work/{}",
100 item,
101 work_info["id"],
102 )
103
104 parentwork_info["parentwork"] = work_info["title"]
105 parentwork_info["mb_parentworkid"] = work_info["id"]
106
107 if "disambiguation" in work_info:
108 parentwork_info["parentwork_disambig"] = work_info["disambiguation"]
109
110 else:
111 parentwork_info["parentwork_disambig"] = None
112
113 return parentwork_info
114
115 def find_work(self, item: Item, force: bool, verbose: bool) -> bool | None:
116 """Finds the parent work of a recording and populates the tags
117 accordingly.
118
119 The parent work is found recursively, by finding the direct parent
120 repeatedly until there are no more links in the chain. We return the
121 final, topmost work in the chain.
122
123 Namely, the tags parentwork, parentwork_disambig, mb_parentworkid,
124 parent_composer, parent_composer_sort and work_date are populated.
125 """
126
127 if not item.mb_workid:
128 self._log.info(
129 "No work for {0}, add one at https://musicbrainz.org/recording/{0.mb_trackid}",
130 item,
131 )
132 return None
133
134 hasparent = hasattr(item, "parentwork")
135 work_changed = True
136 if hasattr(item, "parentwork_workid_current"):
137 work_changed = item.parentwork_workid_current != item.mb_workid
138 if force or not hasparent or work_changed:
139 try:
140 work_info, work_date = self.find_parentwork_info(item.mb_workid)
141 except requests.exceptions.RequestException:
142 self._log.debug("error fetching work", item, exc_info=True)
143 return None
144 parent_info = self.get_info(item, work_info)
145 parent_info["parentwork_workid_current"] = item.mb_workid
146 if "parent_composer" in parent_info:
147 self._log.debug(
148 "Work fetched: {} - {}",
149 parent_info["parentwork"],
150 parent_info["parent_composer"],
151 )
152 else:
153 self._log.debug(
154 "Work fetched: {} - no parent composer",
155 parent_info["parentwork"],
156 )
157
158 elif hasparent:
159 self._log.debug("{}: Work present, skipping", item)
160 return None
161
162 # apply all non-null values to the item
163 for key, value in parent_info.items():
164 if value:
165 item[key] = value
166
167 if work_date:
168 item["work_date"] = work_date
169 if verbose:
170 return ui.show_model_changes(
171 item,
172 fields=[
173 "parentwork",
174 "parentwork_disambig",
175 "mb_parentworkid",
176 "parent_composer",
177 "parent_composer_sort",
178 "work_date",
179 "parentwork_workid_current",
180 "parentwork_date",
181 ],
182 )
183 return None
184
185 def find_parentwork_info(self, mb_workid: str) -> tuple[Work, str | None]:
186 """Get the MusicBrainz information dict about a parent work, including
187 the artist relations, and the composition date for a work's parent work.
188 """
189 work_date = None
190
191 parent_id: str | None = mb_workid
192
193 while parent_id:
194 current_id = parent_id
195 work_info = self.mb_api.get_work(
196 current_id, includes=["work-rels", "artist-rels"]
197 )
198 work_date = work_date or next(
199 (
200 end
201 for a in work_info.get("artist_relations", [])
202 if a["type"] == "composer" and (end := a.get("end"))
203 ),
204 None,
205 )
206 parent_id = next(
207 (
208 w["work"]["id"]
209 for w in work_info.get("work_relations", [])
210 if w["type"] == "parts" and w["direction"] == "backward"
211 ),
212 None,
213 )
214
215 return work_info, work_date