@opengis/fastify-table
Version:
core-plugins
88 lines (87 loc) • 3.07 kB
JavaScript
import path from "node:path";
import officeWrapper from "../../../plugins/grpc/office2pdf.js";
import { downloadFile, isFileExists, uploadFile, logger, pgClients, } from "../../../../utils.js";
const { officeToPdf } = officeWrapper();
const mimeTypes = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
svg: "image/svg+xml",
tiff: "image/tiff",
pdf: "application/pdf",
};
export default async function filePreview({ pg = pgClients.client, query = {}, }, reply) {
const { id, nocache } = query;
if (!id) {
return reply.status(400).send("not enough params: id");
}
const filePath = await pg
.query("select file_path from crm.files where file_id = $1", [
id.replace(/.pdf/, ""),
])
.then((el) => el.rows?.[0]?.file_path);
if (!filePath) {
logger.file("/file-preview", {
error: "File with provided id does not found",
id,
});
return reply.status(404).send("File not found");
}
const { base, ext } = path.parse(filePath);
const fileExt = ext.substring(1).toLowerCase();
const filePathPreview = filePath.replace("files/", "files/preview/");
const previewExists = await isFileExists(filePathPreview);
if (previewExists && !nocache) {
const buffer = await downloadFile(filePathPreview, { buffer: true });
return reply
.status(200)
.headers({
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="${base}.pdf"`,
})
.send(buffer);
}
const fileData = await downloadFile(filePath, { buffer: true });
if (!fileData) {
logger.file("/file-preview", {
error: "File with provided id does not found",
id,
filePath,
});
return reply.status(404).send("File not found");
}
if (!mimeTypes[fileExt] &&
!["doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv"].includes(fileExt)) {
logger.file("/file-preview", {
error: "Unsupported file type",
id,
filePath,
});
return reply.status(415).send("Unsupported file type");
}
if (!["doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv"].includes(fileExt)) {
return reply
.status(200)
.headers({
"Content-Type": mimeTypes[fileExt] || "application/octet-stream",
"Content-Disposition": `inline; filename="${base}"`,
})
.send(Buffer.from(fileData, "base64"));
}
const { file } = (await officeToPdf({
file: Buffer.from(fileData).toString("base64"),
ext: fileExt,
}));
const buffer = Buffer.from(file, "base64");
await uploadFile(filePathPreview, buffer);
return reply
.status(200)
.headers({
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="${base}.pdf"`,
})
.send(buffer);
}