| 1 |
"""A Web interface to beets.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import base64 |
| 6 |
import json |
| 7 |
import os |
| 8 |
from typing import TYPE_CHECKING, Any, Protocol |
| 9 |
|
| 10 |
import flask |
| 11 |
from flask import jsonify |
| 12 |
from unidecode import unidecode |
| 13 |
from werkzeug.routing import BaseConverter, PathConverter |
| 14 |
|
| 15 |
import beets.library |
| 16 |
from beets import ui, util |
| 17 |
from beets.dbcore.query import PathQuery |
| 18 |
from beets.plugins import BeetsPlugin |
| 19 |
|
| 20 |
if TYPE_CHECKING: |
| 21 |
from collections.abc import Callable, Iterable, Iterator, Sequence |
| 22 |
|
| 23 |
from beets.library import LibModel, Library |
| 24 |
from beetsplug._typing import JSONDict |
| 25 |
|
| 26 |
if TYPE_CHECKING: |
| 27 |
|
| 28 |
class LibraryCtx(flask.ctx._AppCtxGlobals): |
| 29 |
lib: beets.library.Library |
| 30 |
|
| 31 |
g = LibraryCtx() |
| 32 |
else: |
| 33 |
from flask import g |
| 34 |
|
| 35 |
|
| 36 |
class WebCLIOpts(Protocol): |
| 37 |
debug: bool |
| 38 |
|
| 39 |
|
| 40 |
# Type checking hacks |
| 41 |
|
| 42 |
# Utilities. |
| 43 |
|
| 44 |
|
| 45 |
def _rep(obj: LibModel, expand: bool = False) -> JSONDict | None: |
| 46 |
"""Get a flat -- i.e., JSON-ish -- representation of a beets Item or |
| 47 |
Album object. For Albums, `expand` dictates whether tracks are |
| 48 |
included. |
| 49 |
""" |
| 50 |
out = dict(obj) |
| 51 |
|
| 52 |
if isinstance(obj, beets.library.Item): |
| 53 |
if app.config.get("INCLUDE_PATHS", False): |
| 54 |
out["path"] = util.displayable_path(out["path"]) |
| 55 |
else: |
| 56 |
del out["path"] |
| 57 |
|
| 58 |
# Filter all bytes attributes and convert them to strings. |
| 59 |
for key, value in out.items(): |
| 60 |
if isinstance(out[key], bytes): |
| 61 |
out[key] = base64.b64encode(value).decode("ascii") |
| 62 |
|
| 63 |
# Get the size (in bytes) of the backing file. This is useful |
| 64 |
# for the Tomahawk resolver API. |
| 65 |
try: |
| 66 |
out["size"] = os.path.getsize(util.syspath(obj.path)) |
| 67 |
except OSError: |
| 68 |
out["size"] = 0 |
| 69 |
|
| 70 |
return out |
| 71 |
|
| 72 |
if isinstance(obj, beets.library.Album): |
| 73 |
if app.config.get("INCLUDE_PATHS", False): |
| 74 |
out["artpath"] = util.displayable_path(out["artpath"]) |
| 75 |
else: |
| 76 |
del out["artpath"] |
| 77 |
if expand: |
| 78 |
out["items"] = [_rep(item) for item in obj.items()] |
| 79 |
return out |
| 80 |
return None |
| 81 |
|
| 82 |
|
| 83 |
def json_generator( |
| 84 |
items: Sequence[LibModel], root: str, expand: bool = False |
| 85 |
) -> Iterator[Any]: |
| 86 |
"""Generator that dumps list of beets Items or Albums as JSON |
| 87 |
|
| 88 |
:param root: root key for JSON |
| 89 |
:param items: sequence of :class:`Item` or :class:`Album` to dump |
| 90 |
:param expand: If true every :class:`Album` contains its items in the json |
| 91 |
representation |
| 92 |
:returns: generator that yields strings |
| 93 |
""" |
| 94 |
yield f'{{"{root}":[' |
| 95 |
first = True |
| 96 |
for item in items: |
| 97 |
if first: |
| 98 |
first = False |
| 99 |
else: |
| 100 |
yield "," |
| 101 |
yield json.dumps(_rep(item, expand=expand)) |
| 102 |
yield "]}" |
| 103 |
|
| 104 |
|
| 105 |
def is_expand() -> bool: |
| 106 |
"""Returns whether the current request is for an expanded response.""" |
| 107 |
|
| 108 |
return flask.request.args.get("expand") is not None |
| 109 |
|
| 110 |
|
| 111 |
def is_delete() -> bool: |
| 112 |
"""Returns whether the current delete request should remove the selected |
| 113 |
files. |
| 114 |
""" |
| 115 |
|
| 116 |
return flask.request.args.get("delete") is not None |
| 117 |
|
| 118 |
|
| 119 |
def get_method() -> str: |
| 120 |
"""Returns the HTTP method of the current request.""" |
| 121 |
return flask.request.method |
| 122 |
|
| 123 |
|
| 124 |
def resource(name: str, patchable: bool = False) -> Any: |
| 125 |
"""Decorates a function to handle RESTful HTTP requests for a resource.""" |
| 126 |
|
| 127 |
def make_responder(retriever: Callable[[int], LibModel | None]) -> Any: |
| 128 |
def responder(ids: Sequence[int]) -> Any: |
| 129 |
retrieved = [retriever(id_) for id_ in ids] |
| 130 |
entities = [entity for entity in retrieved if entity] |
| 131 |
|
| 132 |
if get_method() == "DELETE": |
| 133 |
if app.config.get("READONLY", True): |
| 134 |
return flask.abort(405) |
| 135 |
|
| 136 |
for entity in entities: |
| 137 |
entity.remove(delete=is_delete()) |
| 138 |
|
| 139 |
return flask.make_response(jsonify({"deleted": True}), 200) |
| 140 |
|
| 141 |
if get_method() == "PATCH" and patchable: |
| 142 |
if app.config.get("READONLY", True): |
| 143 |
return flask.abort(405) |
| 144 |
|
| 145 |
for entity in entities: |
| 146 |
entity.update(flask.request.get_json()) |
| 147 |
entity.try_sync(True, False) # write, don't move |
| 148 |
|
| 149 |
if len(entities) == 1: |
| 150 |
return flask.jsonify(_rep(entities[0], expand=is_expand())) |
| 151 |
if entities: |
| 152 |
return app.response_class( |
| 153 |
json_generator(entities, root=name), |
| 154 |
mimetype="application/json", |
| 155 |
) |
| 156 |
|
| 157 |
elif get_method() == "GET": |
| 158 |
if len(entities) == 1: |
| 159 |
return flask.jsonify(_rep(entities[0], expand=is_expand())) |
| 160 |
if entities: |
| 161 |
return app.response_class( |
| 162 |
json_generator(entities, root=name), |
| 163 |
mimetype="application/json", |
| 164 |
) |
| 165 |
return flask.abort(404) |
| 166 |
|
| 167 |
return flask.abort(405) |
| 168 |
|
| 169 |
responder.__name__ = f"get_{name}" |
| 170 |
|
| 171 |
return responder |
| 172 |
|
| 173 |
return make_responder |
| 174 |
|
| 175 |
|
| 176 |
def resource_query(name: str, patchable: bool = False) -> Any: |
| 177 |
"""Decorates a function to handle RESTful HTTP queries for resources.""" |
| 178 |
|
| 179 |
def make_responder( |
| 180 |
query_func: Callable[[Iterable[str]], Sequence[LibModel]], |
| 181 |
) -> Any: |
| 182 |
def responder(queries: Iterable[str]) -> Any: |
| 183 |
entities = query_func(queries) |
| 184 |
|
| 185 |
if get_method() == "DELETE": |
| 186 |
if app.config.get("READONLY", True): |
| 187 |
return flask.abort(405) |
| 188 |
|
| 189 |
for entity in entities: |
| 190 |
entity.remove(delete=is_delete()) |
| 191 |
|
| 192 |
return flask.make_response(jsonify({"deleted": True}), 200) |
| 193 |
|
| 194 |
if get_method() == "PATCH" and patchable: |
| 195 |
if app.config.get("READONLY", True): |
| 196 |
return flask.abort(405) |
| 197 |
|
| 198 |
for entity in entities: |
| 199 |
entity.update(flask.request.get_json()) |
| 200 |
entity.try_sync(True, False) # write, don't move |
| 201 |
|
| 202 |
return app.response_class( |
| 203 |
json_generator(entities, root=name), |
| 204 |
mimetype="application/json", |
| 205 |
) |
| 206 |
|
| 207 |
if get_method() == "GET": |
| 208 |
return app.response_class( |
| 209 |
json_generator( |
| 210 |
entities, root="results", expand=is_expand() |
| 211 |
), |
| 212 |
mimetype="application/json", |
| 213 |
) |
| 214 |
|
| 215 |
return flask.abort(405) |
| 216 |
|
| 217 |
responder.__name__ = f"query_{name}" |
| 218 |
|
| 219 |
return responder |
| 220 |
|
| 221 |
return make_responder |
| 222 |
|
| 223 |
|
| 224 |
def resource_list(name: str) -> Any: |
| 225 |
"""Decorates a function to handle RESTful HTTP request for a list of |
| 226 |
resources. |
| 227 |
""" |
| 228 |
|
| 229 |
def make_responder(list_all: Callable[[], Sequence[LibModel]]) -> Any: |
| 230 |
def responder() -> Any: |
| 231 |
return app.response_class( |
| 232 |
json_generator(list_all(), root=name, expand=is_expand()), |
| 233 |
mimetype="application/json", |
| 234 |
) |
| 235 |
|
| 236 |
responder.__name__ = f"all_{name}" |
| 237 |
return responder |
| 238 |
|
| 239 |
return make_responder |
| 240 |
|
| 241 |
|
| 242 |
def _get_unique_table_field_values( |
| 243 |
model: type[LibModel], field: str, sort_field: str |
| 244 |
) -> list[Any]: |
| 245 |
"""retrieve all unique values belonging to a key from a model""" |
| 246 |
if field not in model.all_keys() or sort_field not in model.all_keys(): |
| 247 |
raise KeyError |
| 248 |
with g.lib.transaction() as tx: |
| 249 |
rows = tx.query( |
| 250 |
f"SELECT DISTINCT {field} FROM {model._table} ORDER BY {sort_field}" |
| 251 |
) |
| 252 |
return [row[0] for row in rows] |
| 253 |
|
| 254 |
|
| 255 |
class IdListConverter(BaseConverter): |
| 256 |
"""Converts comma separated lists of ids in urls to integer lists.""" |
| 257 |
|
| 258 |
def to_python(self, value: str) -> list[int]: |
| 259 |
ids = [] |
| 260 |
for id_ in value.split(","): |
| 261 |
try: |
| 262 |
ids.append(int(id_)) |
| 263 |
except ValueError: |
| 264 |
pass |
| 265 |
return ids |
| 266 |
|
| 267 |
def to_url(self, value: Sequence[int]) -> str: |
| 268 |
return ",".join(str(v) for v in value) |
| 269 |
|
| 270 |
|
| 271 |
class QueryConverter(PathConverter): |
| 272 |
"""Converts slash separated lists of queries in the url to string list.""" |
| 273 |
|
| 274 |
def to_python(self, value: str) -> list[str]: |
| 275 |
queries = value.split("/") |
| 276 |
"""Do not do path substitution on regex value tests""" |
| 277 |
return [ |
| 278 |
query if "::" in query else query.replace("\\", os.sep) |
| 279 |
for query in queries |
| 280 |
] |
| 281 |
|
| 282 |
def to_url(self, value: Sequence[str]) -> str: |
| 283 |
return "/".join([v.replace(os.sep, "\\") for v in value]) |
| 284 |
|
| 285 |
|
| 286 |
class EverythingConverter(PathConverter): |
| 287 |
part_isolating = False |
| 288 |
regex = ".*?" |
| 289 |
|
| 290 |
|
| 291 |
# Flask setup. |
| 292 |
|
| 293 |
app = flask.Flask(__name__) |
| 294 |
app.url_map.converters["idlist"] = IdListConverter |
| 295 |
app.url_map.converters["query"] = QueryConverter |
| 296 |
app.url_map.converters["everything"] = EverythingConverter |
| 297 |
|
| 298 |
|
| 299 |
@app.before_request |
| 300 |
def before_request() -> None: |
| 301 |
g.lib = app.config["lib"] |
| 302 |
|
| 303 |
|
| 304 |
# Items. |
| 305 |
|
| 306 |
|
| 307 |
@app.route("/item/<idlist:ids>", methods=["GET", "DELETE", "PATCH"]) |
| 308 |
@resource("items", patchable=True) |
| 309 |
def get_item(id_: int) -> Any: |
| 310 |
return g.lib.get_item(id_) |
| 311 |
|
| 312 |
|
| 313 |
@app.route("/item/") |
| 314 |
@app.route("/item/query/") |
| 315 |
@resource_list("items") |
| 316 |
def all_items() -> Any: |
| 317 |
return g.lib.items() |
| 318 |
|
| 319 |
|
| 320 |
@app.route("/item/<int:item_id>/file") |
| 321 |
def item_file(item_id: int) -> Any: |
| 322 |
item = g.lib.get_item(item_id) |
| 323 |
if not item: |
| 324 |
return flask.abort(404, f"Item with id {item_id} not found") |
| 325 |
|
| 326 |
item_path = util.syspath(item.path) |
| 327 |
base_filename = os.path.basename(item_path) |
| 328 |
|
| 329 |
try: |
| 330 |
# Imitate http.server behaviour |
| 331 |
base_filename.encode("latin-1", "strict") |
| 332 |
except UnicodeError: |
| 333 |
safe_filename = unidecode(base_filename) |
| 334 |
else: |
| 335 |
safe_filename = base_filename |
| 336 |
|
| 337 |
return flask.send_file( |
| 338 |
item_path, as_attachment=True, download_name=safe_filename |
| 339 |
) |
| 340 |
|
| 341 |
|
| 342 |
@app.route("/item/query/<query:queries>", methods=["GET", "DELETE", "PATCH"]) |
| 343 |
@resource_query("items", patchable=True) |
| 344 |
def item_query(queries: Sequence[str]) -> Any: |
| 345 |
return g.lib.items(queries) |
| 346 |
|
| 347 |
|
| 348 |
@app.route("/item/path/<everything:path>") |
| 349 |
def item_at_path(path: str) -> Any: |
| 350 |
query = PathQuery("path", path.encode("utf-8")) |
| 351 |
item = g.lib.items(query).get() |
| 352 |
if item: |
| 353 |
return flask.jsonify(_rep(item)) |
| 354 |
return flask.abort(404) |
| 355 |
|
| 356 |
|
| 357 |
@app.route("/item/values/<string:key>") |
| 358 |
def item_unique_field_values(key: str) -> Any: |
| 359 |
sort_key = flask.request.args.get("sort_key", key) |
| 360 |
try: |
| 361 |
values = _get_unique_table_field_values( |
| 362 |
beets.library.Item, key, sort_key |
| 363 |
) |
| 364 |
except KeyError: |
| 365 |
return flask.abort(404) |
| 366 |
return flask.jsonify(values=values) |
| 367 |
|
| 368 |
|
| 369 |
# Albums. |
| 370 |
|
| 371 |
|
| 372 |
@app.route("/album/<idlist:ids>", methods=["GET", "DELETE"]) |
| 373 |
@resource("albums") |
| 374 |
def get_album(id_: int) -> Any: |
| 375 |
return g.lib.get_album(id_) |
| 376 |
|
| 377 |
|
| 378 |
@app.route("/album/") |
| 379 |
@app.route("/album/query/") |
| 380 |
@resource_list("albums") |
| 381 |
def all_albums() -> Any: |
| 382 |
return g.lib.albums() |
| 383 |
|
| 384 |
|
| 385 |
@app.route("/album/query/<query:queries>", methods=["GET", "DELETE"]) |
| 386 |
@resource_query("albums") |
| 387 |
def album_query(queries: Sequence[str]) -> Any: |
| 388 |
return g.lib.albums(queries) |
| 389 |
|
| 390 |
|
| 391 |
@app.route("/album/<int:album_id>/art") |
| 392 |
def album_art(album_id: int) -> Any: |
| 393 |
album = g.lib.get_album(album_id) |
| 394 |
if album and album.artpath: |
| 395 |
return flask.send_file(album.artpath.decode()) |
| 396 |
return flask.abort(404) |
| 397 |
|
| 398 |
|
| 399 |
@app.route("/album/values/<string:key>") |
| 400 |
def album_unique_field_values(key: str) -> Any: |
| 401 |
sort_key = flask.request.args.get("sort_key", key) |
| 402 |
try: |
| 403 |
values = _get_unique_table_field_values( |
| 404 |
beets.library.Album, key, sort_key |
| 405 |
) |
| 406 |
except KeyError: |
| 407 |
return flask.abort(404) |
| 408 |
return flask.jsonify(values=values) |
| 409 |
|
| 410 |
|
| 411 |
# Artists. |
| 412 |
|
| 413 |
|
| 414 |
@app.route("/artist/") |
| 415 |
def all_artists() -> Any: |
| 416 |
with g.lib.transaction() as tx: |
| 417 |
rows = tx.query("SELECT DISTINCT albumartist FROM albums") |
| 418 |
all_artists = [row[0] for row in rows] |
| 419 |
return flask.jsonify(artist_names=all_artists) |
| 420 |
|
| 421 |
|
| 422 |
# Library information. |
| 423 |
|
| 424 |
|
| 425 |
@app.route("/stats") |
| 426 |
def stats() -> Any: |
| 427 |
with g.lib.transaction() as tx: |
| 428 |
item_rows = tx.query("SELECT COUNT(*) FROM items") |
| 429 |
album_rows = tx.query("SELECT COUNT(*) FROM albums") |
| 430 |
return flask.jsonify({"items": item_rows[0][0], "albums": album_rows[0][0]}) |
| 431 |
|
| 432 |
|
| 433 |
# UI. |
| 434 |
|
| 435 |
|
| 436 |
@app.route("/") |
| 437 |
def home() -> Any: |
| 438 |
return flask.render_template("index.html") |
| 439 |
|
| 440 |
|
| 441 |
# Plugin hook. |
| 442 |
|
| 443 |
|
| 444 |
class WebPlugin(BeetsPlugin): |
| 445 |
def __init__(self) -> None: |
| 446 |
super().__init__() |
| 447 |
self.config.add( |
| 448 |
{ |
| 449 |
"host": "127.0.0.1", |
| 450 |
"port": 8337, |
| 451 |
"cors": "", |
| 452 |
"cors_supports_credentials": False, |
| 453 |
"reverse_proxy": False, |
| 454 |
"include_paths": False, |
| 455 |
"readonly": True, |
| 456 |
} |
| 457 |
) |
| 458 |
|
| 459 |
def commands(self) -> list[ui.Subcommand]: |
| 460 |
cmd = ui.Subcommand("web", help="start a Web interface") |
| 461 |
cmd.parser.add_option( |
| 462 |
"-d", |
| 463 |
"--debug", |
| 464 |
action="store_true", |
| 465 |
default=False, |
| 466 |
help="debug mode", |
| 467 |
) |
| 468 |
|
| 469 |
def func(lib: Library, opts: WebCLIOpts, args: list[str]) -> None: |
| 470 |
if args: |
| 471 |
self.config["host"] = args.pop(0) |
| 472 |
if args: |
| 473 |
self.config["port"] = int(args.pop(0)) |
| 474 |
|
| 475 |
app.config["lib"] = lib |
| 476 |
# Normalizes json output |
| 477 |
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False |
| 478 |
|
| 479 |
app.config["INCLUDE_PATHS"] = self.config["include_paths"] |
| 480 |
app.config["READONLY"] = self.config["readonly"] |
| 481 |
|
| 482 |
# Enable CORS if required. |
| 483 |
if self.config["cors"]: |
| 484 |
self._log.info( |
| 485 |
"Enabling CORS with origin: {}", self.config["cors"] |
| 486 |
) |
| 487 |
from flask_cors import CORS |
| 488 |
|
| 489 |
app.config["CORS_ALLOW_HEADERS"] = "Content-Type" |
| 490 |
app.config["CORS_RESOURCES"] = { |
| 491 |
r"/*": {"origins": self.config["cors"].get(str)} |
| 492 |
} |
| 493 |
CORS( |
| 494 |
app, |
| 495 |
supports_credentials=self.config[ |
| 496 |
"cors_supports_credentials" |
| 497 |
].get(bool), |
| 498 |
) |
| 499 |
|
| 500 |
# Allow serving behind a reverse proxy |
| 501 |
if self.config["reverse_proxy"]: |
| 502 |
app.wsgi_app = ReverseProxied(app.wsgi_app) # type: ignore[method-assign] |
| 503 |
|
| 504 |
# Start the web application. |
| 505 |
app.run( |
| 506 |
host=self.config["host"].as_str(), |
| 507 |
port=self.config["port"].get(int), |
| 508 |
debug=opts.debug, |
| 509 |
threaded=True, |
| 510 |
) |
| 511 |
|
| 512 |
cmd.func = func |
| 513 |
return [cmd] |
| 514 |
|
| 515 |
|
| 516 |
class ReverseProxied: |
| 517 |
"""Wrap the application in this middleware and configure the |
| 518 |
front-end server to add these headers, to let you quietly bind |
| 519 |
this to a URL other than / and to an HTTP scheme that is |
| 520 |
different than what is used locally. |
| 521 |
|
| 522 |
In nginx: |
| 523 |
location /myprefix { |
| 524 |
proxy_pass http://192.168.0.1:5001; |
| 525 |
proxy_set_header Host $host; |
| 526 |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; |
| 527 |
proxy_set_header X-Scheme $scheme; |
| 528 |
proxy_set_header X-Script-Name /myprefix; |
| 529 |
} |
| 530 |
|
| 531 |
From: http://flask.pocoo.org/snippets/35/ |
| 532 |
|
| 533 |
:param app: the WSGI application |
| 534 |
""" |
| 535 |
|
| 536 |
def __init__(self, app: Callable[..., Any]) -> None: |
| 537 |
self.app = app |
| 538 |
|
| 539 |
def __call__( |
| 540 |
self, environ: dict[str, Any], start_response: Callable[..., Any] |
| 541 |
) -> Any: |
| 542 |
script_name = environ.get("HTTP_X_SCRIPT_NAME", "") |
| 543 |
if script_name: |
| 544 |
environ["SCRIPT_NAME"] = script_name |
| 545 |
path_info = environ["PATH_INFO"] |
| 546 |
if path_info.startswith(script_name): |
| 547 |
environ["PATH_INFO"] = path_info[len(script_name) :] |
| 548 |
|
| 549 |
scheme = environ.get("HTTP_X_SCHEME", "") |
| 550 |
if scheme: |
| 551 |
environ["wsgi.url_scheme"] = scheme |
| 552 |
return self.app(environ, start_response) |