2023-03-28 14:52:17 +00:00
|
|
|
const AWS = require('aws-sdk')
|
|
|
|
const fs = require('node:fs')
|
|
|
|
|
|
|
|
const keys = require('../s3.json')
|
|
|
|
|
|
|
|
async function uploadVideo(video) {
|
2023-07-17 20:20:49 +00:00
|
|
|
const key = keys.videos[0]
|
2023-03-28 14:52:17 +00:00
|
|
|
|
|
|
|
const s3 = new AWS.S3({
|
|
|
|
accessKeyId: key.access,
|
|
|
|
secretAccessKey: key.secret,
|
2023-07-17 20:20:49 +00:00
|
|
|
endpoint: keys.endpoint,
|
|
|
|
s3ForcePathStyle: true
|
2023-03-28 14:52:17 +00:00
|
|
|
})
|
|
|
|
|
2023-06-04 10:34:27 +00:00
|
|
|
const videoFile = fs.createReadStream(video)
|
2023-07-17 20:20:49 +00:00
|
|
|
const uploaded = await s3.upload({
|
|
|
|
Bucket: key.bucket,
|
2023-03-28 14:52:17 +00:00
|
|
|
Key: video.split('/')[2],
|
|
|
|
Body: videoFile,
|
|
|
|
ContentType: 'video/webm',
|
|
|
|
}).promise()
|
|
|
|
|
2023-07-17 20:20:49 +00:00
|
|
|
return uploaded.Location
|
2023-03-28 14:52:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function uploadImage(id, url) {
|
2023-07-17 20:20:49 +00:00
|
|
|
const key = keys.images[0]
|
2023-03-28 14:52:17 +00:00
|
|
|
|
|
|
|
const s3 = new AWS.S3({
|
|
|
|
accessKeyId: key.access,
|
|
|
|
secretAccessKey: key.secret,
|
2023-07-17 20:20:49 +00:00
|
|
|
endpoint: keys.endpoint,
|
|
|
|
s3ForcePathStyle: true
|
2023-03-28 14:52:17 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
const exists = await checkIfFileExists({
|
2023-07-17 20:20:49 +00:00
|
|
|
Bucket: key.bucket,
|
2023-03-28 14:52:17 +00:00
|
|
|
Key: `${id}.webp`
|
|
|
|
}, s3)
|
|
|
|
|
|
|
|
if (exists) {
|
|
|
|
return `${key.url}${id}.webp`
|
|
|
|
} else {
|
|
|
|
const response = await fetch(url)
|
|
|
|
const buffer = Buffer.from(await response.arrayBuffer())
|
|
|
|
|
2023-07-17 20:20:49 +00:00
|
|
|
const uploaded = await s3.upload({
|
|
|
|
Bucket: key.bucket,
|
2023-03-28 14:52:17 +00:00
|
|
|
Key: `${id}.webp`,
|
|
|
|
Body: buffer,
|
|
|
|
ContentType: 'video/webp',
|
|
|
|
}).promise()
|
|
|
|
|
2023-07-17 20:20:49 +00:00
|
|
|
return uploaded.Location
|
2023-03-28 14:52:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function checkIfFileExists(params, s3) {
|
|
|
|
try {
|
|
|
|
await s3.headObject(params).promise()
|
|
|
|
return true
|
|
|
|
} catch (err) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = { uploadVideo, uploadImage }
|