Debian Codegraph @

beetsplug/mbsubmit.py

raw
1 """Aid in submitting information to MusicBrainz.
2
3 This plugin allows the user to print track information in a format that is
4 parseable by the MusicBrainz track parser [1]. Programmatic submitting is not
5 implemented by MusicBrainz yet.
6
7 [1] https://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings
8 """
9
10 from __future__ import annotations
11
12 import subprocess
13 from functools import cached_property
14 from typing import TYPE_CHECKING
15
16 from beets import ui
17 from beets.autotag import Recommendation
18 from beets.plugins import BeetsPlugin
19 from beets.util import PromptChoice, displayable_path
20
21 if TYPE_CHECKING:
22 import optparse
23 from collections.abc import Sequence
24
25 from beets.importer import ImportSession, ImportTask
26 from beets.library import Item, Library
27
28
29 class MBSubmitPlugin(BeetsPlugin):
30 def __init__(self) -> None:
31 super().__init__()
32
33 self.config.add(
34 {
35 "format": "$track. $title - $artist ($length)",
36 "threshold": "medium",
37 "picard_path": "picard",
38 }
39 )
40
41 # Validate and store threshold.
42 self.threshold = self.config["threshold"].as_choice(
43 {
44 "none": Recommendation.none,
45 "low": Recommendation.low,
46 "medium": Recommendation.medium,
47 "strong": Recommendation.strong,
48 }
49 )
50
51 self.register_listener(
52 "before_choose_candidate", self.before_choose_candidate_event
53 )
54
55 def before_choose_candidate_event(
56 self, session: ImportSession, task: ImportTask
57 ) -> list[PromptChoice]:
58 if task.rec and task.rec <= self.threshold:
59 return [
60 PromptChoice("p", "Print tracks", self.print_tracks),
61 PromptChoice("o", "Open files with Picard", self.picard),
62 ]
63 return []
64
65 def picard(self, session: ImportSession, task: ImportTask) -> None:
66 paths = []
67 for p in task.paths:
68 paths.append(displayable_path(p))
69 try:
70 picard_path = self.config["picard_path"].as_str()
71 subprocess.Popen([picard_path, *paths])
72 self._log.info("launched picard from\n{}", picard_path)
73 except OSError as exc:
74 self._log.error("Could not open picard, got error:\n{}", exc)
75
76 @cached_property
77 def fmt(self) -> str:
78 return self.config["format"].as_str()
79
80 def print_tracks(self, session: ImportSession, task: ImportTask) -> None:
81 for i in sorted(task.items, key=lambda i: i.track):
82 ui.print_(format(i, self.fmt))
83
84 def commands(self) -> list[ui.Subcommand]:
85 """Add beet UI commands for mbsubmit."""
86 mbsubmit_cmd = ui.Subcommand(
87 "mbsubmit", help="Submit Tracks to MusicBrainz"
88 )
89
90 def func(lib: Library, opts: optparse.Values, args: list[str]) -> None:
91 items = lib.items(args)
92 self._mbsubmit(items)
93
94 mbsubmit_cmd.func = func
95
96 return [mbsubmit_cmd]
97
98 def _mbsubmit(self, items: Sequence[Item]) -> None:
99 """Print track information to be submitted to MusicBrainz."""
100 for i in sorted(items, key=lambda i: i.track):
101 ui.print_(format(i, self.fmt))