| 1 |
"""Updates a Plex library whenever the beets library is changed. |
| 2 |
|
| 3 |
Plex Home users enter the Plex Token to enable updating, or run |
| 4 |
``beet plexupdate --auth`` once to log in via plex.tv: the obtained |
| 5 |
device token is stored in a token file next to the beets configuration. |
| 6 |
Put something like the following in your config.yaml to configure: |
| 7 |
plex: |
| 8 |
host: localhost |
| 9 |
port: 32400 |
| 10 |
token: token |
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import annotations |
| 14 |
|
| 15 |
import json |
| 16 |
import time |
| 17 |
import uuid |
| 18 |
import webbrowser |
| 19 |
from contextlib import suppress |
| 20 |
from functools import cached_property |
| 21 |
from http import HTTPStatus |
| 22 |
from json import JSONDecodeError |
| 23 |
from typing import TYPE_CHECKING, ClassVar, Protocol |
| 24 |
from urllib.parse import urlencode, urljoin |
| 25 |
|
| 26 |
import confuse |
| 27 |
import requests |
| 28 |
|
| 29 |
from beets import __version__, ui |
| 30 |
from beets.exceptions import UserError |
| 31 |
from beets.logging import getLogger |
| 32 |
from beets.plugins import BeetsPlugin |
| 33 |
from beetsplug._utils.requests import ( |
| 34 |
BeetsHTTPError, |
| 35 |
RequestHandler, |
| 36 |
TimeoutAndRetrySession, |
| 37 |
) |
| 38 |
|
| 39 |
if TYPE_CHECKING: |
| 40 |
from pathlib import Path |
| 41 |
|
| 42 |
from beets.library import LibModel, Library |
| 43 |
from beetsplug._typing import JSONDict |
| 44 |
|
| 45 |
log = getLogger("beets.plexupdate") |
| 46 |
|
| 47 |
# plex.tv endpoints used by the interactive PIN based authentication. |
| 48 |
PLEX_API = "https://plex.tv/api/v2" |
| 49 |
PLEX_AUTH_URL = "https://app.plex.tv/auth#?" |
| 50 |
|
| 51 |
|
| 52 |
class PlexUpdateCLIOpts(Protocol): |
| 53 |
auth: bool |
| 54 |
|
| 55 |
|
| 56 |
class PlexSession(TimeoutAndRetrySession): |
| 57 |
"""HTTP session for the Plex server and plex.tv with PIN auth. |
| 58 |
|
| 59 |
Plex does not offer a public OAuth2 flow (bummer). Instead, third-party |
| 60 |
applications authenticate through Plex' PIN flow: the obtained access |
| 61 |
token is exchanged for the token of the local server, which is stored |
| 62 |
and used for updates. |
| 63 |
|
| 64 |
see https://developer.plex.tv/pms/#section/API-Info/Authenticating-with-Plex |
| 65 |
""" |
| 66 |
|
| 67 |
def __init__( |
| 68 |
self, |
| 69 |
token_path: Path, |
| 70 |
verify: bool = True, |
| 71 |
token_override: str | None = None, |
| 72 |
) -> None: |
| 73 |
super().__init__() |
| 74 |
self.token_path = token_path |
| 75 |
self.token_override = token_override |
| 76 |
# The token file is read at most once per run; `save_token` is the |
| 77 |
# only writer and keeps the cache in sync. |
| 78 |
self._token_cache: JSONDict | None = None |
| 79 |
|
| 80 |
# Allow ignoring certificate errors for self-signed certs. |
| 81 |
self.verify = verify |
| 82 |
|
| 83 |
self.headers.update( |
| 84 |
{ |
| 85 |
"accept": "application/json", |
| 86 |
"X-Plex-Product": "beets", |
| 87 |
"X-Plex-Product-Version": __version__, |
| 88 |
"X-Plex-Client-Identifier": self.client_id, |
| 89 |
} |
| 90 |
) |
| 91 |
|
| 92 |
@property |
| 93 |
def token(self) -> str | None: |
| 94 |
"""The auth token: the configured override or the stored token.""" |
| 95 |
return self.token_override or self.load_token().get("X-Plex-Token") |
| 96 |
|
| 97 |
@property |
| 98 |
def client_id(self) -> str: |
| 99 |
"""The client identifier used for plex.tv authentication. |
| 100 |
|
| 101 |
Either load from the token file or generate a new one and persist it |
| 102 |
on first use. |
| 103 |
""" |
| 104 |
data = self.load_token() |
| 105 |
if client_id := data.get("client_identifier"): |
| 106 |
return client_id |
| 107 |
|
| 108 |
client_id = uuid.uuid4().hex |
| 109 |
data["client_identifier"] = client_id |
| 110 |
self.save_token(data) |
| 111 |
log.debug("Generated and saved new client identifier") |
| 112 |
return client_id |
| 113 |
|
| 114 |
def load_token(self) -> JSONDict: |
| 115 |
"""Load the token data from the token file. |
| 116 |
|
| 117 |
The contents are cached after the first successful read; a |
| 118 |
not-yet-existing file is re-checked until it appears. |
| 119 |
""" |
| 120 |
if self._token_cache is None: |
| 121 |
with suppress(FileNotFoundError, JSONDecodeError, OSError): |
| 122 |
self._token_cache = json.loads(self.token_path.read_text()) |
| 123 |
|
| 124 |
return self._token_cache or {} |
| 125 |
|
| 126 |
def save_token(self, data: JSONDict) -> None: |
| 127 |
"""Merge data into the token file and persist it.""" |
| 128 |
token = self.load_token() |
| 129 |
token.update(data) |
| 130 |
self.token_path.write_text(json.dumps(token, indent=2)) |
| 131 |
|
| 132 |
def request(self, *args, **kwargs) -> requests.Response: |
| 133 |
"""Send a request, attaching the auth token.""" |
| 134 |
headers = kwargs.setdefault("headers", {}) |
| 135 |
if token := self.token: |
| 136 |
headers["X-Plex-Token"] = token |
| 137 |
return super().request(*args, **kwargs) |
| 138 |
|
| 139 |
def create_pin(self) -> JSONDict: |
| 140 |
"""Create a pin that yields the user's access token after |
| 141 |
authorization.""" |
| 142 |
return ( |
| 143 |
super() |
| 144 |
.request("post", f"{PLEX_API}/pins", params={"strong": True}) |
| 145 |
.json() |
| 146 |
) |
| 147 |
|
| 148 |
def wait_for_login( |
| 149 |
self, |
| 150 |
pin_id: int, |
| 151 |
timeout: int = 300, # 5min |
| 152 |
) -> str | None: |
| 153 |
"""Poll the pin endpoint until the user authorized the login. |
| 154 |
|
| 155 |
Returns the plex.tv account token, or ``None`` on timeout. |
| 156 |
""" |
| 157 |
deadline = time.monotonic() + timeout |
| 158 |
while time.monotonic() < deadline: |
| 159 |
data: JSONDict = {} |
| 160 |
with suppress(requests.exceptions.RequestException): |
| 161 |
data = ( |
| 162 |
super().request("get", f"{PLEX_API}/pins/{pin_id}").json() |
| 163 |
) |
| 164 |
|
| 165 |
if token := data.get("authToken"): |
| 166 |
return token |
| 167 |
|
| 168 |
log.debug("Plex pin polling failed. Retrying in 5s...") |
| 169 |
time.sleep(5) # 5s polling |
| 170 |
return None |
| 171 |
|
| 172 |
|
| 173 |
class UnauthorizedPlexError(BeetsHTTPError): |
| 174 |
"""The Plex server rejected the request (401).""" |
| 175 |
|
| 176 |
STATUS = HTTPStatus.UNAUTHORIZED |
| 177 |
|
| 178 |
def __init__(self, *args, message: str | None = None, **kwargs) -> None: |
| 179 |
message = ( |
| 180 |
f"HTTP Error: {self.STATUS.value} {self.STATUS.phrase}. " |
| 181 |
"You may need to reauthenticate using `beet plexupdate --auth`." |
| 182 |
) |
| 183 |
super().__init__(*args, message=message, **kwargs) |
| 184 |
|
| 185 |
|
| 186 |
class PlexAPI(RequestHandler): |
| 187 |
"""API client for Plex. |
| 188 |
|
| 189 |
Wraps the interactive plex.tv PIN authentication flow and the local |
| 190 |
server API used to refresh the music library; the session deals with |
| 191 |
the HTTP requests to plex.tv, token persistence and the PIN flow. |
| 192 |
""" |
| 193 |
|
| 194 |
explicit_http_errors: ClassVar[list[type[BeetsHTTPError]]] = [ |
| 195 |
UnauthorizedPlexError |
| 196 |
] |
| 197 |
|
| 198 |
def __init__( |
| 199 |
self, |
| 200 |
token_path: Path, |
| 201 |
host: str, |
| 202 |
port: int, |
| 203 |
library_name: str, |
| 204 |
secure: bool, |
| 205 |
verify: bool, |
| 206 |
token_override: str | None = None, |
| 207 |
) -> None: |
| 208 |
self.token_path = token_path |
| 209 |
self.token_override = token_override |
| 210 |
self.library_name = library_name |
| 211 |
|
| 212 |
self.base_url = f"{'https' if secure else 'http'}://{host}:{port}/" |
| 213 |
self._verify = verify |
| 214 |
|
| 215 |
@cached_property |
| 216 |
def session(self) -> PlexSession: |
| 217 |
"""Session with token persistence and plex.tv identifying headers.""" |
| 218 |
return PlexSession( |
| 219 |
token_path=self.token_path, |
| 220 |
verify=self._verify, |
| 221 |
token_override=self.token_override, |
| 222 |
) |
| 223 |
|
| 224 |
def ui_authenticate_flow(self) -> None: |
| 225 |
"""Interactive authentication with plex.tv (PIN flow). |
| 226 |
|
| 227 |
1. Open the authentication URL in the browser |
| 228 |
2. Wait for the user to authorize (~5 minutes) |
| 229 |
3. Token is auto-saved for future use |
| 230 |
""" |
| 231 |
try: |
| 232 |
pin = self.session.create_pin() |
| 233 |
except requests.exceptions.RequestException as e: |
| 234 |
raise UserError(f"Plex login flow failed: {e}") from e |
| 235 |
|
| 236 |
auth_url = PLEX_AUTH_URL + urlencode( |
| 237 |
{ |
| 238 |
"clientID": self.session.client_id, |
| 239 |
"code": pin["code"], |
| 240 |
"context[device][product]": "beets", |
| 241 |
} |
| 242 |
) |
| 243 |
ui.print_(f"Please visit: {auth_url}") |
| 244 |
ui.print_("Waiting for authorization in your browser...") |
| 245 |
with suppress(webbrowser.Error): |
| 246 |
webbrowser.open(auth_url) |
| 247 |
|
| 248 |
if not (account_token := self.session.wait_for_login(pin["id"])): |
| 249 |
raise UserError( |
| 250 |
"Plex authentication timed out. Please run " |
| 251 |
"`beet plexupdate --auth` again." |
| 252 |
) |
| 253 |
|
| 254 |
# The pin flow token works for plex.tv and the local server |
| 255 |
# alike, so it is stored directly. |
| 256 |
self.session.save_token({"X-Plex-Token": account_token}) |
| 257 |
ui.print_( |
| 258 |
f"Authentication successful! Token saved to {self.token_path}." |
| 259 |
) |
| 260 |
|
| 261 |
def get_music_section(self) -> str | None: |
| 262 |
"""The section key for the music library in Plex.""" |
| 263 |
data = self.get_json(urljoin(self.base_url, "library/sections")) |
| 264 |
|
| 265 |
# Find the section with the configured name and return its key. |
| 266 |
for directory in data.get("MediaContainer", {}).get("Directory", []): |
| 267 |
if directory.get("title") == self.library_name: |
| 268 |
return str(directory["key"]) |
| 269 |
return None |
| 270 |
|
| 271 |
def update_library(self) -> requests.Response: |
| 272 |
"""Start a refresh of the music library.""" |
| 273 |
section_key = self.get_music_section() |
| 274 |
if section_key is None: |
| 275 |
raise UserError( |
| 276 |
f"No music library named {self.library_name!r} found on " |
| 277 |
"the Plex server. Check the `plex.library_name` setting." |
| 278 |
) |
| 279 |
|
| 280 |
return self.get( |
| 281 |
urljoin(self.base_url, f"library/sections/{section_key}/refresh") |
| 282 |
) |
| 283 |
|
| 284 |
|
| 285 |
class PlexUpdate(BeetsPlugin): |
| 286 |
def __init__(self) -> None: |
| 287 |
# Set name so the config is available under `plex:` in config.yaml |
| 288 |
super().__init__("plex") |
| 289 |
self.config.add( |
| 290 |
{ |
| 291 |
"host": "localhost", |
| 292 |
"port": 32400, |
| 293 |
"library_name": "Music", |
| 294 |
"secure": False, |
| 295 |
"ignore_cert_errors": False, |
| 296 |
"tokenfile": "plex_token.json", |
| 297 |
# Deprecated: use `beet plexupdate --auth` instead. |
| 298 |
"token": "", |
| 299 |
} |
| 300 |
) |
| 301 |
self.config["token"].redact = True |
| 302 |
|
| 303 |
# `cli_exit` is registered lazily on the first library change so |
| 304 |
# read-only operations skip the refresh. |
| 305 |
self._registered = False |
| 306 |
self.register_listener("database_change", self.listen_for_db_change) |
| 307 |
|
| 308 |
@cached_property |
| 309 |
def api(self) -> PlexAPI: |
| 310 |
"""API client for plex.tv authentication and the local server.""" |
| 311 |
return PlexAPI( |
| 312 |
token_path=self._tokenfile(), |
| 313 |
host=self.config["host"].get(str), |
| 314 |
port=self.config["port"].get(), |
| 315 |
library_name=self.config["library_name"].get(), |
| 316 |
secure=self.config["secure"].get(bool), |
| 317 |
verify=not self.config["ignore_cert_errors"].get(bool), |
| 318 |
token_override=self.config["token"].get(str) or None, |
| 319 |
) |
| 320 |
|
| 321 |
def _tokenfile(self) -> Path: |
| 322 |
"""Path to the JSON file holding the plex.tv auth token.""" |
| 323 |
return self.config["tokenfile"].get(confuse.Path(in_app_dir=True)) |
| 324 |
|
| 325 |
def listen_for_db_change(self, lib: Library, model: LibModel) -> None: |
| 326 |
"""Register the exit-time Plex refresh on the first library change.""" |
| 327 |
if not self._registered: |
| 328 |
self.register_listener("cli_exit", self.update) |
| 329 |
self._registered = True |
| 330 |
|
| 331 |
def update(self, lib: Library) -> None: |
| 332 |
"""Send a refresh request to the Plex server when the client exits.""" |
| 333 |
log.info("Updating Plex library...") |
| 334 |
|
| 335 |
try: |
| 336 |
self.api.update_library() |
| 337 |
log.info("Started library update successfully.") |
| 338 |
except UserError as e: |
| 339 |
log.exception("Plex library update failed: %s", e) |
| 340 |
except UnauthorizedPlexError: |
| 341 |
log.error( |
| 342 |
"Plex library update failed: the server rejected the " |
| 343 |
"request (401). If it requires authentication, run " |
| 344 |
"`beet plexupdate --auth`." |
| 345 |
) |
| 346 |
except requests.exceptions.RequestException: |
| 347 |
log.exception("Library update failed!") |
| 348 |
|
| 349 |
def commands(self) -> list[ui.Subcommand]: |
| 350 |
plexupdate_cmd = ui.Subcommand( |
| 351 |
"plexupdate", help="Update Plex library when beets library changes" |
| 352 |
) |
| 353 |
plexupdate_cmd.parser.add_option( |
| 354 |
"-a", |
| 355 |
"--auth", |
| 356 |
action="store_true", |
| 357 |
help="Authenticate and login to Plex", |
| 358 |
default=False, |
| 359 |
) |
| 360 |
|
| 361 |
def auth_func( |
| 362 |
lib: Library, opts: PlexUpdateCLIOpts, args: list[str] |
| 363 |
) -> None: |
| 364 |
if opts.auth: |
| 365 |
self.api.ui_authenticate_flow() |
| 366 |
else: |
| 367 |
plexupdate_cmd.print_help() |
| 368 |
|
| 369 |
plexupdate_cmd.func = auth_func |
| 370 |
|
| 371 |
return [plexupdate_cmd] |