Last.fm API core: signatures, XML/JSON responses and dispatcher
- /2.0/ dispatcher backed by a method registry that declares each method's params and signature/session requirements - api_sig verification per the Last.fm auth spec - XML (default) and Last.fm-style JSON rendering, including error shapes and HTTP statuses per error code - Last.fm request, error and auth-failure metrics with bounded labels Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ae8d3b65db
commit
9af8a4be8b
11 files changed
+585
No files matched your search
@@ -0,0 +1,95 @@
|
||||
"""Last.fm / Audioscrobbler 2.0 compatible API, mounted at /2.0/."""
|
||||
|
||||
import time
|
||||
|
||||
from flask import Blueprint, Response, request
|
||||
|
||||
from scrobbler import metrics
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.lastfm import errors, signature
|
||||
from scrobbler.lastfm.errors import LastFMError
|
||||
from scrobbler.lastfm.registry import METHODS, Call, LastfmMethod
|
||||
from scrobbler.lastfm.responses import render, render_error
|
||||
from scrobbler.models import ApiApp, Session
|
||||
|
||||
bp = Blueprint("lastfm", __name__)
|
||||
|
||||
_AUTH_FAILURE_REASONS = {
|
||||
errors.INVALID_API_KEY: "bad_api_key",
|
||||
errors.INVALID_SIGNATURE: "bad_signature",
|
||||
errors.INVALID_SESSION_KEY: "bad_session",
|
||||
errors.AUTHENTICATION_FAILED: "bad_password",
|
||||
errors.TOKEN_EXPIRED: "token_expired",
|
||||
errors.UNAUTHORIZED_TOKEN: "token_unauthorized",
|
||||
}
|
||||
|
||||
|
||||
def _request_params() -> dict[str, str]:
|
||||
# Clients send params in the query string (GET) or a form body (POST); body wins.
|
||||
params = request.args.to_dict()
|
||||
params.update(request.form.to_dict())
|
||||
return params
|
||||
|
||||
|
||||
def _authenticate(method: LastfmMethod, params: dict[str, str], fmt: str) -> Call:
|
||||
api_key = params.get("api_key")
|
||||
if not api_key:
|
||||
raise LastFMError(errors.INVALID_PARAMETERS, "Missing required parameter: api_key")
|
||||
api_app = db.session.scalar(db.select(ApiApp).filter_by(api_key=api_key))
|
||||
if api_app is None:
|
||||
raise LastFMError(errors.INVALID_API_KEY)
|
||||
if method.signed and not signature.is_valid(params, api_app.shared_secret):
|
||||
raise LastFMError(errors.INVALID_SIGNATURE)
|
||||
|
||||
call = Call(params=params, api_app=api_app, format=fmt)
|
||||
if method.session:
|
||||
sk = params.get("sk")
|
||||
if not sk:
|
||||
raise LastFMError(errors.INVALID_PARAMETERS, "Missing required parameter: sk")
|
||||
session = db.session.scalar(db.select(Session).filter_by(session_key=sk))
|
||||
if session is None or session.api_app_id != api_app.id:
|
||||
raise LastFMError(errors.INVALID_SESSION_KEY)
|
||||
call.user = session.user
|
||||
|
||||
missing = [p.name for p in method.params if p.required and not params.get(p.name)]
|
||||
if missing:
|
||||
raise LastFMError(
|
||||
errors.INVALID_PARAMETERS, f"Missing required parameter: {', '.join(missing)}"
|
||||
)
|
||||
return call
|
||||
|
||||
|
||||
@bp.route("/2.0/", methods=["GET", "POST"], strict_slashes=False)
|
||||
def dispatch() -> Response:
|
||||
params = _request_params()
|
||||
fmt = "json" if params.get("format", "").lower() == "json" else "xml"
|
||||
requested = (params.get("method") or "").lower()
|
||||
method = METHODS.get(requested)
|
||||
label = method.name if method else "unknown"
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
if method is None:
|
||||
raise LastFMError(errors.INVALID_METHOD)
|
||||
result = method.handler(_authenticate(method, params, fmt))
|
||||
if isinstance(result, Response):
|
||||
response = result
|
||||
else:
|
||||
el, force_list = result if isinstance(result, tuple) else (result, ())
|
||||
response = render(el, fmt, force_list=force_list)
|
||||
outcome = "ok"
|
||||
except LastFMError as err:
|
||||
db.session.rollback()
|
||||
response = render_error(err, fmt)
|
||||
outcome = "error"
|
||||
metrics.lastfm_errors_total.labels(lastfm_method=label, code=str(err.code)).inc()
|
||||
if reason := _AUTH_FAILURE_REASONS.get(err.code):
|
||||
metrics.auth_failures_total.labels(reason=reason).inc()
|
||||
|
||||
metrics.lastfm_requests_total.labels(lastfm_method=label, format=fmt, outcome=outcome).inc()
|
||||
metrics.lastfm_request_duration_seconds.labels(lastfm_method=label).observe(
|
||||
time.perf_counter() - start
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
from scrobbler.lastfm import methods # noqa: E402,F401 (register handlers)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Last.fm API error codes (https://www.last.fm/api/errorcodes)."""
|
||||
|
||||
INVALID_SERVICE = 2
|
||||
INVALID_METHOD = 3
|
||||
AUTHENTICATION_FAILED = 4
|
||||
INVALID_PARAMETERS = 6
|
||||
OPERATION_FAILED = 8
|
||||
INVALID_SESSION_KEY = 9
|
||||
INVALID_API_KEY = 10
|
||||
INVALID_SIGNATURE = 13
|
||||
UNAUTHORIZED_TOKEN = 14
|
||||
TOKEN_EXPIRED = 15
|
||||
RATE_LIMIT_EXCEEDED = 29
|
||||
|
||||
MESSAGES = {
|
||||
INVALID_SERVICE: "Invalid service - This service does not exist",
|
||||
INVALID_METHOD: "Invalid Method - No method with that name in this package",
|
||||
AUTHENTICATION_FAILED: (
|
||||
"Authentication Failed - You do not have permissions to access the service"
|
||||
),
|
||||
INVALID_PARAMETERS: "Invalid parameters - Your request is missing a required parameter",
|
||||
OPERATION_FAILED: "Operation failed - Something else went wrong",
|
||||
INVALID_SESSION_KEY: "Invalid session key - Please re-authenticate",
|
||||
INVALID_API_KEY: "Invalid API key - You must be granted a valid key by last.fm",
|
||||
INVALID_SIGNATURE: "Invalid method signature supplied",
|
||||
UNAUTHORIZED_TOKEN: "Unauthorized Token - This token has not been authorized",
|
||||
TOKEN_EXPIRED: "This token has expired",
|
||||
RATE_LIMIT_EXCEEDED: "Rate limit exceeded",
|
||||
}
|
||||
|
||||
HTTP_STATUS = {
|
||||
INVALID_SERVICE: 400,
|
||||
INVALID_METHOD: 400,
|
||||
INVALID_PARAMETERS: 400,
|
||||
AUTHENTICATION_FAILED: 403,
|
||||
INVALID_SESSION_KEY: 403,
|
||||
INVALID_API_KEY: 403,
|
||||
INVALID_SIGNATURE: 403,
|
||||
UNAUTHORIZED_TOKEN: 403,
|
||||
TOKEN_EXPIRED: 403,
|
||||
RATE_LIMIT_EXCEEDED: 429,
|
||||
OPERATION_FAILED: 500,
|
||||
}
|
||||
|
||||
|
||||
class LastFMError(Exception):
|
||||
def __init__(self, code: int, message: str | None = None):
|
||||
self.code = code
|
||||
self.message = message or MESSAGES.get(code, "Unknown error")
|
||||
super().__init__(f"{code}: {self.message}")
|
||||
|
||||
@property
|
||||
def http_status(self) -> int:
|
||||
return HTTP_STATUS.get(self.code, 400)
|
||||
@@ -0,0 +1 @@
|
||||
"""Importing this package registers every Last.fm method handler."""
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Registry of Last.fm API methods.
|
||||
|
||||
Each handler declares its name, parameters and auth requirements. The dispatcher
|
||||
enforces the requirements and the OpenAPI document is generated from the same
|
||||
entries, so the docs always list exactly the methods that exist.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from flask import Response
|
||||
|
||||
from scrobbler.lastfm.responses import El
|
||||
from scrobbler.models import ApiApp, User
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Param:
|
||||
name: str
|
||||
description: str
|
||||
required: bool = False
|
||||
example: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Call:
|
||||
"""Everything a handler needs about the current request."""
|
||||
|
||||
params: dict[str, str]
|
||||
api_app: ApiApp
|
||||
format: str
|
||||
user: User | None = None # set for methods that require a session key
|
||||
|
||||
def get(self, name: str, default: str | None = None) -> str | None:
|
||||
value = self.params.get(name)
|
||||
return value if value not in (None, "") else default
|
||||
|
||||
|
||||
Handler = Callable[[Call], El | tuple[El, tuple[str, ...]] | Response]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LastfmMethod:
|
||||
name: str
|
||||
handler: Handler
|
||||
summary: str
|
||||
signed: bool = False
|
||||
session: bool = False
|
||||
params: tuple[Param, ...] = ()
|
||||
example_xml: str | None = None
|
||||
example_json: dict | None = None
|
||||
notes: str = ""
|
||||
|
||||
|
||||
METHODS: dict[str, LastfmMethod] = {}
|
||||
|
||||
|
||||
def lastfm_method(
|
||||
name: str,
|
||||
*,
|
||||
summary: str,
|
||||
signed: bool = False,
|
||||
session: bool = False,
|
||||
params: tuple[Param, ...] = (),
|
||||
example_xml: str | None = None,
|
||||
example_json: dict | None = None,
|
||||
notes: str = "",
|
||||
):
|
||||
"""Register a handler. Handlers return an `El` tree, or `(El, force_list_tags)`."""
|
||||
|
||||
def decorator(handler: Handler) -> Handler:
|
||||
key = name.lower()
|
||||
if key in METHODS:
|
||||
raise ValueError(f"Last.fm method {name} registered twice")
|
||||
METHODS[key] = LastfmMethod(
|
||||
name=name,
|
||||
handler=handler,
|
||||
summary=summary,
|
||||
signed=signed,
|
||||
session=session,
|
||||
params=params,
|
||||
example_xml=example_xml,
|
||||
example_json=example_json,
|
||||
notes=notes,
|
||||
)
|
||||
return handler
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Render Last.fm responses as XML (the default) or Last.fm-style JSON.
|
||||
|
||||
Handlers build a small element tree with `El`; this module turns it into either
|
||||
`<lfm status="ok">...</lfm>` or the JSON shape Last.fm uses, where:
|
||||
* a text element with attributes becomes {"attr": ..., "#text": text}
|
||||
* a container element's attributes go under "@attr"
|
||||
* repeated child tags become a list
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
from flask import Response, jsonify
|
||||
|
||||
from scrobbler.lastfm.errors import LastFMError
|
||||
|
||||
|
||||
@dataclass
|
||||
class El:
|
||||
tag: str
|
||||
text: str | None = None
|
||||
attrs: dict[str, Any] = field(default_factory=dict)
|
||||
children: list["El"] = field(default_factory=list)
|
||||
|
||||
@classmethod
|
||||
def of(cls, tag: str, *children: "El", **attrs: Any) -> "El":
|
||||
return cls(tag, attrs=attrs, children=list(children))
|
||||
|
||||
@classmethod
|
||||
def text_el(cls, tag: str, text: Any, **attrs: Any) -> "El":
|
||||
return cls(tag, text="" if text is None else str(text), attrs=attrs)
|
||||
|
||||
|
||||
def _to_xml(el: El) -> ET.Element:
|
||||
node = ET.Element(el.tag, {k: str(v) for k, v in el.attrs.items()})
|
||||
if el.text is not None:
|
||||
node.text = el.text
|
||||
for child in el.children:
|
||||
node.append(_to_xml(child))
|
||||
return node
|
||||
|
||||
|
||||
def _to_json(el: El) -> Any:
|
||||
attrs = {k: str(v) for k, v in el.attrs.items()}
|
||||
if el.text is not None:
|
||||
return {**attrs, "#text": el.text} if attrs else el.text
|
||||
body: dict[str, Any] = {}
|
||||
for child in el.children:
|
||||
value = _to_json(child)
|
||||
if child.tag in body:
|
||||
existing = body[child.tag]
|
||||
if isinstance(existing, list):
|
||||
existing.append(value)
|
||||
else:
|
||||
body[child.tag] = [existing, value]
|
||||
else:
|
||||
body[child.tag] = value
|
||||
if attrs:
|
||||
body["@attr"] = attrs
|
||||
return body
|
||||
|
||||
|
||||
def render(el: El, fmt: str, *, force_list: tuple[str, ...] = ()) -> Response:
|
||||
"""Render a successful response. `force_list` names child tags that must be JSON
|
||||
lists even when there is only one (e.g. "track" in a recent-tracks page)."""
|
||||
if fmt == "json":
|
||||
body = _to_json(el)
|
||||
for tag in force_list:
|
||||
if isinstance(body, dict) and tag in body and not isinstance(body[tag], list):
|
||||
body[tag] = [body[tag]]
|
||||
return jsonify({el.tag: body})
|
||||
root = ET.Element("lfm", {"status": "ok"})
|
||||
root.append(_to_xml(el))
|
||||
return _xml_response(root, 200)
|
||||
|
||||
|
||||
def render_error(err: LastFMError, fmt: str) -> Response:
|
||||
if fmt == "json":
|
||||
response = jsonify({"error": err.code, "message": err.message})
|
||||
response.status_code = err.http_status
|
||||
return response
|
||||
root = ET.Element("lfm", {"status": "failed"})
|
||||
error = ET.SubElement(root, "error", {"code": str(err.code)})
|
||||
error.text = err.message
|
||||
return _xml_response(root, err.http_status)
|
||||
|
||||
|
||||
def _xml_response(root: ET.Element, status: int) -> Response:
|
||||
body = ET.tostring(root, encoding="unicode", xml_declaration=False)
|
||||
return Response(
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n' + body,
|
||||
status=status,
|
||||
mimetype="application/xml",
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Last.fm request signatures: https://www.last.fm/api/authspec#_8-signing-calls"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
from collections.abc import Mapping
|
||||
|
||||
UNSIGNED_PARAMS = frozenset({"format", "callback", "api_sig"})
|
||||
|
||||
|
||||
def sign(params: Mapping[str, str], secret: str) -> str:
|
||||
payload = "".join(
|
||||
f"{name}{params[name]}" for name in sorted(params) if name not in UNSIGNED_PARAMS
|
||||
)
|
||||
return hashlib.md5((payload + secret).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def is_valid(params: Mapping[str, str], secret: str) -> bool:
|
||||
supplied = params.get("api_sig", "")
|
||||
return bool(supplied) and hmac.compare_digest(sign(params, secret), supplied.lower())
|
||||
Reference in new issue
Block a user