Generate public urls for media.discordapp.net too

This commit is contained in:
Cadence Ember 2024-09-15 00:34:53 +12:00
commit ae9acbcc52
3 changed files with 38 additions and 33 deletions

View file

@ -27,36 +27,41 @@ function timeUntilExpiry(url) {
return false
}
as.router.get(`/download/discordcdn/:channel_id/:attachment_id/:file_name`, defineEventHandler(async event => {
const params = await getValidatedRouterParams(event, schema.params.parse)
function defineMediaProxyHandler(domain) {
return defineEventHandler(async event => {
const params = await getValidatedRouterParams(event, schema.params.parse)
const row = select("channel_room", "channel_id", {channel_id: params.channel_id}).get()
if (row == null) {
throw createError({
status: 403,
data: `The file you requested isn't permitted by this media proxy.`
})
}
const row = select("channel_room", "channel_id", {channel_id: params.channel_id}).get()
if (row == null) {
throw createError({
status: 403,
data: `The file you requested isn't permitted by this media proxy.`
})
}
const url = `https://cdn.discordapp.com/attachments/${params.channel_id}/${params.attachment_id}/${params.file_name}`
let promise = cache.get(url)
/** @type {string | undefined} */
let refreshed
if (promise) {
refreshed = await promise
if (!timeUntilExpiry(refreshed)) promise = undefined
}
if (!promise) {
promise = discord.snow.channel.refreshAttachmentURLs([url]).then(x => x.refreshed_urls[0].refreshed)
cache.set(url, promise)
refreshed = await promise
const time = timeUntilExpiry(refreshed)
assert(time) // the just-refreshed URL will always be in the future
setTimeout(() => {
cache.delete(url)
}, time).unref()
}
assert(refreshed) // will have been assigned by one of the above branches
const url = `https://${domain}/attachments/${params.channel_id}/${params.attachment_id}/${params.file_name}`
let promise = cache.get(url)
/** @type {string | undefined} */
let refreshed
if (promise) {
refreshed = await promise
if (!timeUntilExpiry(refreshed)) promise = undefined
}
if (!promise) {
promise = discord.snow.channel.refreshAttachmentURLs([url]).then(x => x.refreshed_urls[0].refreshed)
cache.set(url, promise)
refreshed = await promise
const time = timeUntilExpiry(refreshed)
assert(time) // the just-refreshed URL will always be in the future
setTimeout(() => {
cache.delete(url)
}, time).unref()
}
assert(refreshed) // will have been assigned by one of the above branches
return sendRedirect(event, refreshed)
}))
return sendRedirect(event, refreshed)
})
}
as.router.get(`/download/discordcdn/:channel_id/:attachment_id/:file_name`, defineMediaProxyHandler("cdn.discordapp.com"))
as.router.get(`/download/discordmedia/:channel_id/:attachment_id/:file_name`, defineMediaProxyHandler("media.discordapp.net"))