Imports API: upload exports, pull from Last.fm, follow progress
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 47s
CI / python-package (push) Skipped
CI / assets (push) Successful in 8s
CI / images (push) Successful in 31s
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 47s
CI / python-package (push) Skipped
CI / assets (push) Successful in 8s
CI / images (push) Successful in 31s
CI / notify (push) Successful in 6s
- /api/v1/imports/options lists the available sources; `lastfm` only
appears when the server has a Last.fm API key
- POST /imports/file (multipart; format detected or forced with
?format=), POST /imports/lastfm, GET /imports, GET /imports/{id},
POST /imports/{id}/cancel
- Upload size limit (IMPORT_MAX_BYTES, default 200 MB) with a 413
- Documented in OpenAPI under the Imports tag
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
6fc9d91fa2
commit
eebd7b8730
5 files changed
+759
-1
No files matched your search
@@ -992,6 +992,356 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/imports/options": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportOptions"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "What can be imported",
|
||||
"description": "Pulling from Last.fm is only offered when the server has a Last.fm API key.",
|
||||
"tags": [
|
||||
"Imports"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/imports/file": {
|
||||
"post": {
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "format",
|
||||
"description": "Detected from the file name and contents when `auto`",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"default": "auto",
|
||||
"enum": [
|
||||
"auto",
|
||||
"csv",
|
||||
"json"
|
||||
]
|
||||
},
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"422": {
|
||||
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
|
||||
},
|
||||
"413": {
|
||||
"description": "File too large",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Empty or unsupported file",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"202": {
|
||||
"description": "Accepted",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportJob"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"multipart/form-data": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportFile"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"summary": "Import an export file",
|
||||
"description": "Accepts lastfm-to-csv CSV files, other CSV/TSV files with a header row, and JSON\nexports of user.getRecentTracks pages. Files may be gzipped.",
|
||||
"tags": [
|
||||
"Imports"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/imports/lastfm": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"422": {
|
||||
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
|
||||
},
|
||||
"400": {
|
||||
"description": "Last.fm import isn't configured",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"202": {
|
||||
"description": "Accepted",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportJob"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/LastfmImport"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"summary": "Import from Last.fm",
|
||||
"description": "Copies a Last.fm user's public scrobble history into your account.",
|
||||
"tags": [
|
||||
"Imports"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/imports": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ImportJob"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "Your recent imports",
|
||||
"tags": [
|
||||
"Imports"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/imports/{job_id}": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "No such import",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportJob"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "One import's progress",
|
||||
"tags": [
|
||||
"Imports"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "job_id",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"/api/v1/imports/{job_id}/cancel": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "No such import",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportJob"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "Cancel an import",
|
||||
"description": "Stops a waiting or running import. Scrobbles already imported are kept.",
|
||||
"tags": [
|
||||
"Imports"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "job_id",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"/healthz": {
|
||||
"get": {
|
||||
"responses": {
|
||||
@@ -1529,6 +1879,10 @@
|
||||
"name": "Stats",
|
||||
"description": "Your listening history and statistics"
|
||||
},
|
||||
{
|
||||
"name": "Imports",
|
||||
"description": "Import listening history from a Last.fm export file, or straight from Last.fm. Imports run in the background; poll a job to follow its progress."
|
||||
},
|
||||
{
|
||||
"name": "Health",
|
||||
"description": "Liveness for load balancers and containers"
|
||||
@@ -1974,6 +2328,141 @@
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ImportOptions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"description": "`lastfm` is only listed when the server has a Last.fm API key",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"csv",
|
||||
"json",
|
||||
"lastfm"
|
||||
]
|
||||
}
|
||||
},
|
||||
"max_upload_bytes": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ImportFile": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file": {
|
||||
"description": "CSV or JSON export, optionally gzipped",
|
||||
"type": "string",
|
||||
"format": "binary"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"file"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ImportJob": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"csv",
|
||||
"json",
|
||||
"lastfm"
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"pending",
|
||||
"running",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"filename": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"lastfm_username": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"total": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"description": "Rows or tracks to process, once known"
|
||||
},
|
||||
"processed": {
|
||||
"type": "integer"
|
||||
},
|
||||
"imported": {
|
||||
"type": "integer",
|
||||
"description": "New scrobbles added"
|
||||
},
|
||||
"duplicates": {
|
||||
"type": "integer",
|
||||
"description": "Already in your history"
|
||||
},
|
||||
"skipped": {
|
||||
"type": "integer",
|
||||
"description": "No artist/track, bad date, or future"
|
||||
},
|
||||
"error": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"started_at": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"format": "date-time"
|
||||
},
|
||||
"finished_at": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"format": "date-time"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"LastfmImport": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"username": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 64,
|
||||
"example": "rj"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"username"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"Health": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -43,13 +43,14 @@ def init_app(app: Flask) -> None:
|
||||
},
|
||||
)
|
||||
|
||||
from scrobbler.api import apps, auth, health, sessions, stats, tokens
|
||||
from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens
|
||||
|
||||
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
|
||||
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
||||
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
||||
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
||||
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
||||
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
||||
api.register_blueprint(health.blp)
|
||||
|
||||
from scrobbler.openapi import lastfm
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
from flask import current_app, g
|
||||
from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler.api.decorators import authenticated
|
||||
from scrobbler.schemas import (
|
||||
ErrorSchema,
|
||||
ImportFileSchema,
|
||||
ImportFormatSchema,
|
||||
ImportJobSchema,
|
||||
ImportOptionsSchema,
|
||||
LastfmImportSchema,
|
||||
)
|
||||
from scrobbler.services import imports
|
||||
|
||||
blp = Blueprint(
|
||||
"Imports",
|
||||
__name__,
|
||||
description=(
|
||||
"Import listening history from a Last.fm export file, or straight from Last.fm. "
|
||||
"Imports run in the background; poll a job to follow its progress."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@blp.route("/options", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, ImportOptionsSchema)
|
||||
def options():
|
||||
"""What can be imported
|
||||
|
||||
Pulling from Last.fm is only offered when the server has a Last.fm API key.
|
||||
"""
|
||||
sources = ["csv", "json"] + (["lastfm"] if imports.lastfm_pull_available() else [])
|
||||
return {"sources": sources, "max_upload_bytes": current_app.config["IMPORT_MAX_BYTES"]}
|
||||
|
||||
|
||||
@blp.route("/file", methods=["POST"])
|
||||
@authenticated(blp)
|
||||
@blp.arguments(ImportFileSchema, location="files")
|
||||
@blp.arguments(ImportFormatSchema, location="query")
|
||||
@blp.response(202, ImportJobSchema)
|
||||
@blp.alt_response(400, schema=ErrorSchema, description="Empty or unsupported file")
|
||||
@blp.alt_response(413, schema=ErrorSchema, description="File too large")
|
||||
def import_file(files, query):
|
||||
"""Import an export file
|
||||
|
||||
Accepts lastfm-to-csv CSV files, other CSV/TSV files with a header row, and JSON
|
||||
exports of user.getRecentTracks pages. Files may be gzipped.
|
||||
"""
|
||||
upload = files["file"]
|
||||
raw = upload.read(current_app.config["IMPORT_MAX_BYTES"] + 1)
|
||||
if len(raw) > current_app.config["IMPORT_MAX_BYTES"]:
|
||||
abort(413, code="file_too_large", message="That file is larger than this server accepts.")
|
||||
try:
|
||||
return imports.create_file_import(g.user, upload.filename, raw, query["format"])
|
||||
except imports.ImportFailed as err:
|
||||
abort(400, code=err.code, message=err.message)
|
||||
|
||||
|
||||
@blp.route("/lastfm", methods=["POST"])
|
||||
@authenticated(blp)
|
||||
@blp.arguments(LastfmImportSchema)
|
||||
@blp.response(202, ImportJobSchema)
|
||||
@blp.alt_response(400, schema=ErrorSchema, description="Last.fm import isn't configured")
|
||||
def import_lastfm(body):
|
||||
"""Import from Last.fm
|
||||
|
||||
Copies a Last.fm user's public scrobble history into your account.
|
||||
"""
|
||||
try:
|
||||
return imports.create_lastfm_import(g.user, body["username"])
|
||||
except imports.ImportFailed as err:
|
||||
abort(400, code=err.code, message=err.message)
|
||||
|
||||
|
||||
@blp.route("", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, ImportJobSchema(many=True))
|
||||
def list_imports():
|
||||
"""Your recent imports"""
|
||||
return imports.list_jobs(g.user)
|
||||
|
||||
|
||||
@blp.route("/<int:job_id>", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, ImportJobSchema)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No such import")
|
||||
def get_import(job_id):
|
||||
"""One import's progress"""
|
||||
job = imports.get_job(g.user, job_id)
|
||||
if job is None:
|
||||
abort(404, code="not_found", message="No such import")
|
||||
return job
|
||||
|
||||
|
||||
@blp.route("/<int:job_id>/cancel", methods=["POST"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, ImportJobSchema)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No such import")
|
||||
def cancel_import(job_id):
|
||||
"""Cancel an import
|
||||
|
||||
Stops a waiting or running import. Scrobbles already imported are kept.
|
||||
"""
|
||||
job = imports.cancel_job(g.user, job_id)
|
||||
if job is None:
|
||||
abort(404, code="not_found", message="No such import")
|
||||
return job
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Marshmallow schemas for the /api/v1 JSON API. They drive both request
|
||||
validation and the generated OpenAPI document."""
|
||||
|
||||
from flask_smorest.fields import Upload
|
||||
from marshmallow import Schema, fields, validate
|
||||
|
||||
|
||||
@@ -143,3 +144,55 @@ class SummarySchema(Schema):
|
||||
artists = fields.Integer()
|
||||
tracks = fields.Integer()
|
||||
first_scrobble_at = fields.DateTime(allow_none=True)
|
||||
|
||||
|
||||
IMPORT_SOURCES = ["csv", "json", "lastfm"]
|
||||
IMPORT_STATUSES = ["pending", "running", "completed", "failed", "cancelled"]
|
||||
|
||||
|
||||
class ImportOptionsSchema(Schema):
|
||||
sources = fields.List(
|
||||
fields.String(validate=validate.OneOf(IMPORT_SOURCES)),
|
||||
metadata={"description": "`lastfm` is only listed when the server has a Last.fm API key"},
|
||||
)
|
||||
max_upload_bytes = fields.Integer()
|
||||
|
||||
|
||||
class ImportJobSchema(Schema):
|
||||
id = fields.Integer()
|
||||
source = fields.String(validate=validate.OneOf(IMPORT_SOURCES))
|
||||
status = fields.String(validate=validate.OneOf(IMPORT_STATUSES))
|
||||
filename = fields.String(allow_none=True)
|
||||
lastfm_username = fields.String(allow_none=True)
|
||||
total = fields.Integer(
|
||||
allow_none=True, metadata={"description": "Rows or tracks to process, once known"}
|
||||
)
|
||||
processed = fields.Integer()
|
||||
imported = fields.Integer(metadata={"description": "New scrobbles added"})
|
||||
duplicates = fields.Integer(metadata={"description": "Already in your history"})
|
||||
skipped = fields.Integer(metadata={"description": "No artist/track, bad date, or future"})
|
||||
error = fields.String(allow_none=True)
|
||||
created_at = fields.DateTime()
|
||||
started_at = fields.DateTime(allow_none=True)
|
||||
finished_at = fields.DateTime(allow_none=True)
|
||||
|
||||
|
||||
class ImportFileSchema(Schema):
|
||||
file = Upload(
|
||||
required=True,
|
||||
metadata={"description": "CSV or JSON export, optionally gzipped"},
|
||||
)
|
||||
|
||||
|
||||
class ImportFormatSchema(Schema):
|
||||
format = fields.String(
|
||||
load_default="auto",
|
||||
validate=validate.OneOf(["auto", "csv", "json"]),
|
||||
metadata={"description": "Detected from the file name and contents when `auto`"},
|
||||
)
|
||||
|
||||
|
||||
class LastfmImportSchema(Schema):
|
||||
username = fields.String(
|
||||
required=True, validate=validate.Length(min=1, max=64), metadata={"example": "rj"}
|
||||
)
|
||||
@@ -0,0 +1,107 @@
|
||||
import io
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from scrobbler.services import imports
|
||||
|
||||
|
||||
def csv_bytes(n=3) -> bytes:
|
||||
day = datetime.now(UTC) - timedelta(days=400)
|
||||
rows = [
|
||||
f"Artist,Album,Track {i},{(day + timedelta(minutes=i)).strftime('%d %b %Y %H:%M')}"
|
||||
for i in range(n)
|
||||
]
|
||||
return ("\n".join(rows) + "\n").encode()
|
||||
|
||||
|
||||
def upload(client, auth, data: bytes, name="export.csv", query=""):
|
||||
return client.post(
|
||||
f"/api/v1/imports/file{query}",
|
||||
data={"file": (io.BytesIO(data), name)},
|
||||
headers=auth,
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
|
||||
|
||||
def test_options_hide_lastfm_without_an_api_key(client, auth, app):
|
||||
body = client.get("/api/v1/imports/options", headers=auth).get_json()
|
||||
assert body["sources"] == ["csv", "json"]
|
||||
assert body["max_upload_bytes"] == app.config["IMPORT_MAX_BYTES"]
|
||||
|
||||
|
||||
def test_options_offer_lastfm_with_an_api_key(client, auth, app):
|
||||
app.config["LASTFM_API_KEY"] = "configured"
|
||||
try:
|
||||
body = client.get("/api/v1/imports/options", headers=auth).get_json()
|
||||
finally:
|
||||
app.config["LASTFM_API_KEY"] = ""
|
||||
assert body["sources"] == ["csv", "json", "lastfm"]
|
||||
|
||||
|
||||
def test_upload_then_follow_progress(client, auth):
|
||||
response = upload(client, auth, csv_bytes(3))
|
||||
assert response.status_code == 202
|
||||
job = response.get_json()
|
||||
assert (job["source"], job["status"], job["filename"]) == ("csv", "pending", "export.csv")
|
||||
|
||||
imports.run_worker(once=True)
|
||||
done = client.get(f"/api/v1/imports/{job['id']}", headers=auth).get_json()
|
||||
assert (done["status"], done["imported"], done["total"]) == ("completed", 3, 3)
|
||||
assert client.get("/api/v1/me/summary", headers=auth).get_json()["scrobbles"] == 3
|
||||
assert [j["id"] for j in client.get("/api/v1/imports", headers=auth).get_json()] == [job["id"]]
|
||||
|
||||
|
||||
def test_forced_format(client, auth):
|
||||
response = upload(
|
||||
client,
|
||||
auth,
|
||||
b'[{"artist": "A", "name": "T", "uts": 1600000000}]',
|
||||
name="data.txt",
|
||||
query="?format=json",
|
||||
)
|
||||
assert response.get_json()["source"] == "json"
|
||||
|
||||
|
||||
def test_empty_upload_is_a_400(client, auth):
|
||||
response = upload(client, auth, b"")
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "empty_file"
|
||||
|
||||
|
||||
def test_too_large_upload_is_a_413(client, auth, app):
|
||||
saved = app.config["IMPORT_MAX_BYTES"]
|
||||
app.config["IMPORT_MAX_BYTES"] = 10
|
||||
try:
|
||||
response = upload(client, auth, csv_bytes(3))
|
||||
finally:
|
||||
app.config["IMPORT_MAX_BYTES"] = saved
|
||||
assert response.status_code == 413
|
||||
assert response.get_json()["error"]["code"] == "file_too_large"
|
||||
|
||||
|
||||
def test_lastfm_import_without_api_key(client, auth):
|
||||
response = client.post("/api/v1/imports/lastfm", json={"username": "rj"}, headers=auth)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "lastfm_not_configured"
|
||||
|
||||
|
||||
def test_cancel(client, auth):
|
||||
job = upload(client, auth, csv_bytes(1)).get_json()
|
||||
cancelled = client.post(f"/api/v1/imports/{job['id']}/cancel", headers=auth).get_json()
|
||||
assert cancelled["status"] == "cancelled"
|
||||
|
||||
|
||||
def test_other_users_imports_are_hidden(client, auth, make_user):
|
||||
from scrobbler.services.accounts import issue_ui_token
|
||||
|
||||
job = upload(client, auth, csv_bytes(1)).get_json()
|
||||
other = {"Authorization": f"Bearer {issue_ui_token(make_user(username='mallory'))}"}
|
||||
assert client.get(f"/api/v1/imports/{job['id']}", headers=other).status_code == 404
|
||||
assert client.post(f"/api/v1/imports/{job['id']}/cancel", headers=other).status_code == 404
|
||||
assert client.get("/api/v1/imports", headers=other).get_json() == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/api/v1/imports", "/api/v1/imports/options"])
|
||||
def test_imports_need_auth(client, path):
|
||||
assert client.get(path).status_code == 401
|
||||
Reference in new issue
Block a user