import { MAX_SUCCESS_BODY_BYTES, CALL_MS, DeadlineError, dropAnswer, readBounded, startDeadline, waitForResponse, type Deadline } from './deadline.ts'
import { throughLogin, loginFetch, type LoginClient } from './login-client.ts'
import { AudibleApiError } from './errors.ts'
import { buildQuery, sendableCall, WISHLIST_COLLECTION, WISHLIST_REMOVE, type QueryValue } from './policy.ts'
// The collections calls copy mkb79/audible-rs, whose wire matches a capture of the official app:
// the token in x-amz-access-token, no Authorization, and the app's User-Agent.
const COLLECTIONS_HEADERS = {
'User-Agent': 'Audible/671 CFNetwork/1240.0.4 Darwin/20.6.0',
}
async function send(client: LoginClient, method: string, path: string, url: string, bodyText: string, call: string) {
return loginFetch(client, url, {
method,
headers: { Accept: 'application/json', ...(path.startsWith('/1.0/collections/') ? COLLECTIONS_HEADERS : {}), ...(bodyText ? { 'Content-Type': 'application/json' } : {}) },
body: bodyText || undefined,
}, call)
}
const unreadable = (call: string, response: Response) => new Error(`Audible API ${call} → HTTP ${response.status} (body: unreadable)`)
async function bodyOf(response: Response, call: string, deadline: Deadline): Promise<unknown> {
const read = await readBounded(response, MAX_SUCCESS_BODY_BYTES + 1, deadline)
if (!read) throw unreadable(call, response)
if (read.size > MAX_SUCCESS_BODY_BYTES) throw new Error(`Audible API ${call} → HTTP ${response.status} (body: over 16 MB)`)
if (!read.text) return null
try {
return JSON.parse(read.text)
} catch {
return read.text
}
}
const ERROR_BODY_BYTES = 4096
const ERROR_BODY_MS = 1000
const ERROR_TAGS: ReadonlyArray<readonly [tag: string, phrases: readonly string[]]> = [
['not-found', ['not found', 'notfound']],
['signature', ['signature', 'signed', 'unsigned', 'adp']],
['auth', ['unauthorized', 'forbidden', 'token', 'authenticat']],
['content-type', ['content type', 'unsupported media', 'media type']],
['invalid', ['invalid', 'malformed', 'bad request']],
]
const errorText = (response: Response, deadline: Deadline) =>
readBounded(response, ERROR_BODY_BYTES, deadline, ERROR_BODY_MS).then((read) => read?.text, () => undefined)
function errorSummary(status: number, text: string | undefined) {
if (text === undefined) return `HTTP ${status}`
const shape = !text.trim() ? 'empty' : /^\s*[{[]/.test(text) ? 'json' : 'text'
const words = ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, ' ')}`
const tags = ERROR_TAGS.filter(([, phrases]) => phrases.some((phrase) => words.includes(` ${phrase}`))).map(([tag]) => tag)
return `HTTP ${status} (body: ${shape}${tags.length ? `; tags: ${tags.join(', ')}` : ''})`
}
async function exchange(client: LoginClient, apiHost: string, method: string, path: string, query: Record<string, QueryValue> | undefined, bodyText: string, call: string, deadline: Deadline) {
const url = `https://${apiHost}${path}${buildQuery(query)}`
const response = await waitForResponse(deadline, () => send(client, method, path, url, bodyText, call))
if (!response.ok) throw new AudibleApiError(response.status, `Audible API ${call} → ${errorSummary(response.status, await errorText(response, deadline))}`)
return { response }
}
const STATE_TOKEN_CHARS = 4096
const COLLECTION_BODY_BYTES = 65536
const COLLECTION_BODY_MS = 1000
async function wishlistStateToken(client: LoginClient, apiHost: string, deadline: Deadline) {
const call = `GET ${WISHLIST_COLLECTION}`
const meta = await exchange(client, apiHost, 'GET', WISHLIST_COLLECTION, undefined, '', call, deadline)
const body = await readBounded(meta.response, COLLECTION_BODY_BYTES + 1, deadline, COLLECTION_BODY_MS)
if (!body) throw unreadable(call, meta.response)
if (body.size > COLLECTION_BODY_BYTES) throw new Error(`Audible API ${call} → HTTP ${meta.response.status} (body: over 64 KB)`)
let token: unknown
try {
token = JSON.parse(body.text)?.state_token
} catch {}
if (typeof token !== 'string' || !token || token.length > STATE_TOKEN_CHARS) {
throw new Error('Audible gave no state_token for the Wishlist, so the remove was not sent.')
}
return token
}
export async function sendAudible<T = unknown>(
...args: Parameters<typeof sendableCall>
): Promise<T> {
const { method, path, query, body } = sendableCall(...args)
const call = `${method} ${path}${buildQuery(query)}`
const deadline = startDeadline(CALL_MS, () => new DeadlineError(`Audible API ${call} → no answer within ${CALL_MS / 1000} s`))
try {
return await throughLogin(deadline, async ({ client, locale }) => {
const remove = method === 'DELETE' && path === WISHLIST_REMOVE
const wireQuery = remove ? { state_token: await wishlistStateToken(client, locale.apiHost, deadline), ...query } : query
const result = await exchange(client, locale.apiHost, method, path, wireQuery, body ? JSON.stringify(body) : '', call, deadline)
if (remove) dropAnswer(result.response)
return (remove ? null : await bodyOf(result.response, call, deadline)) as T
})
} finally {
deadline.end()
}
}