diff --git a/src/matrix/api.js b/src/matrix/api.js index edffc45..6d135bd 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -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}>} */ 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) } diff --git a/src/matrix/mreq.js b/src/matrix/mreq.js index 9179825..bed7951 100644 --- a/src/matrix/mreq.js +++ b/src/matrix/mreq.js @@ -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} @@ -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