Debian Codegraph @

beetsplug/metasync/__init__.py

raw
1 """Synchronize information from music player libraries"""
2
3 from __future__ import annotations
4
5 from abc import ABCMeta, abstractmethod
6 from importlib import import_module
7 from typing import TYPE_CHECKING, ClassVar, Protocol
8
9 from confuse import ConfigValueError
10
11 from beets import ui
12 from beets.plugins import BeetsPlugin
13
14 if TYPE_CHECKING:
15 from confuse import ConfigView
16
17 from beets.dbcore import types
18 from beets.library import Item, Library
19 from beets.logging import BeetsLogger as Logger
20
21 METASYNC_MODULE = "beetsplug.metasync"
22
23 # Dictionary to map the MODULE and the CLASS NAME of meta sources
24 SOURCES = {"amarok": "Amarok", "itunes": "Itunes"}
25
26
27 class MetaSyncCLIOpts(Protocol):
28 pretend: bool | None
29 sources: list[str]
30
31
32 class MetaSource(metaclass=ABCMeta):
33 item_types: ClassVar[dict[str, types.Type]]
34
35 def __init__(self, config: ConfigView, log: Logger) -> None:
36 self.config = config
37 self._log = log
38
39 @abstractmethod
40 def sync_from_source(self, item: Item) -> None:
41 pass
42
43
44 def load_meta_sources() -> dict[str, type[MetaSource]]:
45 """Returns a dictionary of all the MetaSources
46 E.g., {'itunes': Itunes} with isinstance(Itunes, MetaSource) true
47 """
48 meta_sources = {}
49
50 for module_path, class_name in SOURCES.items():
51 module = import_module(f"{METASYNC_MODULE}.{module_path}")
52 meta_sources[class_name.lower()] = getattr(module, class_name)
53
54 return meta_sources
55
56
57 META_SOURCES = load_meta_sources()
58
59
60 def load_item_types() -> dict[str, types.Type]:
61 """Returns a dictionary containing the item_types of all the MetaSources"""
62 item_types = {}
63 for meta_source in META_SOURCES.values():
64 item_types.update(meta_source.item_types)
65 return item_types
66
67
68 class MetaSyncPlugin(BeetsPlugin):
69 item_types = load_item_types()
70
71 def __init__(self) -> None:
72 super().__init__()
73
74 def commands(self) -> list[ui.Subcommand]:
75 cmd = ui.Subcommand(
76 "metasync", help="update metadata from music player libraries"
77 )
78 cmd.parser.add_option(
79 "-p",
80 "--pretend",
81 action="store_true",
82 help="show all changes but do nothing",
83 )
84 cmd.parser.add_option(
85 "-s",
86 "--source",
87 default=[],
88 action="append",
89 dest="sources",
90 help="comma-separated list of sources to sync",
91 )
92 cmd.parser.add_format_option()
93 cmd.func = self.func
94 return [cmd]
95
96 def func(
97 self, lib: Library, opts: MetaSyncCLIOpts, args: list[str]
98 ) -> None:
99 """Command handler for the metasync function."""
100 pretend = opts.pretend
101
102 sources = []
103 for source in opts.sources:
104 sources.extend(source.split(","))
105
106 sources = sources or self.config["source"].as_str_seq()
107
108 meta_source_instances = {}
109 items = lib.items(args)
110
111 # Avoid needlessly instantiating meta sources (can be expensive)
112 if not items:
113 self._log.info("No items found matching query")
114 return
115
116 # Instantiate the meta sources
117 for player in sources:
118 try:
119 cls = META_SOURCES[player]
120 except KeyError:
121 self._log.error("Unknown metadata source '{}'", player)
122
123 try:
124 meta_source_instances[player] = cls(self.config, self._log)
125 except (ImportError, ConfigValueError) as e:
126 self._log.error(
127 "Failed to instantiate metadata source {!r}: {}", player, e
128 )
129
130 # Avoid needlessly iterating over items
131 if not meta_source_instances:
132 self._log.error("No valid metadata sources found")
133 return
134
135 # Sync the items with all of the meta sources
136 for item in items:
137 for meta_source in meta_source_instances.values():
138 meta_source.sync_from_source(item)
139
140 changed = ui.show_model_changes(item)
141
142 if changed and not pretend:
143 item.store()