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, // 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); 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", 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}`; 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); };