backend/src/utils/upload.ts

40 lines
1.5 KiB
TypeScript
Raw Normal View History

import * as fs from 'node:fs'
const keys = JSON.parse(fs.readFileSync('s3.json', 'utf-8'))
async function uploadVideo(video: string) {
2026-01-07 19:55:23 +00:00
const uploaded = await fetch(`${keys.endpoint}/preservetube/${video.split('/')[2]}`, {
2026-01-07 19:48:04 +00:00
method: 'PUT',
headers: {
'x-authtoken': keys.videos[0].secret
},
body: await Bun.file(video).arrayBuffer()
})
2026-03-22 14:18:55 +00:00
if (!uploaded.ok) throw new Error(`failed to upload video - ${uploaded.status} (${uploaded.statusText}) ${await uploaded.text()}`)
2026-03-08 22:12:28 +00:00
return uploaded.url.replace(keys.endpoint, 'https://s5.archive.party')
}
async function uploadImage(id: string, url: string) {
const response = await fetch(url)
2026-01-07 19:48:04 +00:00
const arrayBuffer = await response.arrayBuffer()
const bufferHash = Bun.hash(Buffer.from(arrayBuffer)).toString()
2025-11-16 10:04:38 +00:00
2026-01-07 19:55:23 +00:00
const exists = await fetch(`${keys.endpoint}/preservetube-media/${id}-${bufferHash}.webp`, {
2026-01-07 19:48:04 +00:00
method: 'HEAD',
headers: {
'x-authtoken': keys.videos[0].secret
}
})
if (exists.status == 200) return `${keys.images[0].url}${id}-${bufferHash}.webp`
2026-01-07 19:55:23 +00:00
const uploaded = await fetch(`${keys.endpoint}/preservetube-media//${id}-${bufferHash}.webp`, {
2026-01-07 19:48:04 +00:00
method: 'PUT',
headers: {
'x-authtoken': keys.videos[0].secret
},
2026-01-07 19:50:27 +00:00
body: arrayBuffer
2026-01-07 19:48:04 +00:00
})
2026-03-22 14:18:55 +00:00
if (!uploaded.ok) throw new Error(`failed to upload video - ${uploaded.status} (${uploaded.statusText}) ${await uploaded.text()}`)
2026-03-08 22:12:28 +00:00
return uploaded.url.replace(keys.endpoint, 'https://s5.archive.party')
}
export { uploadVideo, uploadImage }