Debian Codegraph @

beetsplug/subsonicupdate.py

raw
1 """Updates Subsonic library on Beets import
2 Your Beets configuration file should contain
3 a "subsonic" section like the following:
4 subsonic:
5 url: https://mydomain.com:443/subsonic
6 user: username
7 pass: password
8 auth: token
9 For older Subsonic versions, token authentication
10 is not supported, use password instead:
11 subsonic:
12 url: https://mydomain.com:443/subsonic
13 user: username
14 pass: password
15 auth: pass
16 """
17
18 from __future__ import annotations
19
20 import hashlib
21 import random
22 import string
23 from binascii import hexlify
24 from typing import TYPE_CHECKING
25
26 import requests
27
28 from beets.plugins import BeetsPlugin
29
30 if TYPE_CHECKING:
31 from beets.library import LibModel, Library
32
33
34 __author__ = "https://github.com/maffo999"
35
36
37 class SubsonicUpdate(BeetsPlugin):
38 def __init__(self) -> None:
39 super().__init__("subsonic")
40 # Set default configuration values
41 self.config.add(
42 {
43 "user": "admin",
44 "pass": "admin",
45 "url": "http://localhost:4040",
46 "auth": "token",
47 }
48 )
49 self.config["user"].redact = True
50 self.config["pass"].redact = True
51 self.register_listener("database_change", self.db_change)
52 self.register_listener("smartplaylist_update", self.spl_update)
53
54 def db_change(self, lib: Library, model: LibModel) -> None:
55 self.register_listener("cli_exit", self.start_scan)
56
57 def spl_update(self) -> None:
58 self.register_listener("cli_exit", self.start_scan)
59
60 def __create_token(self) -> tuple[str, str]:
61 """Create salt and token from given password.
62
63 :return: The generated salt and hashed token
64 """
65 password = self.config["pass"].as_str()
66
67 # Pick the random sequence and salt the password
68 r = string.ascii_letters + string.digits
69 salt = "".join([random.choice(r) for _ in range(6)])
70 salted_password = f"{password}{salt}"
71 token = hashlib.md5(salted_password.encode("utf-8")).hexdigest()
72
73 # Put together the payload of the request to the server and the URL
74 return salt, token
75
76 def __format_url(self, endpoint: str) -> str:
77 """Get the Subsonic URL to trigger the given endpoint.
78 Uses either the url config option or the deprecated host, port,
79 and context_path config options together.
80
81 :return: Endpoint for updating Subsonic
82 """
83
84 url = self.config["url"].as_str()
85 if url and url.endswith("/"):
86 url = url[:-1]
87
88 # @deprecated("Use url config option instead")
89 if not url:
90 host = self.config["host"].as_str()
91 port = self.config["port"].get(int)
92 context_path = self.config["contextpath"].as_str()
93 if context_path == "/":
94 context_path = ""
95 url = f"http://{host}:{port}{context_path}"
96
97 return f"{url}/rest/{endpoint}"
98
99 def start_scan(self, lib: Library) -> None:
100 user = self.config["user"].as_str()
101 auth = self.config["auth"].as_str()
102 url = self.__format_url("startScan")
103 self._log.debug("URL is {}", url)
104 self._log.debug("auth type is {.config[auth]}", self)
105
106 if auth == "token":
107 salt, token = self.__create_token()
108 payload = {
109 "u": user,
110 "t": token,
111 "s": salt,
112 "v": "1.13.0", # Subsonic 5.3 and newer
113 "c": "beets",
114 "f": "json",
115 }
116 elif auth == "password":
117 password = self.config["pass"].as_str()
118 encpass = hexlify(password.encode()).decode()
119 payload = {
120 "u": user,
121 "p": f"enc:{encpass}",
122 "v": "1.12.0",
123 "c": "beets",
124 "f": "json",
125 }
126 else:
127 return
128 try:
129 response = requests.get(url, params=payload, timeout=10)
130 json = response.json()
131 except requests.exceptions.JSONDecodeError:
132 self._log.error(
133 "Subsonic server returned a non-JSON response from {} "
134 "(HTTP {})",
135 url,
136 response.status_code,
137 )
138 return
139 except requests.exceptions.RequestException as error:
140 self._log.error("Error connecting to Subsonic server: {}", error)
141 return
142 try:
143 if (
144 response.status_code == 200
145 and json["subsonic-response"]["status"] == "ok"
146 ):
147 count = json["subsonic-response"]["scanStatus"]["count"]
148 self._log.info("Updating Subsonic; scanning {} tracks", count)
149 elif (
150 response.status_code == 200
151 and json["subsonic-response"]["status"] == "failed"
152 ):
153 self._log.error(
154 "Error: {[subsonic-response][error][message]}", json
155 )
156 else:
157 self._log.error("Error: {}", json)
158 except Exception as error:
159 self._log.error("Error: {}", error)