MusicTopus/src/libs/aws.js

79 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2024-01-15 21:28:15 +01:00
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import fs from "fs";
import path from "path";
import axios from "axios";
import { v4 as uuid } from "uuid";
import {
awsAccessKeyId,
awsSecretAccessKey,
s3BaseFolder,
s3Endpoint,
s3Bucket,
2024-01-15 21:28:15 +01:00
// s3Signature,
} from "../config";
/**
* Fonction permettant de stocker un fichier local sur S3
* @param {String} filename
* @param {String} file
* @param {Boolean} deleteFile
*
* @return {String}
*/
export const uploadFromFile = async (filename, file, deleteFile = false) => {
const data = await fs.readFileSync(file);
const base64data = Buffer.from(data, "binary");
const dest = path.join(s3BaseFolder, filename);
2024-01-15 21:28:15 +01:00
const multipartUpload = new Upload({
client: new S3Client({
region: "fr-par",
endpoint: `https://${s3Endpoint}`,
credentials: {
accessKeyId: awsAccessKeyId,
secretAccessKey: awsSecretAccessKey,
},
}),
params: {
Bucket: s3Bucket,
Key: dest,
Body: base64data,
ACL: "public-read",
2024-01-15 21:28:15 +01:00
endpoint: s3Endpoint,
},
});
await multipartUpload.done();
if (deleteFile) {
fs.unlinkSync(file);
}
return `https://${s3Bucket}.${s3Endpoint}/${dest}`;
};
/**
* Fonction permettant de stocker un fichier provenant d'une URL sur S3
* @param {String} url
*
* @return {String}
*/
export const uploadFromUrl = async (url) => {
const filename = `${uuid()}.jpg`;
const file = `/tmp/${filename}`;
2023-09-18 14:31:51 +02:00
const { data } = await axios.get(url, {
headers: {
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/117.0",
},
responseType: "arraybuffer",
});
fs.writeFileSync(file, data);
return uploadFromFile(filename, file, true);
};