History imports: parsers, import jobs and the import worker
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 41s
CI / python-package (push) Skipped
CI / assets (push) Successful in 8s
CI / images (push) Successful in 28s
CI / notify (push) Successful in 7s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 41s
CI / python-package (push) Skipped
CI / assets (push) Successful in 8s
CI / images (push) Successful in 28s
CI / notify (push) Successful in 7s
- Import jobs (import_jobs table): uploaded exports stored gzipped, processed by `flask imports worker`, which claims jobs with SKIP LOCKED, inserts in chunks with progress, supports cancelling and re-queues jobs whose worker died - CSV: lastfm-to-csv (no header) or any header-labelled CSV/TSV with comma, semicolon or tab delimiters; several date formats and Unix seconds/milliseconds - JSON: pages of user.getRecentTracks (e.g. lastfm.ghan.nl), a single recenttracks response, or a flat list; gzipped files accepted - Last.fm API pull (only when LASTFM_API_KEY is set): pages through user.getRecentTracks up to the job's creation time, rate limited, with retries and resume - Imports keep plays older than 14 days, skip empty/future ones and dedupe against existing history - Import metrics and pending/running job gauges Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
e29abe05dd
commit
6fc9d91fa2
9 files changed
+1004
-1
No files matched your search
@@ -37,6 +37,10 @@ def create_app(config_object=None):
|
||||
max_age=600,
|
||||
)
|
||||
|
||||
from scrobbler.cli import imports_cli
|
||||
|
||||
app.cli.add_command(imports_cli)
|
||||
|
||||
from scrobbler.metrics import db as db_metrics
|
||||
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import logging
|
||||
|
||||
import click
|
||||
from flask import current_app
|
||||
from flask.cli import AppGroup
|
||||
|
||||
imports_cli = AppGroup("imports", help="History imports.")
|
||||
|
||||
|
||||
@imports_cli.command("worker")
|
||||
@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.")
|
||||
@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.")
|
||||
@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.")
|
||||
def worker(once: bool, poll: float, metrics: bool) -> None:
|
||||
"""Process import jobs: uploaded Last.fm exports and pulls from Last.fm."""
|
||||
from scrobbler.services.imports import run_worker
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
if metrics:
|
||||
from scrobbler.metrics.server import start_metrics_server
|
||||
|
||||
start_metrics_server(current_app.config["IMPORT_WORKER_METRICS_PORT"])
|
||||
run_worker(poll_seconds=poll, once=once)
|
||||
@@ -49,6 +49,15 @@ class Config:
|
||||
},
|
||||
}
|
||||
|
||||
# History imports. Pulling from Last.fm is offered only when an API key is set
|
||||
# (get one at https://www.last.fm/api/account/create).
|
||||
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
|
||||
LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/")
|
||||
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
|
||||
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024)))
|
||||
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
|
||||
IMPORT_WORKER_METRICS_PORT = int(os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101"))
|
||||
|
||||
# Last.fm behaviour
|
||||
AUTH_TOKEN_TTL_SECONDS = 60 * 60
|
||||
UI_TOKEN_TTL_DAYS = 30
|
||||
|
||||
@@ -97,6 +97,24 @@ registrations_total = Counter(
|
||||
"User registrations",
|
||||
)
|
||||
|
||||
# History imports (counted by the import worker)
|
||||
imports_total = Counter(
|
||||
"scrobbler_imports_total",
|
||||
"Import jobs by source and lifecycle event (created, completed, failed, cancelled)",
|
||||
["source", "status"],
|
||||
)
|
||||
imported_scrobbles_total = Counter(
|
||||
"scrobbler_imported_scrobbles_total",
|
||||
"Rows read by imports, by outcome",
|
||||
["source", "result"],
|
||||
)
|
||||
import_duration_seconds = Histogram(
|
||||
"scrobbler_import_duration_seconds",
|
||||
"Time to process an import job",
|
||||
["source"],
|
||||
buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200),
|
||||
)
|
||||
|
||||
# Database
|
||||
db_query_duration_seconds = Histogram(
|
||||
"scrobbler_db_query_duration_seconds",
|
||||
@@ -124,4 +142,5 @@ COLLECTED = {
|
||||
"users": "scrobbler_users",
|
||||
"active_users": "scrobbler_active_users",
|
||||
"now_playing_active": "scrobbler_now_playing_active",
|
||||
"import_jobs": "scrobbler_import_jobs",
|
||||
}
|
||||
@@ -38,7 +38,20 @@ class DatabaseStatsCollector(Collector):
|
||||
now_playing = conn.execute(
|
||||
text("SELECT count(*) FROM now_playing WHERE expires_at > now()")
|
||||
).scalar_one()
|
||||
return {"users": users, "active": active, "now_playing": now_playing}
|
||||
import_jobs = dict(
|
||||
conn.execute(
|
||||
text(
|
||||
"SELECT status, count(*) FROM import_jobs "
|
||||
"WHERE status IN ('pending', 'running') GROUP BY status"
|
||||
)
|
||||
).all()
|
||||
)
|
||||
return {
|
||||
"users": users,
|
||||
"active": active,
|
||||
"now_playing": now_playing,
|
||||
"import_jobs": {s: import_jobs.get(s, 0) for s in ("pending", "running")},
|
||||
}
|
||||
|
||||
def values(self) -> dict | None:
|
||||
with self._lock:
|
||||
@@ -66,3 +79,9 @@ class DatabaseStatsCollector(Collector):
|
||||
"Users currently playing a track",
|
||||
value=values["now_playing"],
|
||||
)
|
||||
jobs = GaugeMetricFamily(
|
||||
COLLECTED["import_jobs"], "Import jobs waiting or in progress", labels=["status"]
|
||||
)
|
||||
for status, count in values["import_jobs"].items():
|
||||
jobs.add_metric([status], count)
|
||||
yield jobs
|
||||
@@ -0,0 +1,58 @@
|
||||
"""import jobs
|
||||
|
||||
Revision ID: e7fb730bac15
|
||||
Revises: d6113d27cce6
|
||||
Create Date: 2026-09-25 14:59:23.375055
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e7fb730bac15'
|
||||
down_revision = 'd6113d27cce6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('import_jobs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('source', sa.String(length=16), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=False),
|
||||
sa.Column('filename', sa.String(length=255), nullable=True),
|
||||
sa.Column('lastfm_username', sa.String(length=64), nullable=True),
|
||||
sa.Column('payload', sa.LargeBinary(), nullable=True),
|
||||
sa.Column('total', sa.Integer(), nullable=True),
|
||||
sa.Column('processed', sa.Integer(), nullable=False),
|
||||
sa.Column('imported', sa.Integer(), nullable=False),
|
||||
sa.Column('duplicates', sa.Integer(), nullable=False),
|
||||
sa.Column('skipped', sa.Integer(), nullable=False),
|
||||
sa.Column('error', sa.Text(), nullable=True),
|
||||
sa.Column('next_page', sa.Integer(), nullable=True),
|
||||
sa.Column('pull_until', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('started_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('finished_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('heartbeat_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('import_jobs', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_import_jobs_status'), ['status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_import_jobs_user_id'), ['user_id'], unique=False)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('import_jobs', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_import_jobs_user_id'))
|
||||
batch_op.drop_index(batch_op.f('ix_import_jobs_status'))
|
||||
|
||||
op.drop_table('import_jobs')
|
||||
# ### end Alembic commands ###
|
||||
@@ -5,6 +5,7 @@ from sqlalchemy import (
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
LargeBinary,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
@@ -126,3 +127,33 @@ class NowPlaying(db.Model):
|
||||
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))
|
||||
|
||||
|
||||
class ImportJob(db.Model):
|
||||
"""A history import: an uploaded export file, or a pull from the Last.fm API.
|
||||
|
||||
Created by the API and processed by the import worker (`flask imports worker`).
|
||||
"""
|
||||
|
||||
__tablename__ = "import_jobs"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
source: Mapped[str] = mapped_column(String(16)) # csv, json or lastfm
|
||||
status: Mapped[str] = mapped_column(String(16), default="pending", index=True)
|
||||
filename: Mapped[str | None] = mapped_column(String(255))
|
||||
lastfm_username: Mapped[str | None] = mapped_column(String(64))
|
||||
payload: Mapped[bytes | None] = mapped_column(LargeBinary, deferred=True) # gzipped upload
|
||||
total: Mapped[int | None] = mapped_column(Integer) # rows or tracks, once known
|
||||
processed: Mapped[int] = mapped_column(Integer, default=0)
|
||||
imported: Mapped[int] = mapped_column(Integer, default=0)
|
||||
duplicates: Mapped[int] = mapped_column(Integer, default=0)
|
||||
skipped: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error: Mapped[str | None] = mapped_column(Text)
|
||||
# Last.fm pulls resume from here, and only fetch scrobbles before pull_until.
|
||||
next_page: Mapped[int | None] = mapped_column(Integer)
|
||||
pull_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
heartbeat_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
@@ -0,0 +1,569 @@
|
||||
"""Importing listening history: Last.fm export files and pulls from the Last.fm API.
|
||||
|
||||
Jobs are created by the API and processed by the import worker (`flask imports
|
||||
worker`), because large histories take longer than a request should.
|
||||
|
||||
Supported inputs:
|
||||
* CSV from lastfm-to-csv (no header: artist, album, track, date) or any CSV/TSV
|
||||
with a header naming the columns (artist, album, track/name/title, and one of
|
||||
uts/timestamp/date/utc_time). Comma, semicolon and tab delimiters are detected.
|
||||
* JSON: an array of user.getRecentTracks pages (e.g. lastfm.ghan.nl exports),
|
||||
a single {"recenttracks": ...} response, or a flat list of track objects.
|
||||
* The Last.fm API: user.getRecentTracks for a Last.fm username, paged, rate
|
||||
limited and resumable.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from collections.abc import Iterable, Iterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from scrobbler import metrics
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.models import ImportJob, Scrobble, User
|
||||
from scrobbler.services.scrobbles import MAX_TEXT, TrackInput
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SOURCES = ("csv", "json", "lastfm")
|
||||
ACTIVE = ("pending", "running")
|
||||
CHUNK = 1000
|
||||
GZIP_MAGIC = b"\x1f\x8b"
|
||||
|
||||
|
||||
class ImportFailed(ValueError):
|
||||
"""An import can't be started or its input can't be read."""
|
||||
|
||||
def __init__(self, code: str, message: str):
|
||||
self.code, self.message = code, message
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
# --- Parsing -----------------------------------------------------------------------
|
||||
|
||||
_DATE_FORMATS = (
|
||||
"%d %b %Y %H:%M", # lastfm-to-csv: "31 Jan 2021 14:05"
|
||||
"%d %b %Y, %H:%M", # Last.fm API "#text": "31 Jan 2021, 14:05"
|
||||
"%Y-%m-%d %H:%M:%S",
|
||||
"%Y-%m-%dT%H:%M:%S",
|
||||
"%Y-%m-%dT%H:%M:%SZ",
|
||||
"%Y-%m-%d %H:%M",
|
||||
)
|
||||
|
||||
|
||||
def parse_time(value: str | int | None) -> int | None:
|
||||
"""Unix seconds from a Unix time (seconds or milliseconds) or a UTC date string."""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
if text.isdigit():
|
||||
number = int(text)
|
||||
return number // 1000 if number > 10**11 else number
|
||||
try:
|
||||
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
return int((parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)).timestamp())
|
||||
except ValueError:
|
||||
pass
|
||||
for fmt in _DATE_FORMATS:
|
||||
try:
|
||||
return int(datetime.strptime(text, fmt).replace(tzinfo=UTC).timestamp())
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _clean(value) -> str | None:
|
||||
if isinstance(value, dict): # {"#text": "...", "mbid": "..."} or {"name": "..."}
|
||||
value = value.get("#text", value.get("name"))
|
||||
text = ("" if value is None else str(value)).strip()
|
||||
return text[:MAX_TEXT] or None
|
||||
|
||||
|
||||
def _mbid(value) -> str | None:
|
||||
mbid = _clean(value)
|
||||
return mbid if mbid and len(mbid) <= 36 else None
|
||||
|
||||
|
||||
_HEADER_ALIASES = {
|
||||
"artist": {"artist", "artist_name", "artistname"},
|
||||
"album": {"album", "album_name", "albumname"},
|
||||
"track": {"track", "track_name", "trackname", "name", "title", "song"},
|
||||
"time": {"uts", "timestamp", "date", "utc_time", "time", "played_at", "datetime", "date#"},
|
||||
"album_artist": {"album_artist", "albumartist"},
|
||||
"mbid": {"track_mbid", "mbid"},
|
||||
}
|
||||
|
||||
|
||||
def _header_map(row: list[str]) -> dict[str, int] | None:
|
||||
mapping: dict[str, int] = {}
|
||||
for index, cell in enumerate(row):
|
||||
key = cell.strip().lower().replace(" ", "_")
|
||||
for field, aliases in _HEADER_ALIASES.items():
|
||||
if key in aliases and field not in mapping:
|
||||
mapping[field] = index
|
||||
return mapping if {"artist", "track", "time"} <= mapping.keys() else None
|
||||
|
||||
|
||||
def parse_csv(text: str) -> Iterator[TrackInput | None]:
|
||||
"""Yields a TrackInput per row, or None for rows that can't be used."""
|
||||
sample = text[:4096]
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
|
||||
except csv.Error:
|
||||
dialect = csv.excel
|
||||
reader = csv.reader(io.StringIO(text), dialect)
|
||||
first = next(reader, None)
|
||||
if first is None:
|
||||
return
|
||||
columns = _header_map(first)
|
||||
rows: Iterable[list[str]] = reader
|
||||
if columns is None:
|
||||
# lastfm-to-csv has no header: artist, album, track, date
|
||||
columns = {"artist": 0, "album": 1, "track": 2, "time": 3}
|
||||
rows = _prepend(first, reader)
|
||||
|
||||
def cell(row: list[str], field: str) -> str | None:
|
||||
index = columns.get(field)
|
||||
return row[index] if index is not None and index < len(row) else None
|
||||
|
||||
for row in rows:
|
||||
if not any(c.strip() for c in row):
|
||||
continue
|
||||
timestamp = parse_time(cell(row, "time"))
|
||||
if timestamp is None:
|
||||
yield None
|
||||
continue
|
||||
yield TrackInput(
|
||||
artist=_clean(cell(row, "artist")) or "",
|
||||
track=_clean(cell(row, "track")) or "",
|
||||
album=_clean(cell(row, "album")),
|
||||
album_artist=_clean(cell(row, "album_artist")),
|
||||
mbid=_mbid(cell(row, "mbid")),
|
||||
timestamp=timestamp,
|
||||
)
|
||||
|
||||
|
||||
def _prepend(first, rest):
|
||||
yield first
|
||||
yield from rest
|
||||
|
||||
|
||||
def _track_from_json(track: dict) -> TrackInput | None:
|
||||
"""A track object as found in user.getRecentTracks (compact or extended)."""
|
||||
if not isinstance(track, dict):
|
||||
return None
|
||||
if (track.get("@attr") or {}).get("nowplaying") == "true":
|
||||
return None # no timestamp: it's still playing
|
||||
date = track.get("date")
|
||||
timestamp = parse_time(
|
||||
date.get("uts") or date.get("#text")
|
||||
if isinstance(date, dict)
|
||||
else date or track.get("uts") or track.get("timestamp")
|
||||
)
|
||||
if timestamp is None:
|
||||
return None
|
||||
return TrackInput(
|
||||
artist=_clean(track.get("artist")) or "",
|
||||
track=_clean(track.get("name") or track.get("track") or track.get("title")) or "",
|
||||
album=_clean(track.get("album")),
|
||||
mbid=_mbid(track.get("mbid")),
|
||||
timestamp=timestamp,
|
||||
)
|
||||
|
||||
|
||||
def _json_tracks(data) -> Iterator[dict]:
|
||||
if isinstance(data, dict):
|
||||
if "recenttracks" in data:
|
||||
data = data["recenttracks"]
|
||||
if "track" in data:
|
||||
tracks = data["track"]
|
||||
yield from tracks if isinstance(tracks, list) else [tracks]
|
||||
return
|
||||
raise ImportFailed("unrecognised_json", "The JSON doesn't look like a Last.fm export.")
|
||||
if isinstance(data, list):
|
||||
for item in data:
|
||||
if isinstance(item, dict) and (
|
||||
"recenttracks" in item or isinstance(item.get("track"), list | dict)
|
||||
):
|
||||
yield from _json_tracks(item) # a page of tracks
|
||||
else:
|
||||
yield item # a flat list of tracks
|
||||
return
|
||||
raise ImportFailed("unrecognised_json", "The JSON doesn't look like a Last.fm export.")
|
||||
|
||||
|
||||
def parse_json(text: str) -> Iterator[TrackInput | None]:
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError as err:
|
||||
raise ImportFailed("invalid_json", f"The file isn't valid JSON: {err.msg}") from err
|
||||
for track in _json_tracks(data):
|
||||
yield _track_from_json(track)
|
||||
|
||||
|
||||
def detect_format(filename: str | None, raw: bytes) -> str:
|
||||
name = (filename or "").lower().removesuffix(".gz")
|
||||
if name.endswith(".json"):
|
||||
return "json"
|
||||
if name.endswith((".csv", ".tsv", ".txt")):
|
||||
return "csv"
|
||||
if raw[:2] == GZIP_MAGIC:
|
||||
with gzip.open(io.BytesIO(raw)) as unzipped:
|
||||
raw = unzipped.read(64)
|
||||
return "json" if raw.lstrip()[:1] in (b"[", b"{") else "csv"
|
||||
|
||||
|
||||
def _decode(raw: bytes) -> str:
|
||||
if raw[:2] == GZIP_MAGIC: # a gzipped export
|
||||
raw = gzip.decompress(raw)
|
||||
for encoding in ("utf-8-sig", "utf-16"):
|
||||
try:
|
||||
return raw.decode(encoding)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return raw.decode("latin-1")
|
||||
|
||||
|
||||
# --- Jobs ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def lastfm_pull_available() -> bool:
|
||||
return bool(current_app.config.get("LASTFM_API_KEY"))
|
||||
|
||||
|
||||
def create_file_import(
|
||||
user: User, filename: str | None, raw: bytes, fmt: str = "auto"
|
||||
) -> ImportJob:
|
||||
if not raw.strip():
|
||||
raise ImportFailed("empty_file", "The file is empty.")
|
||||
source = detect_format(filename, raw) if fmt == "auto" else fmt
|
||||
if source not in ("csv", "json"):
|
||||
raise ImportFailed("unsupported_format", "Upload a CSV or JSON export.")
|
||||
job = ImportJob(
|
||||
user_id=user.id,
|
||||
source=source,
|
||||
filename=(filename or "upload")[:255],
|
||||
payload=gzip.compress(raw, compresslevel=6),
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
metrics.imports_total.labels(source=source, status="created").inc()
|
||||
return job
|
||||
|
||||
|
||||
def create_lastfm_import(user: User, lastfm_username: str) -> ImportJob:
|
||||
if not lastfm_pull_available():
|
||||
raise ImportFailed(
|
||||
"lastfm_not_configured", "Importing from Last.fm isn't set up on this server."
|
||||
)
|
||||
username = lastfm_username.strip()
|
||||
if not username:
|
||||
raise ImportFailed("missing_username", "Enter your Last.fm username.")
|
||||
job = ImportJob(
|
||||
user_id=user.id,
|
||||
source="lastfm",
|
||||
lastfm_username=username[:64],
|
||||
next_page=1,
|
||||
pull_until=_now(),
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
metrics.imports_total.labels(source="lastfm", status="created").inc()
|
||||
return job
|
||||
|
||||
|
||||
def list_jobs(user: User, limit: int = 20) -> list[ImportJob]:
|
||||
return list(
|
||||
db.session.scalars(
|
||||
db.select(ImportJob)
|
||||
.filter_by(user_id=user.id)
|
||||
.order_by(ImportJob.created_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_job(user: User, job_id: int) -> ImportJob | None:
|
||||
return db.session.scalar(db.select(ImportJob).filter_by(id=job_id, user_id=user.id))
|
||||
|
||||
|
||||
def cancel_job(user: User, job_id: int) -> ImportJob | None:
|
||||
job = get_job(user, job_id)
|
||||
if job is None:
|
||||
return None
|
||||
if job.status in ACTIVE:
|
||||
job.status = "cancelled"
|
||||
job.finished_at = _now()
|
||||
job.payload = None
|
||||
db.session.commit()
|
||||
metrics.imports_total.labels(source=job.source, status="cancelled").inc()
|
||||
return job
|
||||
|
||||
|
||||
# --- Storing -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _usable(item: TrackInput | None, now: datetime) -> bool:
|
||||
"""Imports keep old plays (that's the point), but not empty or future ones."""
|
||||
if item is None or not item.artist or not item.track:
|
||||
return False
|
||||
limit = current_app.config["SCROBBLE_MAX_FUTURE_SECONDS"]
|
||||
return datetime.fromtimestamp(item.timestamp, UTC) - now <= timedelta(seconds=limit)
|
||||
|
||||
|
||||
def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None:
|
||||
"""Insert one chunk and update the job's counters (the caller commits)."""
|
||||
now = _now()
|
||||
rows, seen = [], set()
|
||||
skipped = repeated = 0
|
||||
for item in items:
|
||||
if not _usable(item, now):
|
||||
skipped += 1
|
||||
continue
|
||||
played_at = datetime.fromtimestamp(item.timestamp, UTC)
|
||||
key = (played_at, item.artist, item.track)
|
||||
if key in seen: # the same play twice in one chunk: ON CONFLICT can't handle that
|
||||
repeated += 1
|
||||
continue
|
||||
seen.add(key)
|
||||
rows.append(
|
||||
{
|
||||
"user_id": job.user_id,
|
||||
"artist": item.artist,
|
||||
"track": item.track,
|
||||
"album": item.album,
|
||||
"album_artist": item.album_artist,
|
||||
"mbid": item.mbid,
|
||||
"played_at": played_at,
|
||||
"submitted_at": now,
|
||||
}
|
||||
)
|
||||
inserted = 0
|
||||
if rows:
|
||||
inserted = len(
|
||||
db.session.execute(
|
||||
insert(Scrobble)
|
||||
.values(rows)
|
||||
.on_conflict_do_nothing(constraint="uq_scrobbles_dedupe")
|
||||
.returning(Scrobble.id)
|
||||
).all()
|
||||
)
|
||||
duplicates = len(rows) - inserted + repeated
|
||||
job.imported += inserted
|
||||
job.duplicates += duplicates
|
||||
job.skipped += skipped
|
||||
job.processed += len(items)
|
||||
job.heartbeat_at = now
|
||||
counter = metrics.imported_scrobbles_total
|
||||
counter.labels(source=job.source, result="imported").inc(inserted)
|
||||
counter.labels(source=job.source, result="duplicate").inc(duplicates)
|
||||
counter.labels(source=job.source, result="skipped").inc(skipped)
|
||||
|
||||
|
||||
def _cancelled(job: ImportJob) -> bool:
|
||||
status = db.session.scalar(db.select(ImportJob.status).filter_by(id=job.id))
|
||||
return status == "cancelled"
|
||||
|
||||
|
||||
def _chunks(items: Iterable, size: int = CHUNK) -> Iterator[list]:
|
||||
chunk = []
|
||||
for item in items:
|
||||
chunk.append(item)
|
||||
if len(chunk) == size:
|
||||
yield chunk
|
||||
chunk = []
|
||||
if chunk:
|
||||
yield chunk
|
||||
|
||||
|
||||
def _process_file(job: ImportJob) -> None:
|
||||
text = _decode(gzip.decompress(job.payload))
|
||||
parse = parse_json if job.source == "json" else parse_csv
|
||||
items = list(parse(text))
|
||||
job.total = len(items)
|
||||
db.session.commit()
|
||||
for chunk in _chunks(items):
|
||||
if _cancelled(job):
|
||||
return
|
||||
store_chunk(job, chunk)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
# --- Last.fm API pull ------------------------------------------------------------------
|
||||
|
||||
|
||||
class LastfmClient:
|
||||
def __init__(self, api_url: str, api_key: str, interval: float, retries: int = 4):
|
||||
self.api_url, self.api_key = api_url, api_key
|
||||
self.interval, self.retries = interval, retries
|
||||
self._last_call = 0.0
|
||||
|
||||
def recent_tracks(self, username: str, page: int, until: datetime) -> dict:
|
||||
params = {
|
||||
"method": "user.getRecentTracks",
|
||||
"user": username,
|
||||
"api_key": self.api_key,
|
||||
"format": "json",
|
||||
"limit": "200",
|
||||
"page": str(page),
|
||||
"to": str(int(until.timestamp())),
|
||||
}
|
||||
url = f"{self.api_url}?{urllib.parse.urlencode(params)}"
|
||||
for attempt in range(self.retries + 1):
|
||||
wait = self.interval - (time.monotonic() - self._last_call)
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
self._last_call = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=30) as response:
|
||||
body = json.load(response)
|
||||
except urllib.error.HTTPError as err:
|
||||
body = _json_or_none(err)
|
||||
code = (body or {}).get("error")
|
||||
if code == 6: # "User not found"
|
||||
raise ImportFailed(
|
||||
"lastfm_user_not_found", "No Last.fm user with that name."
|
||||
) from err
|
||||
if code in (10, 26):
|
||||
raise ImportFailed(
|
||||
"lastfm_key_rejected", "Last.fm rejected this server's API key."
|
||||
) from err
|
||||
if attempt == self.retries or (err.code < 500 and code != 29):
|
||||
raise ImportFailed(
|
||||
"lastfm_error", f"Last.fm returned an error ({err.code})."
|
||||
) from err
|
||||
except (urllib.error.URLError, TimeoutError) as err:
|
||||
if attempt == self.retries:
|
||||
raise ImportFailed("lastfm_unreachable", "Couldn't reach Last.fm.") from err
|
||||
else:
|
||||
if "error" in body:
|
||||
raise ImportFailed(
|
||||
"lastfm_error", body.get("message", "Last.fm returned an error.")
|
||||
)
|
||||
return body
|
||||
time.sleep(min(30, 2**attempt)) # back off before retrying
|
||||
raise ImportFailed("lastfm_unreachable", "Couldn't reach Last.fm.")
|
||||
|
||||
|
||||
def _json_or_none(err: urllib.error.HTTPError) -> dict | None:
|
||||
try:
|
||||
return json.load(err)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _process_lastfm(job: ImportJob) -> None:
|
||||
config = current_app.config
|
||||
client = LastfmClient(
|
||||
config["LASTFM_API_URL"], config["LASTFM_API_KEY"], config["LASTFM_REQUEST_INTERVAL"]
|
||||
)
|
||||
page = job.next_page or 1
|
||||
while True:
|
||||
if _cancelled(job):
|
||||
return
|
||||
body = client.recent_tracks(job.lastfm_username, page, job.pull_until)
|
||||
recent = body.get("recenttracks", {})
|
||||
attrs = recent.get("@attr", {})
|
||||
total_pages = int(attrs.get("totalPages") or 0)
|
||||
job.total = int(attrs.get("total") or 0)
|
||||
tracks = list(_json_tracks(body))
|
||||
store_chunk(job, [_track_from_json(t) for t in tracks])
|
||||
job.next_page = page + 1
|
||||
db.session.commit()
|
||||
if page >= total_pages or not tracks:
|
||||
return
|
||||
page += 1
|
||||
|
||||
|
||||
# --- Worker ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def claim_next_job() -> ImportJob | None:
|
||||
"""Atomically take the oldest pending job (safe with several workers)."""
|
||||
job = db.session.scalar(
|
||||
db.select(ImportJob)
|
||||
.filter_by(status="pending")
|
||||
.order_by(ImportJob.created_at)
|
||||
.limit(1)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
if job is None:
|
||||
db.session.rollback()
|
||||
return None
|
||||
job.status = "running"
|
||||
job.started_at = job.started_at or _now()
|
||||
job.heartbeat_at = _now()
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def requeue_stalled(max_age: timedelta = timedelta(minutes=5)) -> int:
|
||||
"""Put back jobs whose worker died mid-way (no heartbeat for a while)."""
|
||||
result = db.session.execute(
|
||||
update(ImportJob)
|
||||
.where(ImportJob.status == "running", ImportJob.heartbeat_at < _now() - max_age)
|
||||
.values(status="pending")
|
||||
)
|
||||
db.session.commit()
|
||||
return result.rowcount
|
||||
|
||||
|
||||
def process_job(job: ImportJob) -> None:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
if job.source == "lastfm":
|
||||
_process_lastfm(job)
|
||||
else:
|
||||
_process_file(job)
|
||||
except ImportFailed as err:
|
||||
db.session.rollback()
|
||||
_finish(job, "failed", err.message)
|
||||
except Exception:
|
||||
log.exception("import job %s failed", job.id)
|
||||
db.session.rollback()
|
||||
_finish(
|
||||
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
|
||||
)
|
||||
else:
|
||||
if not _cancelled(job):
|
||||
_finish(job, "completed")
|
||||
metrics.import_duration_seconds.labels(source=job.source).observe(time.perf_counter() - started)
|
||||
|
||||
|
||||
def _finish(job: ImportJob, status: str, error: str | None = None) -> None:
|
||||
job = db.session.get(ImportJob, job.id) # reload after a rollback
|
||||
job.status, job.error, job.finished_at = status, error, _now()
|
||||
job.payload = None
|
||||
db.session.commit()
|
||||
metrics.imports_total.labels(source=job.source, status=status).inc()
|
||||
|
||||
|
||||
def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None:
|
||||
requeue_stalled()
|
||||
while True:
|
||||
job = claim_next_job()
|
||||
if job is not None:
|
||||
log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id)
|
||||
process_job(job)
|
||||
log.info("import job %s finished: %s", job.id, job.status)
|
||||
continue
|
||||
if once:
|
||||
return
|
||||
time.sleep(poll_seconds)
|
||||
@@ -0,0 +1,271 @@
|
||||
import gzip
|
||||
import json
|
||||
import threading
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from werkzeug.serving import make_server
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.models import ImportJob, Scrobble
|
||||
from scrobbler.services import imports
|
||||
from scrobbler.services.imports import ImportFailed, parse_csv, parse_json, parse_time
|
||||
|
||||
NOW = datetime.now(UTC).replace(microsecond=0)
|
||||
|
||||
|
||||
def ts(days_ago: float) -> int:
|
||||
return int((NOW - timedelta(days=days_ago)).timestamp())
|
||||
|
||||
|
||||
def fmt(days_ago: float, pattern="%d %b %Y %H:%M") -> str:
|
||||
return (NOW - timedelta(days=days_ago)).strftime(pattern)
|
||||
|
||||
|
||||
def stored(user):
|
||||
return db.session.scalars(
|
||||
db.select(Scrobble).filter_by(user_id=user.id).order_by(Scrobble.played_at.desc())
|
||||
).all()
|
||||
|
||||
|
||||
def run_all():
|
||||
imports.run_worker(once=True)
|
||||
db.session.expire_all()
|
||||
|
||||
|
||||
# --- Parsing ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
("1700000000", 1700000000),
|
||||
("1700000000000", 1700000000), # milliseconds
|
||||
("14 Nov 2023 22:13", 1700000000 - 20),
|
||||
("14 Nov 2023, 22:13", 1700000000 - 20),
|
||||
("2023-11-14T22:13:20Z", 1700000000),
|
||||
("2023-11-14 22:13:20", 1700000000),
|
||||
("not a date", None),
|
||||
("", None),
|
||||
],
|
||||
)
|
||||
def test_parse_time(value, expected):
|
||||
assert parse_time(value) == expected
|
||||
|
||||
|
||||
def test_lastfm_to_csv_without_header():
|
||||
text = f'Radiohead,In Rainbows,Reckoner,{fmt(400)}\n"Björk, Guðmundsdóttir",,Jóga,{fmt(1)}\n'
|
||||
first, second = parse_csv(text)
|
||||
assert (first.artist, first.album, first.track) == ("Radiohead", "In Rainbows", "Reckoner")
|
||||
assert first.timestamp == ts(400) - ts(400) % 60
|
||||
assert (second.artist, second.album) == ("Björk, Guðmundsdóttir", None)
|
||||
|
||||
|
||||
def test_csv_with_header_semicolons_and_extra_columns():
|
||||
text = (
|
||||
"uts;utc_time;artist;artist_mbid;album;album_mbid;track;track_mbid\n"
|
||||
f"{ts(3)};x;Portishead;;Dummy;;Roads;9b3c1a2e-0000-0000-0000-000000000000\n"
|
||||
f"bad;x;Portishead;;Dummy;;Glory Box;\n"
|
||||
)
|
||||
good, bad = parse_csv(text)
|
||||
assert (good.artist, good.track, good.album, good.timestamp) == (
|
||||
"Portishead",
|
||||
"Roads",
|
||||
"Dummy",
|
||||
ts(3),
|
||||
)
|
||||
assert good.mbid == "9b3c1a2e-0000-0000-0000-000000000000"
|
||||
assert bad is None
|
||||
|
||||
|
||||
def test_json_page_export_skips_now_playing():
|
||||
pages = [
|
||||
{
|
||||
"track": [
|
||||
{"artist": {"#text": "Nobody"}, "name": "Live", "@attr": {"nowplaying": "true"}},
|
||||
{
|
||||
"artist": {"#text": "Radiohead", "mbid": ""},
|
||||
"album": {"#text": "In Rainbows"},
|
||||
"name": "Nude",
|
||||
"date": {"uts": str(ts(2)), "#text": "ignored"},
|
||||
},
|
||||
],
|
||||
"@attr": {"page": "1"},
|
||||
},
|
||||
{"track": {"artist": {"name": "Björk"}, "name": "Hunter", "date": {"uts": str(ts(5))}}},
|
||||
]
|
||||
items = list(parse_json(json.dumps(pages)))
|
||||
assert items[0] is None
|
||||
assert [(i.artist, i.track) for i in items[1:]] == [("Radiohead", "Nude"), ("Björk", "Hunter")]
|
||||
|
||||
|
||||
def test_json_recenttracks_response_and_flat_list():
|
||||
response = {
|
||||
"recenttracks": {"track": [{"artist": "A", "name": "T", "date": {"uts": str(ts(1))}}]}
|
||||
}
|
||||
assert [i.track for i in parse_json(json.dumps(response))] == ["T"]
|
||||
flat = [{"artist": "A", "track": "U", "timestamp": ts(1)}]
|
||||
assert [i.track for i in parse_json(json.dumps(flat))] == ["U"]
|
||||
|
||||
|
||||
def test_json_errors():
|
||||
with pytest.raises(ImportFailed, match="valid JSON"):
|
||||
list(parse_json("{nope"))
|
||||
with pytest.raises(ImportFailed, match="Last.fm export"):
|
||||
list(parse_json('{"something": "else"}'))
|
||||
|
||||
|
||||
def test_format_detection():
|
||||
assert imports.detect_format("export.json", b"x") == "json"
|
||||
assert imports.detect_format("scrobbles.csv", b"[") == "csv"
|
||||
assert imports.detect_format(None, b' [{"a": 1}]') == "json"
|
||||
assert imports.detect_format("export", b"artist,album") == "csv"
|
||||
|
||||
|
||||
# --- File jobs ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_file_import_keeps_old_plays_and_dedupes(app, user, metric_delta):
|
||||
imported = metric_delta("scrobbler_imported_scrobbles_total", source="csv", result="imported")
|
||||
completed = metric_delta("scrobbler_imports_total", source="csv", status="completed")
|
||||
text = (
|
||||
f"Radiohead,In Rainbows,Reckoner,{fmt(900)}\n" # years old: fine for an import
|
||||
f"Radiohead,In Rainbows,Reckoner,{fmt(900)}\n" # repeated row
|
||||
f",No Artist,Track,{fmt(3)}\n" # skipped
|
||||
f"Future,,Track,{fmt(-2)}\n" # skipped: in the future
|
||||
f"Portishead,Dummy,Roads,not-a-date\n" # skipped: no time
|
||||
f"Björk,Homogenic,Jóga,{fmt(1)}\n"
|
||||
)
|
||||
job = imports.create_file_import(user, "export.csv", text.encode())
|
||||
assert (job.source, job.status) == ("csv", "pending")
|
||||
run_all()
|
||||
|
||||
job = db.session.get(ImportJob, job.id)
|
||||
assert job.status == "completed"
|
||||
assert (job.total, job.processed, job.imported, job.duplicates, job.skipped) == (6, 6, 2, 1, 3)
|
||||
assert job.payload is None
|
||||
assert [s.track for s in stored(user)] == ["Jóga", "Reckoner"]
|
||||
assert (imported.delta, completed.delta) == (2, 1)
|
||||
|
||||
# Importing the same export again adds nothing
|
||||
again = imports.create_file_import(user, "export.csv", text.encode())
|
||||
run_all()
|
||||
again = db.session.get(ImportJob, again.id)
|
||||
assert (again.imported, again.duplicates) == (0, 3)
|
||||
assert len(stored(user)) == 2
|
||||
|
||||
|
||||
def test_gzipped_json_upload(app, user):
|
||||
data = [{"artist": "A", "name": f"T{i}", "date": {"uts": str(ts(30 + i))}} for i in range(2500)]
|
||||
raw = gzip.compress(json.dumps(data).encode())
|
||||
job = imports.create_file_import(user, "export.json.gz", raw)
|
||||
run_all()
|
||||
job = db.session.get(ImportJob, job.id)
|
||||
assert (job.source, job.status, job.imported) == ("json", "completed", 2500)
|
||||
|
||||
|
||||
def test_bad_file_fails_the_job_with_a_reason(app, user, metric_delta):
|
||||
failed = metric_delta("scrobbler_imports_total", source="json", status="failed")
|
||||
job = imports.create_file_import(user, "export.json", b'{"not": "an export"}')
|
||||
run_all()
|
||||
job = db.session.get(ImportJob, job.id)
|
||||
assert job.status == "failed"
|
||||
assert "Last.fm export" in job.error
|
||||
assert failed.delta == 1
|
||||
|
||||
|
||||
def test_empty_upload_is_rejected(app, user):
|
||||
with pytest.raises(ImportFailed):
|
||||
imports.create_file_import(user, "empty.csv", b" \n")
|
||||
|
||||
|
||||
def test_cancelled_jobs_are_not_processed(app, user):
|
||||
job = imports.create_file_import(user, "export.csv", f"A,,T,{fmt(1)}\n".encode())
|
||||
imports.cancel_job(user, job.id)
|
||||
run_all()
|
||||
job = db.session.get(ImportJob, job.id)
|
||||
assert job.status == "cancelled"
|
||||
assert stored(user) == []
|
||||
|
||||
|
||||
def test_stalled_jobs_are_requeued(app, user):
|
||||
job = imports.create_file_import(user, "export.csv", f"A,,T,{fmt(1)}\n".encode())
|
||||
job.status = "running"
|
||||
job.heartbeat_at = datetime.now(UTC) - timedelta(minutes=10)
|
||||
db.session.commit()
|
||||
assert imports.requeue_stalled() == 1
|
||||
run_all()
|
||||
assert db.session.get(ImportJob, job.id).status == "completed"
|
||||
|
||||
|
||||
def test_jobs_are_private(app, user, make_user):
|
||||
job = imports.create_file_import(user, "export.csv", f"A,,T,{fmt(1)}\n".encode())
|
||||
other = make_user(username="mallory")
|
||||
assert imports.get_job(other, job.id) is None
|
||||
assert imports.cancel_job(other, job.id) is None
|
||||
|
||||
|
||||
# --- Last.fm pull ------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fake_lastfm(app):
|
||||
"""This app's own Last.fm-compatible API stands in for last.fm."""
|
||||
server = make_server("127.0.0.1", 0, app, threaded=True)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield f"http://127.0.0.1:{server.server_port}/2.0/"
|
||||
server.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lastfm_config(app, fake_lastfm, api_app):
|
||||
saved = {
|
||||
k: app.config[k] for k in ("LASTFM_API_KEY", "LASTFM_API_URL", "LASTFM_REQUEST_INTERVAL")
|
||||
}
|
||||
app.config.update(
|
||||
LASTFM_API_KEY=api_app.api_key, LASTFM_API_URL=fake_lastfm, LASTFM_REQUEST_INTERVAL=0
|
||||
)
|
||||
yield
|
||||
app.config.update(saved)
|
||||
|
||||
|
||||
def test_lastfm_pull_needs_an_api_key(app, user):
|
||||
assert not imports.lastfm_pull_available()
|
||||
with pytest.raises(ImportFailed) as err:
|
||||
imports.create_lastfm_import(user, "someone")
|
||||
assert err.value.code == "lastfm_not_configured"
|
||||
|
||||
|
||||
def test_lastfm_pull_pages_through_history(app, lastfm_config, user, make_user, metric_delta):
|
||||
remote = make_user(username="remote")
|
||||
db.session.add_all(
|
||||
Scrobble(
|
||||
user_id=remote.id,
|
||||
artist="Artist",
|
||||
track=f"Track {i}",
|
||||
played_at=NOW - timedelta(hours=i + 1),
|
||||
)
|
||||
for i in range(450)
|
||||
)
|
||||
db.session.commit()
|
||||
imported = metric_delta(
|
||||
"scrobbler_imported_scrobbles_total", source="lastfm", result="imported"
|
||||
)
|
||||
|
||||
job = imports.create_lastfm_import(user, "remote")
|
||||
run_all()
|
||||
|
||||
job = db.session.get(ImportJob, job.id)
|
||||
assert job.status == "completed", job.error
|
||||
assert (job.total, job.imported, job.next_page) == (450, 450, 4) # 3 pages of 200
|
||||
assert len(stored(user)) == 450
|
||||
assert imported.delta == 450
|
||||
|
||||
|
||||
def test_lastfm_pull_unknown_user(app, lastfm_config, user):
|
||||
job = imports.create_lastfm_import(user, "nobody-by-that-name")
|
||||
run_all()
|
||||
job = db.session.get(ImportJob, job.id)
|
||||
assert job.status == "failed"
|
||||
assert job.error == "No Last.fm user with that name."
|
||||
Reference in new issue
Block a user