const {body, validationResult} = require('express-validator'); const sharp = require('sharp'); const {_sr} = require('../plugins/serverResponses'); const {res404, res500, hasWhiteSpaces, isLatinCharactersWithSymbol, generateRandomDigits} = require('../plugins/controllersHelperFunctions'); const Content = require('../models/Content'); const fs = require('fs'); ////// variables const profileWidth = 1000; const profileHeight = 600; const profileQuality = 100; const profileThumbWidth = 400; const profileThumbHeight = 400; const profileThumbQuality = 100; /////////////////////////////////////////////////////////////////////// admin module.exports.addContent = [ [ body('title') .notEmpty().withMessage(_sr['fa'].required.title), body('param') .notEmpty().withMessage(_sr['fa'].required.field), body('pageContent') .notEmpty().withMessage(_sr['fa'].required.field), body('showInMenu') .optional().isBoolean().withMessage(_sr['fa'].format.boolean), ], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) return res.status(422).json({ validation: errors.mapped() }); try { let { title, param, pageContent, email, showInMenu } = req.body; const catData = { title: title.trim(), param: param, pageContent: pageContent, showInMenu, _creator: req.user._id, _updatedBy: req.user._id } if (email) catData.email = email /** * add new content */ let create = await Content.create(catData); /** * check added or not */ if (!create) { return res500(res, `مشکلی در اضافه کردن محتوا پیش آمده است`); } /** * if we have pic upload to server */ if (req.files && req.files.cover) { const image = req.files.cover; if (!_sr.supportedImageFormats.includes(image.mimetype.split('/')[1])) { return res.status(422).json({ validation: { cover: { msg: _sr['fa'].format.image } } }); } const imageName = `manager_${Date.now()}_${create._id}.${image.mimetype.split('/')[1]}`; const thumbName = 'thumb_' + imageName try { const target = sharp(image.data) await target .resize(profileWidth, profileHeight, { fit: 'cover' }) .jpeg({ quality: profileQuality }) .toFile(`./static/uploads/images/content/${imageName}`) await target .resize(profileThumbWidth, profileThumbHeight, { fit: 'cover' }) .jpeg({ quality: profileThumbQuality }) .toFile(`./static/uploads/images/content/${thumbName}`) create.cover = imageName; create.thumb = imageName; await create.save(); } catch (e) { return res500(res, e?.message); } } /** * show result */ return res.json(create); } catch (error) { res500(res, error.message); } } ] module.exports.updateContent = [ [ body('title') .notEmpty().withMessage(_sr['fa'].required.title), body('pageContent') .notEmpty().withMessage(_sr['fa'].required.field), body('showInMenu') .optional().isBoolean().withMessage(_sr['fa'].format.boolean), ], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) return res.status(422).json({ validation: errors.mapped() }); try { /** * get data from input */ let { title, pageContent, email, showInMenu } = req.body; /** * get id */ var contentParam = req.params.param; /** * check content exist or not */ var targetContent = await Content.findOne({param: contentParam}); if (!targetContent) return res404(res, `صفحه ی مورد نظر پیدا نشد`); /** * if we have pic upload to server */ if (req.files && req.files.cover) { const image = req.files.cover; if (!_sr.supportedImageFormats.includes(image.mimetype.split('/')[1])) { return res.status(422).json({ validation: { cover: { msg: _sr['fa'].format.image } } }); } const imageName = `manager_${Date.now()}_${targetContent._id}.${image.mimetype.split('/')[1]}`; const thumbName = 'thumb_' + imageName try { const target = sharp(image.data) await target .resize(profileWidth, profileHeight, { fit: 'cover' }) .jpeg({ quality: profileQuality }) .toFile(`./static/uploads/images/content/${imageName}`) await target .resize(profileThumbWidth, profileThumbHeight, { fit: 'cover' }) .jpeg({ quality: profileThumbQuality }) .toFile(`./static/uploads/images/content/${thumbName}`) /** * if exist old pic delete it from file */ if (targetContent.cover) { const oldPic = `./static${targetContent.cover}` const oldThumb = `./static${targetContent.thumb}` if (fs.existsSync(oldPic)) { fs.unlink(oldPic, (err) => { if (err) return res500(res, err?.message); }); } if (fs.existsSync(oldThumb)) { fs.unlink(oldThumb, (err) => { if (err) return res500(res, err?.message); }); } } targetContent.cover = imageName; targetContent.thumb = thumbName; } catch (e) { return res500(res, e?.message); } } /** * make update object */ targetContent.title = title.trim(); targetContent._updatedBy = req.user._id; targetContent.pageContent = pageContent; targetContent.showInMenu = showInMenu || false; if (email) targetContent.email = email await targetContent.save(); /** * show result */ return res.json(targetContent); } catch (error) { return res500(res, error?.message); } } ] module.exports.getOneContent = [ async (req, res) => { try { var contentParam = req.params.param; /** * get content */ const targetContent = await Content.findOne({param: contentParam}); /** * show result */ return res.json(targetContent); } catch (error) { return res500(res, error?.message); } } ] /////////////////////////////////////////////////////////////////////// public module.exports.footer = [ async (req, res) => { try { var findQuery = {showInFooter: {$ne: 0}}; var getContents = await Content.find(findQuery).sort({priority: -1}); return res.json(getContents); } catch (error) { return res500(res, error?.message); } } ] module.exports.viewContent = [ async (req, res) => { try { var param = req.params.param; var getContent = await Content.findOne({param}); if (!getContent) { return res404(res, `صفحه ی مورد نظر پیدا نشد`); } return res.json(getContent); } catch (error) { return res500(res, error?.message); } } ]