App factory, data model, initial migration and HTTP metrics
- Flask app factory with env-driven config (.env loaded at import) - SQLAlchemy models: users, API apps, UI tokens, Last.fm auth tokens, sessions, scrobbles (deduplicated) and now-playing - Initial Alembic migration; CI checks migrations match the models - Prometheus metric definitions, per-endpoint RED hooks with bounded labels, and a standalone metrics server - docker compose Postgres with a test database; CI test job runs against a Postgres service container Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
606348800b
commit
98c8f2e824
21 files changed
+1777
-6
No files matched your search
@@ -1,3 +1,32 @@
|
||||
"""Self-hosted, Last.fm-compatible music scrobbling service."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
|
||||
def create_app(config_object=None):
|
||||
from flask import Flask
|
||||
|
||||
from scrobbler import models # noqa: F401 (register models with SQLAlchemy)
|
||||
from scrobbler.config import Config
|
||||
from scrobbler.extensions import db, migrate
|
||||
from scrobbler.metrics import http as http_metrics
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config_object or Config)
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db, directory=_migrations_dir())
|
||||
http_metrics.init_app(app)
|
||||
|
||||
if app.config["START_METRICS_SERVER"]:
|
||||
from scrobbler.metrics.server import start_metrics_server
|
||||
|
||||
start_metrics_server(app.config["METRICS_PORT"])
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def _migrations_dir() -> str:
|
||||
from pathlib import Path
|
||||
|
||||
return str(Path(__file__).resolve().parent / "migrations")
|
||||
@@ -0,0 +1,42 @@
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Settings are read at import time, so .env must be loaded first.
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def _csv(value: str | None) -> list[str]:
|
||||
return [item.strip() for item in (value or "").split(",") if item.strip()]
|
||||
|
||||
|
||||
class Config:
|
||||
SECRET_KEY = os.environ.get("SECRET_KEY", "dev-insecure-secret")
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get(
|
||||
"DATABASE_URL", "postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler"
|
||||
)
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {"pool_pre_ping": True}
|
||||
|
||||
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
|
||||
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
|
||||
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
|
||||
# server is started by gunicorn.conf.py instead, so this stays off there.
|
||||
START_METRICS_SERVER = os.environ.get("START_METRICS_SERVER", "0") == "1"
|
||||
|
||||
# Last.fm behaviour
|
||||
AUTH_TOKEN_TTL_SECONDS = 60 * 60
|
||||
UI_TOKEN_TTL_DAYS = 30
|
||||
SCROBBLE_MAX_AGE_DAYS = 14
|
||||
SCROBBLE_MAX_FUTURE_SECONDS = 5 * 60
|
||||
NOW_PLAYING_DEFAULT_SECONDS = 10 * 60
|
||||
|
||||
|
||||
class TestConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get(
|
||||
"TEST_DATABASE_URL",
|
||||
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
|
||||
)
|
||||
START_METRICS_SERVER = False
|
||||
@@ -0,0 +1,11 @@
|
||||
from flask_migrate import Migrate
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
db = SQLAlchemy(model_class=Base)
|
||||
migrate = Migrate()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""All Prometheus metrics for the service, defined in one place.
|
||||
|
||||
Labels are deliberately low-cardinality: Flask endpoint names (never raw paths),
|
||||
Last.fm method names from the handler registry, and small fixed enums. Never add
|
||||
user, api_key or track labels.
|
||||
"""
|
||||
|
||||
import platform
|
||||
|
||||
from prometheus_client import Counter, Gauge, Histogram
|
||||
|
||||
from scrobbler import __version__
|
||||
|
||||
LATENCY_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
|
||||
|
||||
# HTTP (RED)
|
||||
http_requests_total = Counter(
|
||||
"scrobbler_http_requests_total",
|
||||
"HTTP requests handled",
|
||||
["endpoint", "http_method", "status"],
|
||||
)
|
||||
http_request_duration_seconds = Histogram(
|
||||
"scrobbler_http_request_duration_seconds",
|
||||
"HTTP request latency",
|
||||
["endpoint", "http_method"],
|
||||
buckets=LATENCY_BUCKETS,
|
||||
)
|
||||
http_requests_in_progress = Gauge(
|
||||
"scrobbler_http_requests_in_progress",
|
||||
"HTTP requests currently being handled",
|
||||
["endpoint"],
|
||||
multiprocess_mode="livesum",
|
||||
)
|
||||
|
||||
# Last.fm API
|
||||
lastfm_requests_total = Counter(
|
||||
"scrobbler_lastfm_requests_total",
|
||||
"Last.fm API calls",
|
||||
["lastfm_method", "format", "outcome"],
|
||||
)
|
||||
lastfm_request_duration_seconds = Histogram(
|
||||
"scrobbler_lastfm_request_duration_seconds",
|
||||
"Last.fm API call latency",
|
||||
["lastfm_method"],
|
||||
buckets=LATENCY_BUCKETS,
|
||||
)
|
||||
lastfm_errors_total = Counter(
|
||||
"scrobbler_lastfm_errors_total",
|
||||
"Last.fm API errors by error code",
|
||||
["lastfm_method", "code"],
|
||||
)
|
||||
|
||||
# Scrobbling
|
||||
scrobbles_total = Counter(
|
||||
"scrobbler_scrobbles_total",
|
||||
"Scrobbles submitted, by result",
|
||||
["result"],
|
||||
)
|
||||
scrobbles_ignored_total = Counter(
|
||||
"scrobbler_scrobbles_ignored_total",
|
||||
"Scrobbles ignored, by Last.fm ignored-message code",
|
||||
["reason"],
|
||||
)
|
||||
scrobble_batch_size = Histogram(
|
||||
"scrobbler_scrobble_batch_size",
|
||||
"Tracks per track.scrobble call",
|
||||
buckets=(1, 2, 5, 10, 25, 50),
|
||||
)
|
||||
scrobble_lag_seconds = Histogram(
|
||||
"scrobbler_scrobble_lag_seconds",
|
||||
"Delay between a track being played and its scrobble arriving",
|
||||
buckets=(10, 60, 300, 900, 3600, 6 * 3600, 86400, 7 * 86400, 14 * 86400),
|
||||
)
|
||||
now_playing_updates_total = Counter(
|
||||
"scrobbler_now_playing_updates_total",
|
||||
"track.updateNowPlaying calls that were stored",
|
||||
)
|
||||
|
||||
# Auth
|
||||
auth_sessions_created_total = Counter(
|
||||
"scrobbler_auth_sessions_created_total",
|
||||
"Last.fm session keys issued",
|
||||
["flow"],
|
||||
)
|
||||
auth_failures_total = Counter(
|
||||
"scrobbler_auth_failures_total",
|
||||
"Authentication failures",
|
||||
["reason"],
|
||||
)
|
||||
ui_logins_total = Counter(
|
||||
"scrobbler_ui_logins_total",
|
||||
"Web UI login attempts",
|
||||
["result"],
|
||||
)
|
||||
registrations_total = Counter(
|
||||
"scrobbler_registrations_total",
|
||||
"User registrations",
|
||||
)
|
||||
|
||||
# Database
|
||||
db_query_duration_seconds = Histogram(
|
||||
"scrobbler_db_query_duration_seconds",
|
||||
"Database statement latency",
|
||||
["operation"],
|
||||
buckets=(0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5),
|
||||
)
|
||||
db_pool_connections = Gauge(
|
||||
"scrobbler_db_pool_connections",
|
||||
"Database connection pool state",
|
||||
["state"],
|
||||
multiprocess_mode="livesum",
|
||||
)
|
||||
|
||||
build_info = Gauge(
|
||||
"scrobbler_build_info",
|
||||
"Build information",
|
||||
["version", "python_version"],
|
||||
multiprocess_mode="max",
|
||||
)
|
||||
build_info.labels(version=__version__, python_version=platform.python_version()).set(1)
|
||||
@@ -0,0 +1,36 @@
|
||||
import time
|
||||
|
||||
from flask import Flask, g, request
|
||||
|
||||
from scrobbler import metrics
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
return request.url_rule.endpoint if request.url_rule else "unmatched"
|
||||
|
||||
|
||||
def init_app(app: Flask) -> None:
|
||||
@app.before_request
|
||||
def _start_timer():
|
||||
g._metrics_endpoint = _endpoint()
|
||||
g._metrics_start = time.perf_counter()
|
||||
metrics.http_requests_in_progress.labels(endpoint=g._metrics_endpoint).inc()
|
||||
|
||||
@app.after_request
|
||||
def _record(response):
|
||||
endpoint = g.get("_metrics_endpoint", _endpoint())
|
||||
start = g.get("_metrics_start")
|
||||
if start is not None:
|
||||
metrics.http_request_duration_seconds.labels(
|
||||
endpoint=endpoint, http_method=request.method
|
||||
).observe(time.perf_counter() - start)
|
||||
metrics.http_requests_total.labels(
|
||||
endpoint=endpoint, http_method=request.method, status=str(response.status_code)
|
||||
).inc()
|
||||
return response
|
||||
|
||||
@app.teardown_request
|
||||
def _finish(_exc):
|
||||
endpoint = g.pop("_metrics_endpoint", None)
|
||||
if endpoint is not None:
|
||||
metrics.http_requests_in_progress.labels(endpoint=endpoint).dec()
|
||||
@@ -0,0 +1,25 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from prometheus_client import REGISTRY, CollectorRegistry, multiprocess, start_http_server
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def metrics_registry() -> CollectorRegistry:
|
||||
"""Registry to expose: aggregated across workers when running under gunicorn."""
|
||||
if os.environ.get("PROMETHEUS_MULTIPROC_DIR"):
|
||||
registry = CollectorRegistry()
|
||||
multiprocess.MultiProcessCollector(registry)
|
||||
return registry
|
||||
return REGISTRY
|
||||
|
||||
|
||||
def start_metrics_server(port: int, registry: CollectorRegistry | None = None) -> bool:
|
||||
try:
|
||||
start_http_server(port, registry=registry or metrics_registry())
|
||||
except OSError as exc: # e.g. the dev-server reloader's second process
|
||||
log.warning("metrics server not started on port %s: %s", port, exc)
|
||||
return False
|
||||
log.info("metrics server listening on :%s/metrics", port)
|
||||
return True
|
||||
@@ -0,0 +1 @@
|
||||
Single-database configuration for Flask.
|
||||
@@ -0,0 +1,50 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic,flask_migrate
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[logger_flask_migrate]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = flask_migrate
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,108 @@
|
||||
import logging
|
||||
from logging.config import fileConfig
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from alembic import context
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
logger = logging.getLogger('alembic.env')
|
||||
|
||||
|
||||
def get_engine():
|
||||
return current_app.extensions['migrate'].db.engine
|
||||
|
||||
|
||||
def get_engine_url():
|
||||
try:
|
||||
return get_engine().url.render_as_string(hide_password=False).replace(
|
||||
'%', '%%')
|
||||
except AttributeError:
|
||||
return str(get_engine().url).replace('%', '%%')
|
||||
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
config.set_main_option('sqlalchemy.url', get_engine_url())
|
||||
target_db = current_app.extensions['migrate'].db
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def get_metadata():
|
||||
if hasattr(target_db, 'metadatas'):
|
||||
return target_db.metadatas[None]
|
||||
return target_db.metadata
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url, target_metadata=get_metadata(), literal_binds=True
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
|
||||
# this callback is used to prevent an auto-migration from being generated
|
||||
# when there are no changes to the schema
|
||||
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
|
||||
def process_revision_directives(context, revision, directives):
|
||||
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||
script = directives[0]
|
||||
if script.upgrade_ops.is_empty():
|
||||
directives[:] = []
|
||||
logger.info('No changes in schema detected.')
|
||||
|
||||
conf_args = current_app.extensions['migrate'].configure_args
|
||||
if conf_args.get("process_revision_directives") is None:
|
||||
conf_args["process_revision_directives"] = process_revision_directives
|
||||
|
||||
connectable = get_engine()
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=get_metadata(),
|
||||
**conf_args
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,145 @@
|
||||
"""initial schema
|
||||
|
||||
Revision ID: d6113d27cce6
|
||||
Revises:
|
||||
Create Date: 2026-09-25 13:54:01.877141
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd6113d27cce6'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=64), nullable=False),
|
||||
sa.Column('email', sa.String(length=255), nullable=False),
|
||||
sa.Column('password_hash', sa.String(length=255), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||
batch_op.create_index('uq_users_username_lower', [sa.literal_column('lower(username)')], unique=True)
|
||||
|
||||
op.create_table('api_apps',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('api_key', sa.String(length=32), nullable=False),
|
||||
sa.Column('shared_secret', sa.String(length=32), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('owner_id', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('api_key')
|
||||
)
|
||||
with op.batch_alter_table('api_apps', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_api_apps_owner_id'), ['owner_id'], unique=False)
|
||||
|
||||
op.create_table('now_playing',
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('artist', sa.Text(), nullable=False),
|
||||
sa.Column('track', sa.Text(), nullable=False),
|
||||
sa.Column('album', sa.Text(), nullable=True),
|
||||
sa.Column('album_artist', sa.Text(), nullable=True),
|
||||
sa.Column('duration', sa.Integer(), nullable=True),
|
||||
sa.Column('started_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('user_id')
|
||||
)
|
||||
op.create_table('ui_tokens',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('token_hash', sa.String(length=64), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('last_used_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('token_hash')
|
||||
)
|
||||
with op.batch_alter_table('ui_tokens', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_ui_tokens_user_id'), ['user_id'], unique=False)
|
||||
|
||||
op.create_table('auth_tokens',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('token', sa.String(length=32), nullable=False),
|
||||
sa.Column('api_app_id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['api_app_id'], ['api_apps.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('token')
|
||||
)
|
||||
op.create_table('scrobbles',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('artist', sa.Text(), nullable=False),
|
||||
sa.Column('track', sa.Text(), nullable=False),
|
||||
sa.Column('album', sa.Text(), nullable=True),
|
||||
sa.Column('album_artist', sa.Text(), nullable=True),
|
||||
sa.Column('track_number', sa.Integer(), nullable=True),
|
||||
sa.Column('duration', sa.Integer(), nullable=True),
|
||||
sa.Column('mbid', sa.String(length=36), nullable=True),
|
||||
sa.Column('played_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('submitted_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('api_app_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['api_app_id'], ['api_apps.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('user_id', 'played_at', 'artist', 'track', name='uq_scrobbles_dedupe')
|
||||
)
|
||||
with op.batch_alter_table('scrobbles', schema=None) as batch_op:
|
||||
batch_op.create_index('ix_scrobbles_user_played_at', ['user_id', sa.literal_column('played_at DESC')], unique=False)
|
||||
|
||||
op.create_table('sessions',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('session_key', sa.String(length=32), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('api_app_id', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['api_app_id'], ['api_apps.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('session_key')
|
||||
)
|
||||
with op.batch_alter_table('sessions', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_sessions_user_id'), ['user_id'], unique=False)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('sessions', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_sessions_user_id'))
|
||||
|
||||
op.drop_table('sessions')
|
||||
with op.batch_alter_table('scrobbles', schema=None) as batch_op:
|
||||
batch_op.drop_index('ix_scrobbles_user_played_at')
|
||||
|
||||
op.drop_table('scrobbles')
|
||||
op.drop_table('auth_tokens')
|
||||
with op.batch_alter_table('ui_tokens', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_ui_tokens_user_id'))
|
||||
|
||||
op.drop_table('ui_tokens')
|
||||
op.drop_table('now_playing')
|
||||
with op.batch_alter_table('api_apps', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_api_apps_owner_id'))
|
||||
|
||||
op.drop_table('api_apps')
|
||||
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||
batch_op.drop_index('uq_users_username_lower')
|
||||
|
||||
op.drop_table('users')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,128 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from scrobbler.extensions import db
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
class User(db.Model):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(64))
|
||||
email: Mapped[str] = mapped_column(String(255))
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
__table_args__ = (Index("uq_users_username_lower", func.lower(username), unique=True),)
|
||||
|
||||
|
||||
class ApiApp(db.Model):
|
||||
"""A client application; scrobblers authenticate with its key and secret."""
|
||||
|
||||
__tablename__ = "api_apps"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
api_key: Mapped[str] = mapped_column(String(32), unique=True)
|
||||
shared_secret: Mapped[str] = mapped_column(String(32))
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
owner_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
owner: Mapped[User] = relationship()
|
||||
|
||||
|
||||
class UiToken(db.Model):
|
||||
"""Bearer token for the web UI. Only the sha256 of the token is stored."""
|
||||
|
||||
__tablename__ = "ui_tokens"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
last_used_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
user: Mapped[User] = relationship()
|
||||
|
||||
|
||||
class AuthToken(db.Model):
|
||||
"""Last.fm desktop-auth token: issued unapproved, approved by a user in the UI."""
|
||||
|
||||
__tablename__ = "auth_tokens"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
token: Mapped[str] = mapped_column(String(32), unique=True)
|
||||
api_app_id: Mapped[int] = mapped_column(ForeignKey("api_apps.id", ondelete="CASCADE"))
|
||||
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
api_app: Mapped[ApiApp] = relationship()
|
||||
user: Mapped[User | None] = relationship()
|
||||
|
||||
|
||||
class Session(db.Model):
|
||||
"""Last.fm session key granting a client app access to a user's account."""
|
||||
|
||||
__tablename__ = "sessions"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_key: Mapped[str] = mapped_column(String(32), unique=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
api_app_id: Mapped[int] = mapped_column(ForeignKey("api_apps.id", ondelete="CASCADE"))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
user: Mapped[User] = relationship()
|
||||
api_app: Mapped[ApiApp] = relationship()
|
||||
|
||||
|
||||
class Scrobble(db.Model):
|
||||
__tablename__ = "scrobbles"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
artist: Mapped[str] = mapped_column(Text)
|
||||
track: Mapped[str] = mapped_column(Text)
|
||||
album: Mapped[str | None] = mapped_column(Text)
|
||||
album_artist: Mapped[str | None] = mapped_column(Text)
|
||||
track_number: Mapped[int | None] = mapped_column(Integer)
|
||||
duration: Mapped[int | None] = mapped_column(Integer)
|
||||
mbid: Mapped[str | None] = mapped_column(String(36))
|
||||
played_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
submitted_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
api_app_id: Mapped[int | None] = mapped_column(ForeignKey("api_apps.id", ondelete="SET NULL"))
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_id", "played_at", "artist", "track", name="uq_scrobbles_dedupe"),
|
||||
Index("ix_scrobbles_user_played_at", "user_id", played_at.desc()),
|
||||
)
|
||||
|
||||
|
||||
class NowPlaying(db.Model):
|
||||
__tablename__ = "now_playing"
|
||||
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
artist: Mapped[str] = mapped_column(Text)
|
||||
track: Mapped[str] = mapped_column(Text)
|
||||
album: Mapped[str | None] = mapped_column(Text)
|
||||
album_artist: Mapped[str | None] = mapped_column(Text)
|
||||
duration: Mapped[int | None] = mapped_column(Integer)
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
Reference in new issue
Block a user