Debian Codegraph @

beetsplug/subsonicplaylist.py

raw
1 from __future__ import annotations
2
3 import random
4 import string
5 from hashlib import md5
6 from typing import TYPE_CHECKING
7 from urllib.parse import urlencode
8 from xml.etree import ElementTree
9
10 import requests
11
12 from beets.dbcore import AndQuery
13 from beets.dbcore.query import MatchQuery
14 from beets.plugins import BeetsPlugin
15 from beets.ui import Subcommand
16
17 if TYPE_CHECKING:
18 import optparse
19 from collections.abc import Collection, Sequence
20
21 from beets.library import Item, Library
22
23 from ._typing import JSONDict
24
25
26 __author__ = "https://github.com/MrNuggelz"
27 TrackKey = tuple[str, str, str]
28
29
30 def filter_to_be_removed(
31 items: Sequence[Item], keys: Collection[TrackKey]
32 ) -> list[Item]:
33 if len(items) > len(keys):
34 dont_remove = []
35 for artist, album, title in keys:
36 for item in items:
37 if (
38 artist == item["artist"]
39 and album == item["album"]
40 and title == item["title"]
41 ):
42 dont_remove.append(item)
43 return [item for item in items if item not in dont_remove]
44
45 def to_be_removed(item: Item) -> bool:
46 for artist, album, title in keys:
47 if (
48 artist == item["artist"]
49 and album == item["album"]
50 and title == item["title"]
51 ):
52 return False
53 return True
54
55 return [item for item in items if to_be_removed(item)]
56
57
58 class SubsonicPlaylistPlugin(BeetsPlugin):
59 def __init__(self) -> None:
60 super().__init__()
61 self.config.add(
62 {
63 "delete": False,
64 "playlist_ids": [],
65 "playlist_names": [],
66 "username": "",
67 "password": "",
68 }
69 )
70 self.config["password"].redact = True
71
72 def update_tags(
73 self, playlist_dict: dict[TrackKey, str], lib: Library
74 ) -> None:
75 with lib.transaction():
76 for query, playlist_tag in playlist_dict.items():
77 and_query = AndQuery(
78 [
79 MatchQuery("artist", query[0]),
80 MatchQuery("album", query[1]),
81 MatchQuery("title", query[2]),
82 ]
83 )
84 items = lib.items(and_query)
85 if not items:
86 self._log.warn(
87 "{} | track not found ({})", playlist_tag, query
88 )
89 continue
90 for item in items:
91 item.subsonic_playlist = playlist_tag
92 item.try_sync(write=True, move=False)
93
94 def get_playlist(
95 self, playlist_id: str
96 ) -> tuple[str, list[TrackKey]] | None:
97 xml = self.send("getPlaylist", {"id": playlist_id}).text
98 playlist = ElementTree.fromstring(xml)[0]
99 if playlist.attrib.get("code", "200") != "200":
100 alt_error = "error getting playlist, but no error message found"
101 self._log.warn(playlist.attrib.get("message", alt_error))
102 return None
103
104 name = playlist.attrib.get("name", "undefined")
105 tracks = [
106 (t.attrib["artist"], t.attrib["album"], t.attrib["title"])
107 for t in playlist
108 ]
109 return name, tracks
110
111 def commands(self) -> list[Subcommand]:
112 def build_playlist(
113 lib: Library, opts: optparse.Values, args: list[str]
114 ) -> None:
115 self.config.set_args(opts)
116 ids = self.config["playlist_ids"].as_str_seq()
117 if self.config["playlist_names"].as_str_seq():
118 playlists = ElementTree.fromstring(
119 self.send("getPlaylists").text
120 )[0]
121 if playlists.attrib.get("code", "200") != "200":
122 alt_error = (
123 "error getting playlists, but no error message found"
124 )
125 self._log.warn(playlists.attrib.get("message", alt_error))
126 return
127 for name in self.config["playlist_names"].as_str_seq():
128 for playlist in playlists:
129 if name == playlist.attrib["name"]:
130 ids.append(playlist.attrib["id"])
131
132 playlist_dict = self.get_playlists(ids)
133
134 # delete old tags
135 if self.config["delete"]:
136 existing = list(lib.items('subsonic_playlist:";"'))
137 to_be_removed = filter_to_be_removed(
138 existing, playlist_dict.keys()
139 )
140 for item in to_be_removed:
141 item["subsonic_playlist"] = ""
142 with lib.transaction():
143 item.try_sync(write=True, move=False)
144
145 self.update_tags(playlist_dict, lib)
146
147 subsonicplaylist_cmds = Subcommand(
148 "subsonicplaylist", help="import a subsonic playlist"
149 )
150 subsonicplaylist_cmds.parser.add_option(
151 "-d",
152 "--delete",
153 action="store_true",
154 help="delete tag from items not in any playlist anymore",
155 )
156 subsonicplaylist_cmds.func = build_playlist
157 return [subsonicplaylist_cmds]
158
159 def generate_token(self) -> tuple[str, str]:
160 salt = "".join(random.choices(string.ascii_lowercase + string.digits))
161 return (
162 md5((self.config["password"].get() + salt).encode()).hexdigest(),
163 salt,
164 )
165
166 def send(
167 self, endpoint: str, params: JSONDict | None = None
168 ) -> requests.Response:
169 if params is None:
170 params = {}
171 a, b = self.generate_token()
172 params["u"] = self.config["username"]
173 params["t"] = a
174 params["s"] = b
175 params["v"] = "1.12.0"
176 params["c"] = "beets"
177 return requests.get(
178 f"{self.config['base_url'].get()}/rest/{endpoint}?{urlencode(params)}",
179 timeout=10,
180 )
181
182 def get_playlists(self, ids: Sequence[str]) -> dict[TrackKey, str]:
183 output = {}
184 for playlist_id in ids:
185 playlist = self.get_playlist(playlist_id)
186 if playlist:
187 name, tracks = playlist
188 for track in tracks:
189 if track not in output:
190 output[track] = ";"
191 output[track] += f"{name};"
192 return output