I want my listening history and my playlists from Spotify in Sonda, so that Mixes, Discover and the smart playlists know what I listened to before. - POST /me/import/spotify takes the zip of a Spotify data export, or the JSON files in it (extended streaming history, the older StreamingHistory files, the playlists), as a multipart form. A request may be up to 512 MB; the zip is limited in how much it may inflate and how many files it may hold, and only the history and playlist files are opened. - Everything is read on the server and nothing is sent anywhere. The files are not kept, and of each play only the song, artist, album, time and how it ended are read: never the IP addresses, the country or the platform. - A play is matched to a song of the library by artist and title (no case, accents or punctuation; a "Remastered" note on either side; any credited artist; a compilation by its album). A match is recorded as a listen at the time of the play: complete, skip or play. Nothing is posted to Mastodon. - Importing the same files again records nothing twice, and the same play in the two shapes of history file is counted once. One import per person at a time. - A playlist becomes a playlist of mine with the songs that were found; one with a name I already have is left alone, and one with none of its songs found is not made. - The report counts what was added, what was already there and what is not in the library, and lists the missing artists, most played first. - Settings gets an Import from Spotify section; the API client can send files. - English and Italian.
129 lines
5 KiB
TypeScript
129 lines
5 KiB
TypeScript
/** What the server answers when a call fails: `{"error": {"code", "message"}}`. */
|
|
export class ApiError extends Error {
|
|
status: number
|
|
code: string
|
|
/** Seconds to wait before asking again, when the server said so (`Retry-After`). */
|
|
retryAfter?: number
|
|
|
|
constructor(status: number, code: string, message: string, retryAfter?: number) {
|
|
super(message)
|
|
this.name = 'ApiError'
|
|
this.status = status
|
|
this.code = code
|
|
this.retryAfter = retryAfter
|
|
}
|
|
}
|
|
|
|
/** The session side of a call, injected so that this file never imports the session (which imports this). */
|
|
export interface AuthHooks {
|
|
getAccessToken(): Promise<string | null>
|
|
/** Renews the session; resolves to the new access token, or null when there is nothing to renew. */
|
|
refresh(): Promise<string | null>
|
|
signOut(): void
|
|
}
|
|
|
|
let hooks: AuthHooks = {
|
|
getAccessToken: async () => null,
|
|
refresh: async () => null,
|
|
signOut: () => {},
|
|
}
|
|
|
|
export function setAuthHooks(next: AuthHooks): void {
|
|
hooks = next
|
|
}
|
|
|
|
type QueryValue = string | number | boolean | undefined
|
|
/** A list value is sent once for each item (`seed=1&seed=2`). */
|
|
type Query = Record<string, QueryValue | QueryValue[]>
|
|
|
|
export interface CallOptions {
|
|
/** Default true. Login, register, refresh and logout say false: they carry no token and never renew. */
|
|
auth?: boolean
|
|
/** Lets the request finish after the page is closed (the browser allows it for small bodies). */
|
|
keepalive?: boolean
|
|
/** Cancels the request. A cancelled call rejects with the browser's `AbortError`, not an `ApiError`. */
|
|
signal?: AbortSignal
|
|
}
|
|
|
|
const BASE = '/api/v1'
|
|
|
|
function buildUrl(path: string, params?: Query): string {
|
|
const query = new URLSearchParams()
|
|
for (const [key, value] of Object.entries(params ?? {})) {
|
|
for (const item of Array.isArray(value) ? value : [value]) {
|
|
if (item !== undefined) query.append(key, String(item))
|
|
}
|
|
}
|
|
const text = query.toString()
|
|
return `${BASE}${path}${text ? `?${text}` : ''}`
|
|
}
|
|
|
|
async function toApiError(res: Response): Promise<ApiError> {
|
|
try {
|
|
const body = (await res.json()) as { error?: { code?: string; message?: string } }
|
|
return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText, retryAfter(res))
|
|
} catch {
|
|
return new ApiError(res.status, 'unknown', res.statusText, retryAfter(res))
|
|
}
|
|
}
|
|
|
|
/** The `Retry-After` header in whole seconds, or nothing when it is absent or is a date. */
|
|
function retryAfter(res: Response): number | undefined {
|
|
const text = res.headers.get('Retry-After')
|
|
if (text === null || !/^\d+$/.test(text.trim())) return undefined
|
|
return Number(text)
|
|
}
|
|
|
|
async function send(
|
|
method: string,
|
|
url: string,
|
|
body: unknown,
|
|
token: string | null,
|
|
keepalive: boolean | undefined,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<Response> {
|
|
const headers: Record<string, string> = { Accept: 'application/json' }
|
|
// A form (files) is sent as it is: the browser writes its content type, which carries the boundary.
|
|
const form = body instanceof FormData
|
|
if (body !== undefined && !form) headers['Content-Type'] = 'application/json'
|
|
if (token) headers.Authorization = `Bearer ${token}`
|
|
try {
|
|
return await fetch(url, {
|
|
method,
|
|
headers,
|
|
body: body === undefined ? undefined : form ? body : JSON.stringify(body),
|
|
keepalive: keepalive || undefined,
|
|
signal,
|
|
})
|
|
} catch (e) {
|
|
// A cancelled request is the caller's own doing: say so as it is, not as a broken connection.
|
|
if (e instanceof DOMException && e.name === 'AbortError') throw e
|
|
throw new ApiError(0, 'network', 'The server cannot be reached')
|
|
}
|
|
}
|
|
|
|
async function request<T>(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise<T> {
|
|
const auth = opts.auth ?? true
|
|
const url = buildUrl(path, params)
|
|
let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive, opts.signal)
|
|
|
|
if (res.status === 401 && auth) {
|
|
const fresh = await hooks.refresh()
|
|
if (fresh) res = await send(method, url, body, fresh, opts.keepalive, opts.signal)
|
|
if (res.status === 401) hooks.signOut()
|
|
}
|
|
|
|
if (!res.ok) throw await toApiError(res)
|
|
if (res.status === 204) return undefined as T
|
|
return (await res.json()) as T
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string, params?: Query, opts: CallOptions = {}) => request<T>('GET', path, params, undefined, opts),
|
|
post: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('POST', path, undefined, body ?? {}, opts),
|
|
/** Sends files, as a form. */
|
|
upload: <T>(path: string, form: FormData, opts: CallOptions = {}) => request<T>('POST', path, undefined, form, opts),
|
|
patch: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('PATCH', path, undefined, body ?? {}, opts),
|
|
put: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('PUT', path, undefined, body ?? {}, opts),
|
|
del: <T>(path: string, opts: CallOptions = {}) => request<T>('DELETE', path, undefined, undefined, opts),
|
|
}
|