113 lines
2.7 KiB
JavaScript
113 lines
2.7 KiB
JavaScript
const path = require("path");
|
|
const _ = require("lodash");
|
|
require("dotenv").config({
|
|
path: path.resolve(
|
|
process.cwd(),
|
|
`.env.${process.env.NODE_ENV || "development"}`
|
|
),
|
|
});
|
|
|
|
var cloudinary = require("cloudinary").v2;
|
|
cloudinary.config(process.env.CLOUDINARY_URL);
|
|
|
|
exports.createSignedUploadURL = (req, res) => {
|
|
console.log("Request to create signed upload URL for Cloudinary.", req.body);
|
|
|
|
res.send(
|
|
cloudinary.utils.api_sign_request(
|
|
req.body,
|
|
process.env.CLOUDINARY_API_SECRET
|
|
)
|
|
);
|
|
};
|
|
|
|
exports.downloadFiles = (req, res) => {
|
|
const { ids } = req.body;
|
|
|
|
const url = cloudinary.utils.download_zip_url({
|
|
public_ids: ids,
|
|
flatten_folders: true,
|
|
});
|
|
res.send(url);
|
|
};
|
|
|
|
exports.deleteFiles = async (req, res) => {
|
|
const { ids } = req.body;
|
|
const types = _.groupBy(ids, (x) => DetermineFileType(x.type));
|
|
console.log("🚀 ~ file: media.js ~ line 28 ~ types", types);
|
|
|
|
const returns = [];
|
|
if (types.image) {
|
|
//delete images
|
|
|
|
returns.push(
|
|
await cloudinary.api.delete_resources(
|
|
types.image.map((x) => x.key),
|
|
{ resource_type: "image" }
|
|
)
|
|
);
|
|
}
|
|
if (types.video) {
|
|
//delete images returns.push(
|
|
returns.push(
|
|
await cloudinary.api.delete_resources(
|
|
types.video.map((x) => x.key),
|
|
{ resource_type: "video" }
|
|
)
|
|
);
|
|
}
|
|
if (types.raw) {
|
|
//delete images returns.push(
|
|
returns.push(
|
|
await cloudinary.api.delete_resources(
|
|
types.raw.map((x) => x.key),
|
|
{ resource_type: "raw" }
|
|
)
|
|
);
|
|
}
|
|
console.log("🚀 ~ file: media.js ~ line 40 ~ returns", returns);
|
|
|
|
res.send(returns);
|
|
};
|
|
|
|
exports.renameKeys = async (req, res) => {
|
|
const { documents } = req.body;
|
|
//{id: "", from: "", to:""}
|
|
const proms = [];
|
|
console.log("Documents", documents);
|
|
documents.forEach((d) => {
|
|
proms.push(
|
|
(async () => {
|
|
try {
|
|
const res = {
|
|
id: d.id,
|
|
...(await cloudinary.uploader.rename(d.from, d.to, {
|
|
resource_type: DetermineFileType(d.type),
|
|
})),
|
|
};
|
|
return res;
|
|
} catch (error) {
|
|
return { id: d.id, from: d.from, error: error };
|
|
}
|
|
})()
|
|
);
|
|
});
|
|
|
|
let result;
|
|
|
|
result = await Promise.all(proms);
|
|
|
|
res.send(result);
|
|
};
|
|
|
|
//Also needs to be updated in upload utility and mobile app.
|
|
function DetermineFileType(filetype) {
|
|
if (!filetype) return "auto";
|
|
else if (filetype.startsWith("image")) return "image";
|
|
else if (filetype.startsWith("video")) return "video";
|
|
else if (filetype.startsWith("application/pdf")) return "image";
|
|
else if (filetype.startsWith("application")) return "raw";
|
|
|
|
return "auto";
|
|
}
|