Try raising errors for failed media

This commit is contained in:
Cadence Ember
2025-11-13 15:47:42 +13:00
parent 56a4fe1286
commit 3d34c9d653
2 changed files with 25 additions and 2 deletions

View File

@@ -378,19 +378,26 @@ async function ping() {
}
/**
* Given an mxc:// URL, and an optional height for thumbnailing, get the file from the content repository. Returns res.
* @param {string} mxc
* @param {RequestInit} [init]
* @param {RequestInit & {height?: number | string}} [init]
* @return {Promise<Response & {body: streamWeb.ReadableStream<Uint8Array>}>}
*/
async function getMedia(mxc, init = {}) {
const mediaParts = mxc?.match(/^mxc:\/\/([^/]+)\/(\w+)$/)
assert(mediaParts)
const res = await fetch(`${mreq.baseUrl}/client/v1/media/download/${mediaParts[1]}/${mediaParts[2]}`, {
const downloadOrThumbnail = init.height ? "thumbnail" : "download"
let url = `${mreq.baseUrl}/client/v1/media/${downloadOrThumbnail}/${mediaParts[1]}/${mediaParts[2]}`
if (init.height) url += "?" + new URLSearchParams({height: String(init.height), width: String(init.height)})
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${reg.as_token}`
},
...init
})
if (res.status !== 200) {
throw mreq.makeMatrixServerError(res, init)
}
if (init.method !== "HEAD") {
assert(res.body)
}

View File

@@ -18,6 +18,21 @@ class MatrixServerError extends Error {
}
}
/**
* @param {Response} res
* @param {object} opts
*/
async function makeMatrixServerError(res, opts = {}) {
delete opts.headers?.["Authorization"]
if (res.headers.get("content-type") === "application/json") {
return new MatrixServerError(await res.json(), opts)
} else if (res.headers.get("content-type")?.startsWith("text/")) {
return new MatrixServerError({errcode: "CX_SERVER_ERROR", error: `Server returned HTTP status ${res.status}`, message: await res.text()})
} else {
return new MatrixServerError({errcode: "CX_SERVER_ERROR", error: `Server returned HTTP status ${res.status}`, content_type: res.headers.get("content-type")})
}
}
/**
* @param {undefined | string | object | streamWeb.ReadableStream | stream.Readable} body
* @returns {Promise<string | streamWeb.ReadableStream | stream.Readable | Buffer>}
@@ -85,6 +100,7 @@ async function withAccessToken(token, callback) {
}
module.exports.MatrixServerError = MatrixServerError
module.exports.makeMatrixServerError = makeMatrixServerError
module.exports.baseUrl = baseUrl
module.exports.mreq = mreq
module.exports.withAccessToken = withAccessToken