S3 for other controolers
This commit is contained in:
@@ -1,109 +1,148 @@
|
||||
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");
|
||||
var convertapi = require('convertapi')('6zZB0nquI5V3P3Vg');
|
||||
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) => {
|
||||
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 data = { title: req.body.title };
|
||||
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 filePath = `./static/uploads/pdf/${fileName}`;
|
||||
|
||||
await file.mv(filePath);
|
||||
data.file = fileName;
|
||||
|
||||
const convertPromise = convertapi.convert('jpg', {
|
||||
File: filePath
|
||||
}, 'pdf');
|
||||
|
||||
const result = await convertPromise;
|
||||
const savedFiles = await result.saveFiles(`./static/uploads/books/${imageName}.jpeg`);
|
||||
|
||||
const imagePath = `https://ostan-mr.ir/uploads/books/${imageName}.jpeg`;
|
||||
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 });
|
||||
} else {
|
||||
const newBook = new Book({
|
||||
title: req.body.title,
|
||||
uri: `https://ostan-mr.ir/uploads/pdf/${fileName}`,
|
||||
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 });
|
||||
}
|
||||
[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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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.deleteOne({_id:req.params.id})
|
||||
if(!book){
|
||||
return res.status(200).json({ msg: 'کتاب وجود ندارد ' });
|
||||
}
|
||||
return res.status(200).json({ msg: 'کتاب حذف شد' });
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
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);
|
||||
}
|
||||
]
|
||||
},
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user