| 1 |
"""An AURA server using Flask.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import re |
| 7 |
from dataclasses import dataclass |
| 8 |
from mimetypes import guess_type |
| 9 |
from typing import TYPE_CHECKING, Any, ClassVar, Protocol |
| 10 |
|
| 11 |
from flask import ( |
| 12 |
Blueprint, |
| 13 |
Flask, |
| 14 |
current_app, |
| 15 |
make_response, |
| 16 |
request, |
| 17 |
send_file, |
| 18 |
) |
| 19 |
from typing_extensions import Self |
| 20 |
|
| 21 |
from beets import config |
| 22 |
from beets.dbcore import AndQuery, MatchQuery |
| 23 |
from beets.dbcore.sort import FixedFieldSort, MultipleSort, SlowFieldSort |
| 24 |
from beets.library import Album, Item |
| 25 |
from beets.plugins import BeetsPlugin |
| 26 |
from beets.ui import Subcommand, _open_library |
| 27 |
|
| 28 |
if TYPE_CHECKING: |
| 29 |
from collections.abc import Iterable, Sequence |
| 30 |
|
| 31 |
from werkzeug.datastructures import MultiDict |
| 32 |
|
| 33 |
from beets.dbcore import Query |
| 34 |
from beets.dbcore.sort import Sort |
| 35 |
from beets.library import LibModel, Library |
| 36 |
|
| 37 |
from ._typing import JSONDict |
| 38 |
|
| 39 |
|
| 40 |
class AuraCLIOpts(Protocol): |
| 41 |
debug: bool |
| 42 |
|
| 43 |
|
| 44 |
# Constants |
| 45 |
|
| 46 |
# AURA server information |
| 47 |
# TODO: Add version information |
| 48 |
SERVER_INFO = { |
| 49 |
"aura-version": "0", |
| 50 |
"server": "beets-aura", |
| 51 |
"server-version": "0.1", |
| 52 |
"auth-required": False, |
| 53 |
"features": ["albums", "artists", "images"], |
| 54 |
} |
| 55 |
|
| 56 |
# Maps AURA Track attribute to beets Item attribute |
| 57 |
TRACK_ATTR_MAP = { |
| 58 |
# Required |
| 59 |
"title": "title", |
| 60 |
"artist": "artist", |
| 61 |
# Optional |
| 62 |
"album": "album", |
| 63 |
"track": "track", # Track number on album |
| 64 |
"tracktotal": "tracktotal", |
| 65 |
"disc": "disc", |
| 66 |
"disctotal": "disctotal", |
| 67 |
"year": "year", |
| 68 |
"month": "month", |
| 69 |
"day": "day", |
| 70 |
"bpm": "bpm", |
| 71 |
"genre": "genres", |
| 72 |
"genres": "genres", |
| 73 |
"recording-mbid": "mb_trackid", # beets trackid is MB recording |
| 74 |
"track-mbid": "mb_releasetrackid", |
| 75 |
"composer": "composers", |
| 76 |
"albumartist": "albumartist", |
| 77 |
"comments": "comments", |
| 78 |
# Optional for Audio Metadata |
| 79 |
# TODO: Support the mimetype attribute, format != mime type |
| 80 |
# "mimetype": track.format, |
| 81 |
"duration": "length", |
| 82 |
"framerate": "samplerate", |
| 83 |
# I don't think beets has a framecount field |
| 84 |
# "framecount": ???, |
| 85 |
"channels": "channels", |
| 86 |
"bitrate": "bitrate", |
| 87 |
"bitdepth": "bitdepth", |
| 88 |
"size": "filesize", |
| 89 |
} |
| 90 |
|
| 91 |
# Maps AURA Album attribute to beets Album attribute |
| 92 |
ALBUM_ATTR_MAP = { |
| 93 |
# Required |
| 94 |
"title": "album", |
| 95 |
"artist": "albumartist", |
| 96 |
# Optional |
| 97 |
"tracktotal": "albumtotal", |
| 98 |
"disctotal": "disctotal", |
| 99 |
"year": "year", |
| 100 |
"month": "month", |
| 101 |
"day": "day", |
| 102 |
"genre": "genres", |
| 103 |
"genres": "genres", |
| 104 |
"release-mbid": "mb_albumid", |
| 105 |
"release-group-mbid": "mb_releasegroupid", |
| 106 |
} |
| 107 |
|
| 108 |
# Maps AURA Artist attribute to beets Item field |
| 109 |
# Artists are not first-class in beets, so information is extracted from |
| 110 |
# beets Items. |
| 111 |
ARTIST_ATTR_MAP = { |
| 112 |
# Required |
| 113 |
"name": "artist", |
| 114 |
# Optional |
| 115 |
"artist-mbid": "mb_artistid", |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
@dataclass |
| 120 |
class AURADocument: |
| 121 |
"""Base class for building AURA documents.""" |
| 122 |
|
| 123 |
model_cls: ClassVar[type[LibModel]] |
| 124 |
attribute_map: ClassVar[dict[str, str]] |
| 125 |
|
| 126 |
lib: Library |
| 127 |
args: MultiDict[str, str] |
| 128 |
|
| 129 |
@classmethod |
| 130 |
def from_app(cls) -> Self: |
| 131 |
"""Initialise the document using the global app and request.""" |
| 132 |
return cls(current_app.config["lib"], request.args) |
| 133 |
|
| 134 |
@staticmethod |
| 135 |
def error(status: str, title: str, detail: str) -> Any: |
| 136 |
"""Make a response for an error following the JSON:API spec. |
| 137 |
|
| 138 |
Args: |
| 139 |
status: An HTTP status code string, e.g. "404 Not Found". |
| 140 |
title: A short, human-readable summary of the problem. |
| 141 |
detail: A human-readable explanation specific to this |
| 142 |
occurrence of the problem. |
| 143 |
""" |
| 144 |
document = { |
| 145 |
"errors": [{"status": status, "title": title, "detail": detail}] |
| 146 |
} |
| 147 |
return make_response(document, status) |
| 148 |
|
| 149 |
def translate_filters(self) -> AndQuery: |
| 150 |
"""Translate filters from request arguments to a beets Query.""" |
| 151 |
# The format of each filter key in the request parameter is: |
| 152 |
# filter[<attribute>]. This regex extracts <attribute>. |
| 153 |
pattern = re.compile(r"filter\[(?P<attribute>[a-zA-Z0-9_-]+)\]") |
| 154 |
queries = [] |
| 155 |
for key, v in self.args.items(): |
| 156 |
match = pattern.match(key) |
| 157 |
if match: |
| 158 |
# Extract attribute name from key |
| 159 |
aura_attr = match.group("attribute") |
| 160 |
# Get the beets version of the attribute name |
| 161 |
beets_attr = self.attribute_map.get(aura_attr, aura_attr) |
| 162 |
# Add exact match query to list |
| 163 |
queries.append( |
| 164 |
self.model_cls.field_query(beets_attr, v, MatchQuery) |
| 165 |
) |
| 166 |
# NOTE: AURA doesn't officially support multiple queries |
| 167 |
return AndQuery(queries) |
| 168 |
|
| 169 |
def translate_sorts(self) -> MultipleSort | None: |
| 170 |
"""Translate an AURA sort parameter into a beets Sort. |
| 171 |
|
| 172 |
Args: |
| 173 |
sort_arg: The value of the 'sort' query parameter; a comma |
| 174 |
separated list of fields to sort by, in order. |
| 175 |
E.g. "-year,title". |
| 176 |
""" |
| 177 |
# Change HTTP query parameter to a list |
| 178 |
if not (sort_arg := self.args.get("sort")): |
| 179 |
return None |
| 180 |
|
| 181 |
aura_sorts = sort_arg.strip(",").split(",") |
| 182 |
sorts: list[Sort] = [] |
| 183 |
for aura_attr in aura_sorts: |
| 184 |
if aura_attr[0] == "-": |
| 185 |
ascending = False |
| 186 |
# Remove leading "-" |
| 187 |
aura_attr = aura_attr[1:] |
| 188 |
else: |
| 189 |
# JSON:API default |
| 190 |
ascending = True |
| 191 |
# Get the beets version of the attribute name |
| 192 |
beets_attr = self.attribute_map.get(aura_attr, aura_attr) |
| 193 |
# Use slow sort so it works with all fields (inc. computed) |
| 194 |
sorts.append(SlowFieldSort(beets_attr, ascending=ascending)) |
| 195 |
return MultipleSort(sorts) |
| 196 |
|
| 197 |
@staticmethod |
| 198 |
def get_resource_object(lib: Library, *args) -> JSONDict | None: |
| 199 |
raise NotImplementedError |
| 200 |
|
| 201 |
def paginate( |
| 202 |
self, collection: Sequence[Any] |
| 203 |
) -> tuple[list[Any], str | None]: |
| 204 |
"""Get a page of the collection and the URL to the next page. |
| 205 |
|
| 206 |
Args: |
| 207 |
collection: The raw data from which resource objects can be |
| 208 |
built. Could be an sqlite3.Cursor object (tracks and |
| 209 |
albums) or a list of strings (artists). |
| 210 |
""" |
| 211 |
# Pages start from zero |
| 212 |
page = self.args.get("page", 0, int) |
| 213 |
# Use page limit defined in config by default. |
| 214 |
default_limit = config["aura"]["page_limit"].get(int) |
| 215 |
limit = self.args.get("limit", default_limit, int) |
| 216 |
# start = offset of first item to return |
| 217 |
start = page * limit |
| 218 |
# end = offset of last item + 1 |
| 219 |
end = start + limit |
| 220 |
if end > len(collection): |
| 221 |
end = len(collection) |
| 222 |
next_url = None |
| 223 |
else: |
| 224 |
# Not the last page so work out links.next url |
| 225 |
if not self.args: |
| 226 |
# No existing arguments, so current page is 0 |
| 227 |
next_url = f"{request.url}?page=1" |
| 228 |
elif not self.args.get("page", None): |
| 229 |
# No existing page argument, so add one to the end |
| 230 |
next_url = f"{request.url}&page=1" |
| 231 |
else: |
| 232 |
# Increment page token by 1 |
| 233 |
next_url = request.url.replace( |
| 234 |
f"page={page}", f"page={page + 1}" |
| 235 |
) |
| 236 |
# Get only the items in the page range |
| 237 |
data = [ |
| 238 |
self.get_resource_object(self.lib, collection[i]) |
| 239 |
for i in range(start, end) |
| 240 |
] |
| 241 |
return data, next_url |
| 242 |
|
| 243 |
def get_included( |
| 244 |
self, data: Iterable[JSONDict], include_str: str |
| 245 |
) -> list[JSONDict]: |
| 246 |
"""Build a list of resource objects for inclusion. |
| 247 |
|
| 248 |
Args: |
| 249 |
data: An array of dicts in the form of resource objects. |
| 250 |
include_str: A comma separated list of resource types to |
| 251 |
include. E.g. "tracks,images". |
| 252 |
""" |
| 253 |
# Change HTTP query parameter to a list |
| 254 |
to_include = include_str.strip(",").split(",") |
| 255 |
# Build a list of unique type and id combinations |
| 256 |
# For each resource object in the primary data, iterate over it's |
| 257 |
# relationships. If a relationship matches one of the types |
| 258 |
# requested for inclusion (e.g. "albums") then add each type-id pair |
| 259 |
# under the "data" key to unique_identifiers, checking first that |
| 260 |
# it has not already been added. This ensures that no resources are |
| 261 |
# included more than once. |
| 262 |
unique_identifiers = [] |
| 263 |
for res_obj in data: |
| 264 |
for rel_name, rel_obj in res_obj["relationships"].items(): |
| 265 |
if rel_name in to_include: |
| 266 |
# NOTE: Assumes relationship is to-many |
| 267 |
for identifier in rel_obj["data"]: |
| 268 |
if identifier not in unique_identifiers: |
| 269 |
unique_identifiers.append(identifier) |
| 270 |
# TODO: I think this could be improved |
| 271 |
included: list[JSONDict | None] = [] |
| 272 |
for identifier in unique_identifiers: |
| 273 |
res_type = identifier["type"] |
| 274 |
if res_type == "track": |
| 275 |
track_id = int(identifier["id"]) |
| 276 |
if track := self.lib.get_item(track_id): |
| 277 |
included.append( |
| 278 |
TrackDocument.get_resource_object(self.lib, track) |
| 279 |
) |
| 280 |
elif res_type == "album": |
| 281 |
album_id = int(identifier["id"]) |
| 282 |
if album := self.lib.get_album(album_id): |
| 283 |
included.append( |
| 284 |
AlbumDocument.get_resource_object(self.lib, album) |
| 285 |
) |
| 286 |
elif res_type == "artist": |
| 287 |
artist_id = identifier["id"] |
| 288 |
included.append( |
| 289 |
ArtistDocument.get_resource_object(self.lib, artist_id) |
| 290 |
) |
| 291 |
elif res_type == "image": |
| 292 |
image_id = identifier["id"] |
| 293 |
included.append( |
| 294 |
ImageDocument.get_resource_object(self.lib, image_id) |
| 295 |
) |
| 296 |
else: |
| 297 |
raise ValueError(f"Invalid resource type: {res_type}") |
| 298 |
return list(filter(None, included)) |
| 299 |
|
| 300 |
def get_collection( |
| 301 |
self, |
| 302 |
query: str | Sequence[str] | Query | None = None, |
| 303 |
sort: Sort | None = None, |
| 304 |
) -> Any: |
| 305 |
raise NotImplementedError |
| 306 |
|
| 307 |
def all_resources(self) -> JSONDict: |
| 308 |
"""Build document for /tracks, /albums or /artists.""" |
| 309 |
query = self.translate_filters() |
| 310 |
sort = self.translate_sorts() |
| 311 |
# Get information from the library |
| 312 |
collection = self.get_collection(query=query, sort=sort) |
| 313 |
# Convert info to AURA form and paginate it |
| 314 |
data, next_url = self.paginate(collection) |
| 315 |
document: JSONDict = {"data": data} |
| 316 |
# If there are more pages then provide a way to access them |
| 317 |
if next_url: |
| 318 |
document["links"] = {"next": next_url} |
| 319 |
# Include related resources for each element in "data" |
| 320 |
include_str = self.args.get("include", None) |
| 321 |
if include_str: |
| 322 |
document["included"] = self.get_included(data, include_str) |
| 323 |
return document |
| 324 |
|
| 325 |
def single_resource_document(self, resource_object: JSONDict) -> JSONDict: |
| 326 |
"""Build document for a specific requested resource. |
| 327 |
|
| 328 |
Args: |
| 329 |
resource_object: A dictionary in the form of a JSON:API |
| 330 |
resource object. |
| 331 |
""" |
| 332 |
document: JSONDict = {"data": resource_object} |
| 333 |
include_str = self.args.get("include", None) |
| 334 |
if include_str: |
| 335 |
# [document["data"]] is because arg needs to be list |
| 336 |
document["included"] = self.get_included( |
| 337 |
[document["data"]], include_str |
| 338 |
) |
| 339 |
return document |
| 340 |
|
| 341 |
|
| 342 |
class TrackDocument(AURADocument): |
| 343 |
"""Class for building documents for /tracks endpoints.""" |
| 344 |
|
| 345 |
model_cls = Item |
| 346 |
|
| 347 |
attribute_map = TRACK_ATTR_MAP |
| 348 |
|
| 349 |
def get_collection( |
| 350 |
self, |
| 351 |
query: str | Sequence[str] | Query | None = None, |
| 352 |
sort: Sort | None = None, |
| 353 |
) -> Any: |
| 354 |
"""Get Item objects from the library. |
| 355 |
|
| 356 |
Args: |
| 357 |
query: A beets Query object or a beets query string. |
| 358 |
sort: A beets Sort object. |
| 359 |
""" |
| 360 |
return self.lib.items(query, sort) |
| 361 |
|
| 362 |
@staticmethod |
| 363 |
def get_resource_object(lib: Library, track: Item) -> JSONDict: |
| 364 |
"""Construct a JSON:API resource object from a beets Item. |
| 365 |
|
| 366 |
Args: |
| 367 |
track: A beets Item object. |
| 368 |
""" |
| 369 |
attributes = {} |
| 370 |
# Use aura => beets attribute map, e.g. size => filesize |
| 371 |
for aura_attr, beets_attr in TRACK_ATTR_MAP.items(): |
| 372 |
a = getattr(track, beets_attr) |
| 373 |
# Only set attribute if it's not None, 0, "", etc. |
| 374 |
# NOTE: This could result in required attributes not being set |
| 375 |
if a: |
| 376 |
attributes[aura_attr] = a |
| 377 |
|
| 378 |
# JSON:API one-to-many relationship to parent album |
| 379 |
relationships = { |
| 380 |
"artists": {"data": [{"type": "artist", "id": track.artist}]} |
| 381 |
} |
| 382 |
# Only add album relationship if not singleton |
| 383 |
if not track.singleton: |
| 384 |
relationships["albums"] = { |
| 385 |
"data": [{"type": "album", "id": str(track.album_id)}] |
| 386 |
} |
| 387 |
|
| 388 |
return { |
| 389 |
"type": "track", |
| 390 |
"id": str(track.id), |
| 391 |
"attributes": attributes, |
| 392 |
"relationships": relationships, |
| 393 |
} |
| 394 |
|
| 395 |
def single_resource(self, track_id: int) -> Any: |
| 396 |
"""Get track from the library and build a document. |
| 397 |
|
| 398 |
Args: |
| 399 |
track_id: The beets id of the track (integer). |
| 400 |
""" |
| 401 |
track = self.lib.get_item(track_id) |
| 402 |
if not track: |
| 403 |
return self.error( |
| 404 |
"404 Not Found", |
| 405 |
"No track with the requested id.", |
| 406 |
f"There is no track with an id of {track_id} in the library.", |
| 407 |
) |
| 408 |
return self.single_resource_document( |
| 409 |
self.get_resource_object(self.lib, track) |
| 410 |
) |
| 411 |
|
| 412 |
|
| 413 |
class AlbumDocument(AURADocument): |
| 414 |
"""Class for building documents for /albums endpoints.""" |
| 415 |
|
| 416 |
model_cls = Album |
| 417 |
|
| 418 |
attribute_map = ALBUM_ATTR_MAP |
| 419 |
|
| 420 |
def get_collection( |
| 421 |
self, |
| 422 |
query: str | Sequence[str] | Query | None = None, |
| 423 |
sort: Sort | None = None, |
| 424 |
) -> Any: |
| 425 |
"""Get Album objects from the library. |
| 426 |
|
| 427 |
Args: |
| 428 |
query: A beets Query object or a beets query string. |
| 429 |
sort: A beets Sort object. |
| 430 |
""" |
| 431 |
return self.lib.albums(query, sort) |
| 432 |
|
| 433 |
@staticmethod |
| 434 |
def get_resource_object(lib: Library, album: Album) -> JSONDict: |
| 435 |
"""Construct a JSON:API resource object from a beets Album. |
| 436 |
|
| 437 |
Args: |
| 438 |
album: A beets Album object. |
| 439 |
""" |
| 440 |
attributes = {} |
| 441 |
# Use aura => beets attribute name map |
| 442 |
for aura_attr, beets_attr in ALBUM_ATTR_MAP.items(): |
| 443 |
a = getattr(album, beets_attr) |
| 444 |
# Only set attribute if it's not None, 0, "", etc. |
| 445 |
# NOTE: This could mean required attributes are not set |
| 446 |
if a: |
| 447 |
attributes[aura_attr] = a |
| 448 |
|
| 449 |
# Get beets Item objects for all tracks in the album sorted by |
| 450 |
# track number. Sorting is not required but it's nice. |
| 451 |
query = MatchQuery("album_id", album.id) |
| 452 |
sort = FixedFieldSort("track", ascending=True) |
| 453 |
tracks = lib.items(query, sort) |
| 454 |
# JSON:API one-to-many relationship to tracks on the album |
| 455 |
relationships = { |
| 456 |
"tracks": { |
| 457 |
"data": [{"type": "track", "id": str(t.id)} for t in tracks] |
| 458 |
} |
| 459 |
} |
| 460 |
# Add images relationship if album has associated images |
| 461 |
if album.artpath: |
| 462 |
path = os.fsdecode(album.artpath) |
| 463 |
filename = path.split("/")[-1] |
| 464 |
image_id = f"album-{album.id}-{filename}" |
| 465 |
relationships["images"] = { |
| 466 |
"data": [{"type": "image", "id": image_id}] |
| 467 |
} |
| 468 |
# Add artist relationship if artist name is same on tracks |
| 469 |
# Tracks are used to define artists so don't albumartist |
| 470 |
# Check for all tracks in case some have featured artists |
| 471 |
if album.albumartist in [t.artist for t in tracks]: |
| 472 |
relationships["artists"] = { |
| 473 |
"data": [{"type": "artist", "id": album.albumartist}] |
| 474 |
} |
| 475 |
|
| 476 |
return { |
| 477 |
"type": "album", |
| 478 |
"id": str(album.id), |
| 479 |
"attributes": attributes, |
| 480 |
"relationships": relationships, |
| 481 |
} |
| 482 |
|
| 483 |
def single_resource(self, album_id: int) -> Any: |
| 484 |
"""Get album from the library and build a document. |
| 485 |
|
| 486 |
Args: |
| 487 |
album_id: The beets id of the album (integer). |
| 488 |
""" |
| 489 |
album = self.lib.get_album(album_id) |
| 490 |
if not album: |
| 491 |
return self.error( |
| 492 |
"404 Not Found", |
| 493 |
"No album with the requested id.", |
| 494 |
f"There is no album with an id of {album_id} in the library.", |
| 495 |
) |
| 496 |
return self.single_resource_document( |
| 497 |
self.get_resource_object(self.lib, album) |
| 498 |
) |
| 499 |
|
| 500 |
|
| 501 |
class ArtistDocument(AURADocument): |
| 502 |
"""Class for building documents for /artists endpoints.""" |
| 503 |
|
| 504 |
model_cls = Item |
| 505 |
|
| 506 |
attribute_map = ARTIST_ATTR_MAP |
| 507 |
|
| 508 |
def get_collection( |
| 509 |
self, |
| 510 |
query: str | Sequence[str] | Query | None = None, |
| 511 |
sort: Sort | None = None, |
| 512 |
) -> Any: |
| 513 |
"""Get a list of artist names from the library. |
| 514 |
|
| 515 |
Args: |
| 516 |
query: A beets Query object or a beets query string. |
| 517 |
sort: A beets Sort object. |
| 518 |
""" |
| 519 |
# Gets only tracks with matching artist information |
| 520 |
tracks = self.lib.items(query, sort) |
| 521 |
collection = [] |
| 522 |
for track in tracks: |
| 523 |
# Do not add duplicates |
| 524 |
if track.artist not in collection: |
| 525 |
collection.append(track.artist) |
| 526 |
return collection |
| 527 |
|
| 528 |
@staticmethod |
| 529 |
def get_resource_object(lib: Library, artist_id: str) -> JSONDict | None: |
| 530 |
"""Construct a JSON:API resource object for the given artist. |
| 531 |
|
| 532 |
Args: |
| 533 |
artist_id: A string which is the artist's name. |
| 534 |
""" |
| 535 |
# Get tracks where artist field exactly matches artist_id |
| 536 |
query = MatchQuery("artist", artist_id) |
| 537 |
tracks = lib.items(query) |
| 538 |
if not tracks: |
| 539 |
return None |
| 540 |
|
| 541 |
# Get artist information from the first track |
| 542 |
# NOTE: It could be that the first track doesn't have a |
| 543 |
# MusicBrainz id but later tracks do, which isn't ideal. |
| 544 |
attributes = {} |
| 545 |
# Use aura => beets attribute map, e.g. artist => name |
| 546 |
for aura_attr, beets_attr in ARTIST_ATTR_MAP.items(): |
| 547 |
a = getattr(tracks[0], beets_attr) |
| 548 |
# Only set attribute if it's not None, 0, "", etc. |
| 549 |
# NOTE: This could mean required attributes are not set |
| 550 |
if a: |
| 551 |
attributes[aura_attr] = a |
| 552 |
|
| 553 |
relationships = { |
| 554 |
"tracks": { |
| 555 |
"data": [{"type": "track", "id": str(t.id)} for t in tracks] |
| 556 |
} |
| 557 |
} |
| 558 |
album_query = MatchQuery("albumartist", artist_id) |
| 559 |
albums = lib.albums(query=album_query) |
| 560 |
if len(albums) != 0: |
| 561 |
relationships["albums"] = { |
| 562 |
"data": [{"type": "album", "id": str(a.id)} for a in albums] |
| 563 |
} |
| 564 |
|
| 565 |
return { |
| 566 |
"type": "artist", |
| 567 |
"id": artist_id, |
| 568 |
"attributes": attributes, |
| 569 |
"relationships": relationships, |
| 570 |
} |
| 571 |
|
| 572 |
def single_resource(self, artist_id: str) -> Any: |
| 573 |
"""Get info for the requested artist and build a document. |
| 574 |
|
| 575 |
Args: |
| 576 |
artist_id: A string which is the artist's name. |
| 577 |
""" |
| 578 |
artist_resource = self.get_resource_object(self.lib, artist_id) |
| 579 |
if not artist_resource: |
| 580 |
return self.error( |
| 581 |
"404 Not Found", |
| 582 |
"No artist with the requested id.", |
| 583 |
f"There is no artist with an id of {artist_id} in the library.", |
| 584 |
) |
| 585 |
return self.single_resource_document(artist_resource) |
| 586 |
|
| 587 |
|
| 588 |
def safe_filename(fn: str) -> bool: |
| 589 |
"""Check whether a string is a simple (non-path) filename. |
| 590 |
|
| 591 |
For example, `foo.txt` is safe because it is a "plain" filename. But |
| 592 |
`foo/bar.txt` and `../foo.txt` and `.` are all non-safe because they |
| 593 |
can traverse to other directories other than the current one. |
| 594 |
""" |
| 595 |
# Rule out any directories. |
| 596 |
if os.path.basename(fn) != fn: |
| 597 |
return False |
| 598 |
|
| 599 |
# In single names, rule out Unix directory traversal names. |
| 600 |
if fn in (".", ".."): |
| 601 |
return False |
| 602 |
|
| 603 |
return True |
| 604 |
|
| 605 |
|
| 606 |
class ImageDocument(AURADocument): |
| 607 |
"""Class for building documents for /images/(id) endpoints.""" |
| 608 |
|
| 609 |
model_cls = Album |
| 610 |
|
| 611 |
@staticmethod |
| 612 |
def get_image_path(lib: Library, image_id: str) -> str | None: |
| 613 |
"""Works out the full path to the image with the given id. |
| 614 |
|
| 615 |
Returns None if there is no such image. |
| 616 |
|
| 617 |
Args: |
| 618 |
image_id: A string in the form |
| 619 |
"<parent_type>-<parent_id>-<img_filename>". |
| 620 |
""" |
| 621 |
# Split image_id into its constituent parts |
| 622 |
id_split = image_id.split("-") |
| 623 |
if len(id_split) < 3: |
| 624 |
# image_id is not in the required format |
| 625 |
return None |
| 626 |
parent_type = id_split[0] |
| 627 |
parent_id = id_split[1] |
| 628 |
img_filename = "-".join(id_split[2:]) |
| 629 |
if not safe_filename(img_filename): |
| 630 |
return None |
| 631 |
|
| 632 |
# Get the path to the directory parent's images are in |
| 633 |
if parent_type == "album": |
| 634 |
album = lib.get_album(int(parent_id)) |
| 635 |
if not album or not album.artpath: |
| 636 |
return None |
| 637 |
# Cut the filename off of artpath |
| 638 |
# This is in preparation for supporting images in the same |
| 639 |
# directory that are not tracked by beets. |
| 640 |
artpath = os.fsdecode(album.artpath) |
| 641 |
dir_path = "/".join(artpath.split("/")[:-1]) |
| 642 |
else: |
| 643 |
# Images for other resource types are not supported |
| 644 |
return None |
| 645 |
|
| 646 |
img_path = os.path.join(dir_path, img_filename) |
| 647 |
# Check the image actually exists |
| 648 |
if os.path.isfile(img_path): |
| 649 |
return img_path |
| 650 |
return None |
| 651 |
|
| 652 |
@staticmethod |
| 653 |
def get_resource_object(lib: Library, image_id: str) -> JSONDict | None: |
| 654 |
"""Construct a JSON:API resource object for the given image. |
| 655 |
|
| 656 |
Args: |
| 657 |
image_id: A string in the form |
| 658 |
"<parent_type>-<parent_id>-<img_filename>". |
| 659 |
""" |
| 660 |
# Could be called as a static method, so can't use |
| 661 |
# self.get_image_path() |
| 662 |
image_path = ImageDocument.get_image_path(lib, image_id) |
| 663 |
if not image_path: |
| 664 |
return None |
| 665 |
|
| 666 |
attributes = { |
| 667 |
"role": "cover", |
| 668 |
"mimetype": guess_type(image_path)[0], |
| 669 |
"size": os.path.getsize(image_path), |
| 670 |
} |
| 671 |
try: |
| 672 |
from PIL import Image |
| 673 |
except ImportError: |
| 674 |
pass |
| 675 |
else: |
| 676 |
im = Image.open(image_path) |
| 677 |
attributes["width"] = im.width |
| 678 |
attributes["height"] = im.height |
| 679 |
|
| 680 |
relationships = {} |
| 681 |
# Split id into [parent_type, parent_id, filename] |
| 682 |
id_split = image_id.split("-") |
| 683 |
relationships[f"{id_split[0]}s"] = { |
| 684 |
"data": [{"type": id_split[0], "id": id_split[1]}] |
| 685 |
} |
| 686 |
|
| 687 |
return { |
| 688 |
"id": image_id, |
| 689 |
"type": "image", |
| 690 |
# Remove attributes that are None, 0, "", etc. |
| 691 |
"attributes": {k: v for k, v in attributes.items() if v}, |
| 692 |
"relationships": relationships, |
| 693 |
} |
| 694 |
|
| 695 |
def single_resource(self, image_id: str) -> Any: |
| 696 |
"""Get info for the requested image and build a document. |
| 697 |
|
| 698 |
Args: |
| 699 |
image_id: A string in the form |
| 700 |
"<parent_type>-<parent_id>-<img_filename>". |
| 701 |
""" |
| 702 |
image_resource = self.get_resource_object(self.lib, image_id) |
| 703 |
if not image_resource: |
| 704 |
return self.error( |
| 705 |
"404 Not Found", |
| 706 |
"No image with the requested id.", |
| 707 |
f"There is no image with an id of {image_id} in the library.", |
| 708 |
) |
| 709 |
return self.single_resource_document(image_resource) |
| 710 |
|
| 711 |
|
| 712 |
# Initialise flask blueprint |
| 713 |
aura_bp = Blueprint("aura_bp", __name__) |
| 714 |
|
| 715 |
|
| 716 |
@aura_bp.route("/server") |
| 717 |
def server_info() -> dict[str, JSONDict]: |
| 718 |
"""Respond with info about the server.""" |
| 719 |
return {"data": {"type": "server", "id": "0", "attributes": SERVER_INFO}} |
| 720 |
|
| 721 |
|
| 722 |
# Track endpoints |
| 723 |
|
| 724 |
|
| 725 |
@aura_bp.route("/tracks") |
| 726 |
def all_tracks() -> Any: |
| 727 |
"""Respond with a list of all tracks and related information.""" |
| 728 |
return TrackDocument.from_app().all_resources() |
| 729 |
|
| 730 |
|
| 731 |
@aura_bp.route("/tracks/<int:track_id>") |
| 732 |
def single_track(track_id: int) -> Any: |
| 733 |
"""Respond with info about the specified track. |
| 734 |
|
| 735 |
Args: |
| 736 |
track_id: The id of the track provided in the URL (integer). |
| 737 |
""" |
| 738 |
return TrackDocument.from_app().single_resource(track_id) |
| 739 |
|
| 740 |
|
| 741 |
@aura_bp.route("/tracks/<int:track_id>/audio") |
| 742 |
def audio_file(track_id: int) -> Any: |
| 743 |
"""Supply an audio file for the specified track. |
| 744 |
|
| 745 |
Args: |
| 746 |
track_id: The id of the track provided in the URL (integer). |
| 747 |
""" |
| 748 |
track = current_app.config["lib"].get_item(track_id) |
| 749 |
if not track: |
| 750 |
return AURADocument.error( |
| 751 |
"404 Not Found", |
| 752 |
"No track with the requested id.", |
| 753 |
f"There is no track with an id of {track_id} in the library.", |
| 754 |
) |
| 755 |
|
| 756 |
path = os.fsdecode(track.path) |
| 757 |
if not os.path.isfile(path): |
| 758 |
return AURADocument.error( |
| 759 |
"404 Not Found", |
| 760 |
"No audio file for the requested track.", |
| 761 |
f"There is no audio file for track {track_id} at the expected" |
| 762 |
" location", |
| 763 |
) |
| 764 |
|
| 765 |
file_mimetype = guess_type(path)[0] |
| 766 |
if not file_mimetype: |
| 767 |
return AURADocument.error( |
| 768 |
"500 Internal Server Error", |
| 769 |
"Requested audio file has an unknown mimetype.", |
| 770 |
f"The audio file for track {track_id} has an unknown mimetype. " |
| 771 |
f"Its file extension is {path.split('.')[-1]}.", |
| 772 |
) |
| 773 |
|
| 774 |
# Check that the Accept header contains the file's mimetype |
| 775 |
# Takes into account */* and audio/* |
| 776 |
# Adding support for the bitrate parameter would require some effort so I |
| 777 |
# left it out. This means the client could be sent an error even if the |
| 778 |
# audio doesn't need transcoding. |
| 779 |
if not request.accept_mimetypes.best_match([file_mimetype]): |
| 780 |
return AURADocument.error( |
| 781 |
"406 Not Acceptable", |
| 782 |
"Unsupported MIME type or bitrate parameter in Accept header.", |
| 783 |
f"The audio file for track {track_id} is only available as" |
| 784 |
f" {file_mimetype} and bitrate parameters are not supported.", |
| 785 |
) |
| 786 |
|
| 787 |
return send_file( |
| 788 |
path, |
| 789 |
mimetype=file_mimetype, |
| 790 |
# Handles filename in Content-Disposition header |
| 791 |
as_attachment=True, |
| 792 |
# Tries to upgrade the stream to support range requests |
| 793 |
conditional=True, |
| 794 |
) |
| 795 |
|
| 796 |
|
| 797 |
# Album endpoints |
| 798 |
|
| 799 |
|
| 800 |
@aura_bp.route("/albums") |
| 801 |
def all_albums() -> Any: |
| 802 |
"""Respond with a list of all albums and related information.""" |
| 803 |
return AlbumDocument.from_app().all_resources() |
| 804 |
|
| 805 |
|
| 806 |
@aura_bp.route("/albums/<int:album_id>") |
| 807 |
def single_album(album_id: int) -> Any: |
| 808 |
"""Respond with info about the specified album. |
| 809 |
|
| 810 |
Args: |
| 811 |
album_id: The id of the album provided in the URL (integer). |
| 812 |
""" |
| 813 |
return AlbumDocument.from_app().single_resource(album_id) |
| 814 |
|
| 815 |
|
| 816 |
# Artist endpoints |
| 817 |
# Artist ids are their names |
| 818 |
|
| 819 |
|
| 820 |
@aura_bp.route("/artists") |
| 821 |
def all_artists() -> Any: |
| 822 |
"""Respond with a list of all artists and related information.""" |
| 823 |
return ArtistDocument.from_app().all_resources() |
| 824 |
|
| 825 |
|
| 826 |
# Using the path converter allows slashes in artist_id |
| 827 |
@aura_bp.route("/artists/<path:artist_id>") |
| 828 |
def single_artist(artist_id: str) -> Any: |
| 829 |
"""Respond with info about the specified artist. |
| 830 |
|
| 831 |
Args: |
| 832 |
artist_id: The id of the artist provided in the URL. A string |
| 833 |
which is the artist's name. |
| 834 |
""" |
| 835 |
return ArtistDocument.from_app().single_resource(artist_id) |
| 836 |
|
| 837 |
|
| 838 |
# Image endpoints |
| 839 |
# Image ids are in the form <parent_type>-<parent_id>-<img_filename> |
| 840 |
# For example: album-13-cover.jpg |
| 841 |
|
| 842 |
|
| 843 |
@aura_bp.route("/images/<string:image_id>") |
| 844 |
def single_image(image_id: str) -> Any: |
| 845 |
"""Respond with info about the specified image. |
| 846 |
|
| 847 |
Args: |
| 848 |
image_id: The id of the image provided in the URL. A string in |
| 849 |
the form "<parent_type>-<parent_id>-<img_filename>". |
| 850 |
""" |
| 851 |
return ImageDocument.from_app().single_resource(image_id) |
| 852 |
|
| 853 |
|
| 854 |
@aura_bp.route("/images/<string:image_id>/file") |
| 855 |
def image_file(image_id: str) -> Any: |
| 856 |
"""Supply an image file for the specified image. |
| 857 |
|
| 858 |
Args: |
| 859 |
image_id: The id of the image provided in the URL. A string in |
| 860 |
the form "<parent_type>-<parent_id>-<img_filename>". |
| 861 |
""" |
| 862 |
img_path = ImageDocument.get_image_path(current_app.config["lib"], image_id) |
| 863 |
if not img_path: |
| 864 |
return AURADocument.error( |
| 865 |
"404 Not Found", |
| 866 |
"No image with the requested id.", |
| 867 |
f"There is no image with an id of {image_id} in the library", |
| 868 |
) |
| 869 |
return send_file(img_path) |
| 870 |
|
| 871 |
|
| 872 |
# WSGI app |
| 873 |
|
| 874 |
|
| 875 |
def create_app() -> Flask: |
| 876 |
"""An application factory for use by a WSGI server.""" |
| 877 |
config["aura"].add( |
| 878 |
{ |
| 879 |
"host": "127.0.0.1", |
| 880 |
"port": 8337, |
| 881 |
"cors": [], |
| 882 |
"cors_supports_credentials": False, |
| 883 |
"page_limit": 500, |
| 884 |
} |
| 885 |
) |
| 886 |
|
| 887 |
app = Flask(__name__) |
| 888 |
# Register AURA blueprint view functions under a URL prefix |
| 889 |
app.register_blueprint(aura_bp, url_prefix="/aura") |
| 890 |
# AURA specifies mimetype MUST be this |
| 891 |
app.config["JSONIFY_MIMETYPE"] = "application/vnd.api+json" |
| 892 |
# Disable auto-sorting of JSON keys |
| 893 |
app.config["JSON_SORT_KEYS"] = False |
| 894 |
# Provide a way to access the beets library |
| 895 |
# The normal method of using the Library and config provided in the |
| 896 |
# command function is not used because create_app() could be called |
| 897 |
# by an external WSGI server. |
| 898 |
# NOTE: this uses a 'private' function from beets.ui.__init__ |
| 899 |
app.config["lib"] = _open_library(config) |
| 900 |
|
| 901 |
# Enable CORS if required |
| 902 |
cors = config["aura"]["cors"].as_str_seq(split=True) |
| 903 |
if cors: |
| 904 |
from flask_cors import CORS |
| 905 |
|
| 906 |
# "Accept" is the only header clients use |
| 907 |
app.config["CORS_ALLOW_HEADERS"] = "Accept" |
| 908 |
app.config["CORS_RESOURCES"] = {r"/aura/*": {"origins": cors}} |
| 909 |
app.config["CORS_SUPPORTS_CREDENTIALS"] = config["aura"][ |
| 910 |
"cors_supports_credentials" |
| 911 |
].get(bool) |
| 912 |
CORS(app) |
| 913 |
|
| 914 |
return app |
| 915 |
|
| 916 |
|
| 917 |
# Beets Plugin Hook |
| 918 |
|
| 919 |
|
| 920 |
class AURAPlugin(BeetsPlugin): |
| 921 |
"""The BeetsPlugin subclass for the AURA server plugin.""" |
| 922 |
|
| 923 |
def __init__(self) -> None: |
| 924 |
"""Add configuration options for the AURA plugin.""" |
| 925 |
super().__init__() |
| 926 |
|
| 927 |
def commands(self) -> list[Subcommand]: |
| 928 |
"""Add subcommand used to run the AURA server.""" |
| 929 |
|
| 930 |
def run_aura(lib: Library, opts: AuraCLIOpts, args: list[str]) -> None: |
| 931 |
"""Run the application using Flask's built in-server. |
| 932 |
|
| 933 |
Args: |
| 934 |
lib: A beets Library object (not used). |
| 935 |
opts: Command line options. An optparse.Values object. |
| 936 |
args: The list of arguments to process (not used). |
| 937 |
""" |
| 938 |
app = create_app() |
| 939 |
# Start the built-in server (not intended for production) |
| 940 |
app.run( |
| 941 |
host=self.config["host"].get(str), |
| 942 |
port=self.config["port"].get(int), |
| 943 |
debug=opts.debug, |
| 944 |
threaded=True, |
| 945 |
) |
| 946 |
|
| 947 |
run_aura_cmd = Subcommand("aura", help="run an AURA server") |
| 948 |
run_aura_cmd.parser.add_option( |
| 949 |
"-d", |
| 950 |
"--debug", |
| 951 |
action="store_true", |
| 952 |
default=False, |
| 953 |
help="use Flask debug mode", |
| 954 |
) |
| 955 |
run_aura_cmd.func = run_aura |
| 956 |
return [run_aura_cmd] |