const Links = require('../models/Links'); 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 fs = require('fs'); ////// variables const profileWidth = 50; const profileHeight = 50; const profileQuality = 100; /////////////////////////////////////////////////////////////////////// admin module.exports.addLinks = [ [ body('title') .notEmpty().withMessage(_sr['fa'].required.title), body('url') .notEmpty().withMessage(_sr['fa'].required.field), body('index') .optional().isNumeric().withMessage(_sr['fa'].format.number), body('showInHome') .isBoolean().withMessage(_sr['fa'].format.boolean), body('siteMap') .optional().isBoolean().withMessage(_sr['fa'].format.boolean), body('modelType') .custom((value, { req }) => { if (req.user.portals.join() === portal.join()) { if (!portal.includes(value)) { return Promise.reject(_sr['fa'].required.field); } else { return true } } else { return true } }) ], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) return res.status(422).json({ validation: errors.mapped() }); try { let { title, url, index, showInHome, siteMap, modelType, } = req.body; /** set portals */ modelType = (req.user.portals.join() === portal.join()) ? modelType : req.user.portals[0]; const linksData = { title : title.trim(), url : url.trim(), index, showInHome, siteMap, _creator: req.user._id, _updatedBy: req.user._id, modelType, }; var createLinks = await Links.create(linksData); if (!createLinks) { res500(res, `error in add links to data base`); } /** * if we have pic upload to server */ if (req.files && req.files.icon) { const image = req.files.icon; if (!_sr.supportedImageFormats.includes(image.mimetype.split('/')[1])) { return res.status(422).json({ validation: { cover: { msg: _sr['fa'].format.image } } }); } const imageName = `links_${Date.now()}_${createLinks._id}.${image.mimetype.split('/')[1]}`; try { const target = sharp(image.data) await target .resize(profileWidth, profileHeight, { fit: 'cover' }) .jpeg({ quality: profileQuality }) .toFile(`./static/uploads/images/links/${imageName}`); createLinks.icon = imageName; await createLinks.save(); } catch (e) { return res500(res, e?.message); } } /** * show result */ return res.json(createLinks); } catch (error) { /** * if we got unkown error show to client */ res500(res, error.message); } } ] module.exports.updateLinks = [ [ body('title') .notEmpty().withMessage(_sr['fa'].required.title), body('url') .notEmpty().withMessage(_sr['fa'].required.field), body('index') .optional().isNumeric().withMessage(_sr['fa'].format.number), body('showInHome') .isBoolean().withMessage(_sr['fa'].format.boolean), body('siteMap') .optional().isBoolean().withMessage(_sr['fa'].format.boolean), body('modelType') .custom((value, { req }) => { if (req.user.portals.join() === portal.join()) { if (!portal.includes(value)) { return Promise.reject(_sr['fa'].required.field); } else { return true } } else { return true } }) ], 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, url, index, showInHome, siteMap, modelType, } = req.body; /** * get id */ var linksId = req.params.id; var targetLinks = await Links.findOne({ _id: linksId }); /** check links exist or not */ if (!targetLinks) { return res404(res, `پیوند مورد نظر پیدا نشد`); } /** check access portal */ if (!req.user.portals.includes(targetLinks.modelType)) { return res500(res, `شما اجازه آپدیت این پیوند را ندارید`); } if (targetLinks.title !== title) { var checkDuppTitle = await Links.findOne({ title: title }); if (checkDuppTitle) { return res.status(422).json({ validation: { title: { msg: _sr['fa'].duplicated.title } } }); } } /** * if we have pic upload to server */ if (req.files && req.files.icon) { const image = req.files.icon; if (!_sr.supportedImageFormats.includes(image.mimetype.split('/')[1])) { return res.status(422).json({ validation: { cover: { msg: _sr['fa'].format.image } } }); } const imageName = `links_${Date.now()}_${targetLinks._id}.${image.mimetype.split('/')[1]}`; try { const target = sharp(image.data) await target .resize(profileWidth, profileHeight, { fit: 'cover' }) .jpeg({ quality: profileQuality }) .toFile(`./static/uploads/images/links/${imageName}`); /** * if exist old pic delete it from file */ if (targetLinks.icon) { var oldPic = `./static${targetLinks.icon}`; if (fs.existsSync(oldPic)) { fs.unlink(oldPic, (err) => { if (err) return res500(res, err?.message); }); } } targetLinks.icon = imageName; targetLinks.linksStatus = true; } catch (e) { return res500(res, e?.message); } } targetLinks.title = title.trim(); targetLinks.url = url.trim(); targetLinks.index = index; targetLinks.showInHome = showInHome; targetLinks.siteMap = siteMap; targetLinks.modelType = modelType; await targetLinks.save(); /** * show result */ return res.json(targetLinks); } catch (error) { return res500(res, error.message); } } ] module.exports.deletOneLinks = [ async (req, res) => { try { var linksId = req.params.id; var targetLinks = await Links.findOne({ _id: linksId }); /** check links exist or not */ if (!targetLinks) { return res404(res, `پیوند مورد نظر پیدا نشد`); } /** check access portal */ if (!req.user.portals.includes(targetLinks.modelType)) { return res500(res, `شما اجازه حذف این پیوند را ندارید`); } if (targetLinks.icon) { var oldPic = `./static${targetLinks.icon}`; if (fs.existsSync(oldPic)) { fs.unlink(oldPic, (error) => { if (error) return res500(res, error?.message); }); } } /** delete links */ await targetLinks.deleteOne(); /** * show result */ return res.json(targetLinks); } catch (error) { /** * if we got unkown error show to client */ res500(res, error); } } ] module.exports.getOneLinks = [ async (req, res) => { try { var linksId = req.params.id; var findQuery = { _id: linksId }; var links = await Links.findOne(findQuery); if (!links) { return res404(res, `پیوند مورد نظر پیدا نشد`); } /** check access portal */ if (!req.user.portals.includes(links.modelType)) { return res.status(403).json({ message: `شما اجازه دسترسی به اطلاعات این پیوند را ندارید` }); } /** * show result */ return res.json(links); } catch (error) { /** * if we got unkown error show to client */ res500(res, error); } } ] module.exports.getAll = [ async (req, res) => { try { var findQuery = {}; if (req.user.portals.length) { findQuery.modelType = { $in: req.user.portals }; } /** get all links */ const allLinks = await Links.find(findQuery).sort({ index: 1 }); /** if null we have error */ if (!allLinks) { return res500(res, `مشکلی در گرفتن اطلاعات پیش آمده است`); } /** show result to client */ return res.json(allLinks); } catch (error) { /** if we have unkown error show it */ return res500(res, error?.message); } } ] /////////////////////////////////////////////////////////////////////// public module.exports.getAllLinks = [ async (req, res) => { try { const { portal, } = req.query; let findQuery = {}; const setSort = {index: 1}; findQuery.modelType = !portal ? 'ostandari' : portal; findQuery.showInHome = true; const getLinks = await Links.find(findQuery).sort(setSort); return res.json(getLinks); } catch (error) { return res500(res, error?.message); } } ]