Files
ostandari/server/controllers/pdfController.js
T
2026-06-19 15:47:02 +03:30

149 lines
4.2 KiB
JavaScript

const fs = require("fs/promises");
const os = require("os");
const path = require("path");
const axios = require("axios");
const { body, validationResult } = require("express-validator");
const { _sr } = require("../plugins/serverResponses");
const { checkValidations } = require("../plugins/controllersHelperFunctions");
const Book = require("../models/Book");
const {
uploadPdf,
uploadBookSlide,
deletePdf,
deleteBookSlide,
} = require("../plugins/bookImageStorage");
const convertapi = require("convertapi")("6zZB0nquI5V3P3Vg");
module.exports.AddPDF = [
[body("title").notEmpty().withMessage(_sr["fa"].required.title)],
checkValidations(validationResult),
async (req, res) => {
let tmpDir;
try {
const firstbook = [];
if (!req.files?.file) {
return res
.status(422)
.json({ validation: { file: { msg: _sr["fa"].required.file } } });
}
if (req.files?.file.mimetype.split("/")[1] !== "pdf") {
return res
.status(422)
.json({ validation: { file: { msg: "فقط فرمت PDF قابل قبول است" } } });
}
const book = await Book.findById(req.body.bookId);
const bookId = book ? book._id : null;
const file = req.files.file;
const fileName =
req.body.title.replace(Date.now(), "-") + "_" + Date.now() + ".pdf";
const imageName =
req.body.title.replace(Date.now(), "-") + "_" + Date.now();
const { url: pdfUrl } = await uploadPdf(file.data, fileName);
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "book-"));
const tmpPdfPath = path.join(tmpDir, fileName);
await fs.writeFile(tmpPdfPath, file.data);
const result = await convertapi.convert(
"jpg",
{ File: tmpPdfPath },
"pdf"
);
const convertedResponse = await axios.get(result.files[0].url, {
responseType: "arraybuffer",
});
const imagePath = await uploadBookSlide(
Buffer.from(convertedResponse.data),
imageName
);
firstbook.push(imagePath);
if (bookId) {
const update = await Book.findByIdAndUpdate(
{ _id: bookId },
{ $push: { slides: imagePath } },
{ upsert: true }
);
return res
.status(201)
.json({ msg: "اسلاید کتاب اضافه شد", Data: update });
}
const newBook = new Book({
title: req.body.title,
uri: pdfUrl,
slides: firstbook,
});
await newBook.save();
return res.status(201).json({ msg: "کتاب ایجاد شد", Data: newBook });
} catch (error) {
console.error(error);
return res.status(500).json({
msg: "خطایی در پردازش فایل رخ داد",
error: error.message,
});
} finally {
if (tmpDir) {
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
}
}
},
];
module.exports.GetAll = [
async (req, res, next) => {
try {
const Books = await Book.find({});
return res.status(200).json({ Books });
} catch (error) {
next(error);
}
},
];
module.exports.GetOne = [
async (req, res, next) => {
try {
const id = req.params.id;
const book = await Book.findById(id);
return res.status(200).json({ msg: book });
} catch (error) {
next(error);
}
},
];
module.exports.DeleteOne = [
async (req, res, next) => {
try {
const book = await Book.findById(req.params.id);
if (!book) {
return res.status(200).json({ msg: "کتاب وجود ندارد " });
}
const uri = book.get("uri", null, { getters: false });
if (uri) {
await deletePdf(uri.split("/").pop());
}
const slides = book.get("slides", [], { getters: false }) || [];
for (const slide of slides) {
const imageName = slide.split("/").pop().replace(/\.jpeg$/i, "");
await deleteBookSlide(imageName);
}
await book.deleteOne();
return res.status(200).json({ msg: "کتاب حذف شد" });
} catch (error) {
next(error);
}
},
];