Skip to content

Commit

Permalink
att
Browse files Browse the repository at this point in the history
  • Loading branch information
Th0mzzz committed Sep 10, 2024
1 parent fdbc59d commit 79c0191
Show file tree
Hide file tree
Showing 31 changed files with 284 additions and 830 deletions.
19 changes: 8 additions & 11 deletions app/controller/resenhasController.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,14 @@ const resenhaControl = {
],
postarResenha: async (req, res) => {
let errors = validationResult(req)
let erroMulter = req.session.erroMulter;
if (!errors.isEmpty() || erroMulter != null) {
let errosMulter = req.session.erroMulter;
if (!errors.isEmpty() || errosMulter.length > 0) {

if(!errors.isEmpty()){
var listaErros = errors
}else{
var listaErros = { formatter: null, errors: [] }
}
if (erroMulter != null) {
listaErros.errors.push(erroMulter)
removeImg(`./app/public/img/imagens-servidor/capaImg/${req.file.filename}`)
let listaErros = errors.isEmpty() ? { formatter: null, errors: [] } : errors;

if (errosMulter.length > 0) {
listaErros.errors.push(...errosMulter)
if(req.file){removeImg(`./app/public/img/imagens-servidor/capaImg/${req.file.filename}`)}
}
console.log(listaErros)

Expand Down Expand Up @@ -56,7 +53,7 @@ const resenhaControl = {
res.redirect(`/view-resenha?idResenha=${resultado.insertId}`)
} catch (error) {
console.log(error)
// ADD FUNCTION REMOVEIMG() para o caminho salvo no banco
if(req.file){removeImg(`./app/public/img/imagens-servidor/capaImg/${req.file.filename}`)}
res.render("pages/error-500")
}

Expand Down
6 changes: 3 additions & 3 deletions app/controller/usuariosController.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,9 @@ const usuariosController = {
}

const posts = {
resenhas: resenhasUser,
videos: [],
fichas: [],
resenhas: resenhasUser.length == 0 ? null : resenhasUser,
videos: null,
fichas: null,
}
const jsonResult = {
page: "../partial/template-home/perfil-home",
Expand Down
104 changes: 104 additions & 0 deletions app/controller/videosController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const { body, validationResult } = require("express-validator");
const usuariosModel = require("../models/usuariosModel");
const { removeImg } = require("../util/removeImg");
const videosModel = require("../models/videosModel");

const videoControl = {
validacaoVideo: [
body("tituloVideo")
.isLength({ min: 3, max: 45 }).withMessage("O título deve ter no minimo 3 caracteres e no máximo 45!")
,
body("descricao")
.isLength({ min: 3, max: 400 }).withMessage("A descrição deve ter entre 3 e 400 caracteres!")
],
postarVideo: async (req, res) => {
let errors = validationResult(req)
let errosMulter = req.session.erroMulter;

if (!errors.isEmpty() || errosMulter.length > 0) {

let listaErros = errors.isEmpty() ? { formatter: null, errors: [] } : errors;

if (errosMulter.length > 0) {
listaErros.errors.push(...errosMulter)
if (req.file) removeImg(`./app/public/img/imagens-servidor/videos/${req.file.filename}`)
}
console.log(listaErros)

const jsonResult = {
page: "../partial/template-home/pub-pages/videos-pub",
classePagina: "publicar",
erros: listaErros,
valores: req.body,
token: null,
foto: req.session.autenticado ? req.session.autenticado.foto : "perfil-padrao.webp",

}
res.render("./pages/template-home", jsonResult)
} else {
try {
const capaFile = req.files && req.files.find(file => file.fieldname === 'capaVideo') ? req.files.find(file => file.fieldname === 'capaVideo') : null;
const videoFile = req.files && req.files.find(file => file.fieldname === 'video') ? req.files.find(file => file.fieldname === 'video') : null;
const { titulo, descricao, tags } = req.body
const video = {
NOME_VIDEO: titulo,
DESCR_VIDEO: descricao,
HASHTAG_VIDEO: [tags].toString(),
CAPA_VIDEO: capaFile.filename,
CAMINHO_VIDEO: videoFile.filename,
USUARIOS_ID_USUARIO: req.session.autenticado.id,
}
const resultado = await videosModel.create(video)
console.log(resultado)
res.redirect(`/view-resenha?idResenha=${resultado.insertId}`)
} catch (error) {
console.log(error)
if (req.file) { removeImg(`./app/public/img/imagens-servidor/capaImg/${req.file.filename}`) }
res.render("pages/error-500")
}


}
},
mostrarVideo: async (req, res) => {
let idVideo = req.query.idVideo
// if (!idVideo) {
// const videos = await pool.query("SELECT * FROM VIDEOS LIMIT 10")
// }

try {
const video = await videosModel.buscarPorId(idVideo)
if (video) {
const autor = await usuariosModel.findUserById(video.USUARIOS_ID_USUARIO)
if (autor) {

const jsonResult = {
video: {
titulo: video.NOME_VIDEO,
descricao: video.DESCR_VIDEO,
tags: video.HASHTAG_RESENHA.split(","),
video:video.CAMINHO_VIDEO,
autor: autor[0]
},
}

res.render("./pages/videos-home", jsonResult)
} else {
res.status(404).render("pages/error-404.ejs");
}
} else {
res.status(404).render("pages/error-404.ejs");
}

} catch (error) {
console.log(error)
res.status(404).render("pages/error-404.ejs");
}

}


}


module.exports = videoControl
2 changes: 1 addition & 1 deletion app/models/fichasModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var pool = require("../../config/poolConn");
const fichasModel = {
create: async (dadosFicha)=>{
try {
const [resultados] = await pool.query("insert into set ?", [dadosFicha])
const [resultados] = await pool.query("insert into FICHAS set ?", [dadosFicha])
return resultados
} catch (error) {
return error
Expand Down
13 changes: 12 additions & 1 deletion app/models/videosModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var pool = require("../../config/poolConn");
const videosModel = {
create: async (dadosVideo)=>{
try {
const [resultados] = await pool.query("insert into set ?", [dadosVideo])
const [resultados] = await pool.query("insert into VIDEOS set ?", [dadosVideo])
return resultados
} catch (error) {
return error
Expand All @@ -18,6 +18,17 @@ const videosModel = {
return error
}
},
buscarPorId: async (idUser) => {
try {
const [resultado] = await pool.query("SELECT * FROM VIDEOS WHERE USUARIOS_ID_USUARIO = ?", [idUser])
return resultado[0]
} catch (error) {
console.log("erro no buscar ID")
console.log(error)
return error
}
},

}

module.exports = videosModel;
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 5 additions & 5 deletions app/public/js/addCapa.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const capaContainer = document.querySelector("[data-capaContainer]");
const inputFileCapa = document.querySelector("[data-inputCapa]");
const maxFileSize = 2 * 1024 * 1024;
const aspectRatio = inputFileCapa.classList.contains("capaResenha") ? 4 / 3 : 9 / 16 ;
const margemErro = 0.2
const aspectRatio = inputFileCapa.classList.contains("capaResenha") ? 4 / 3 : 2 / 3;
const margemErro = 1
inputFileCapa.addEventListener("change", function (e) {
e.preventDefault();
const file = e.target.files[0];
Expand All @@ -20,9 +20,9 @@ inputFileCapa.addEventListener("change", function (e) {
const img = new Image();
img.onload = function () {
const imgAspectRatio = img.width / img.height;
if (Math.abs(imgAspectRatio - aspectRatio) > margemErro) {
if (Math.abs(imgAspectRatio - aspectRatio) > margemErro) {
inputFileCapa.parentNode.classList.add("invalid");
inputFileCapa.parentNode.querySelector(".invalid-msg").textContent = inputFileCapa.classList.contains("capaResenha") ? "A proporção da imagem deve ser 4:3." : 'A proporção da imagem deve ser 9:16.';
inputFileCapa.parentNode.querySelector(".invalid-msg").textContent = inputFileCapa.classList.contains("capaResenha") ? "A proporção da imagem deve ser 4:3" : 'A proporção da imagem deve ser 2:3.';
inputFileCapa.value = "";
return;
}
Expand All @@ -41,7 +41,7 @@ inputFileCapa.addEventListener("change", function (e) {
};
img.src = src;
};
reader.readAsDataURL(file);
reader.readAsDataURL(file);
} else {
inputFileCapa.parentNode.classList.add("invalid");
inputFileCapa.parentNode.querySelector(".invalid-msg").textContent = 'Escolha um arquivo do tipo Imagem!!';
Expand Down
41 changes: 34 additions & 7 deletions app/routes/routerHome.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ const usuariosController = require("../controller/usuariosController");
const resenhaControl = require("../controller/resenhasController");
// UTIL ---------------
const upload = require("../util/upload");
const uploadCapa = upload("./app/public/img/imagens-servidor/capas-img/", 5, ['jpeg', 'jpg', 'png']);
const videoControl = require("../controller/videosController");
const uploadCapaResenha = upload("./app/public/img/imagens-servidor/capas-img/", 5, ['jpeg', 'jpg', 'png']);
const uploadCapaVideo = upload("./app/public/img/imagens-servidor/capas-img/", 5, ['jpeg', 'jpg', 'png']);
const uploadVideo = upload("./app/public/img/imagens-servidor/videos/", 400, ['mp4']);


// Página de falha de autenticação ---------
Expand All @@ -28,11 +31,11 @@ router.get("/", function (req, res) {
let token = null
if (req.session.logado == 0 && req.session.autenticado.autenticado != null) {
let msg = "Muito bom te ter de volta,"
if(req.session.cadastro){msg = "Bem-vindo(a) ao Quasart,"}
if (req.session.cadastro) { msg = "Bem-vindo(a) ao Quasart," }
token = { msg: msg, usuario: req.session.autenticado.autenticado }
req.session.logado = req.session.logado + 1
}

const jsonResult = {
foto: req.session.autenticado ? req.session.autenticado.foto : "perfil-padrao.webp",
page: "../partial/template-home/inicial-home",
Expand Down Expand Up @@ -167,8 +170,9 @@ router.get("/sobre", function (req, res) {
})

// --------- PAGINA DE VIDEOS ----------

router.get("/videos", function (req, res) {
res.render("./pages/videos-home")
videoControl.mostrarVideo(req,res)
});


Expand All @@ -191,9 +195,32 @@ router.get("/view-ficha", function (req, res) {


// Form de criação de Resenha
router.post("/criarResenha", uploadCapa("capaResenha"), resenhaControl.validacaoResenha, function (req, res) {
resenhaControl.postarResenha(req, res)
})
router.post("/criarResenha",
(req, res, next) => {
req.session.erroMulter = [];
next();
},
middleWares.verifyAutenticado,
middleWares.verifyAutorizado("pages/template-login", destinoDeFalha),
uploadCapaResenha("capaResenha"),
resenhaControl.validacaoResenha,
function (req, res) {
resenhaControl.postarResenha(req, res)
});

router.post("/criarVideo",
(req, res, next) => {
req.session.erroMulter = [];
next();
},
middleWares.verifyAutenticado,
middleWares.verifyAutorizado("pages/template-login", destinoDeFalha),
uploadCapaVideo("capaVideo"),
uploadVideo("video"),
videoControl.validacaoVideo,
function (req, res) {
videoControl.postarVideo(req, res)
})


module.exports = router;
46 changes: 26 additions & 20 deletions app/util/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ const validarProporcaoImagem = async (buffer, proportion, margemErro) => {
const { width, height } = metadata;
const imageProporcao = width / height;
if (Math.abs(imageProporcao - proportion) > margemErro) {
console.log("Testando proporção")
console.log(Math.abs(imageProporcao - proportion) > margemErro)
console.log(Math.abs(imageProporcao - proportion))
console.log(margemErro)
return false
}
return true
Expand Down Expand Up @@ -72,41 +76,43 @@ module.exports = (caminho = null, tamanhoArq = 3, extensoesPermitidas = ['jpeg',
fileFilter: fileFilter
});
}
req.session.erroMulter = null
if (!req.session.erroMulter) {
req.session.erroMulter = [];
}

upload.single(campoArquivo)(req, res, async function (err) {
if (err instanceof multer.MulterError) {
req.session.erroMulter = {
req.session.erroMulter.push({
value: '',
msg: err.message,
path: campoArquivo
}
});
} else if (err) {
req.session.erroMulter = {
req.session.erroMulter.push({
value: '',
msg: err.message,
path: campoArquivo
}
} else if (req.file && caminho == null) {
});
} else if (req.file) {
try {
const isProporcaoValida = true;
if (proportion && margemErro) { isProporcaoValida = await validarProporcaoImagem(req.file.buffer, proportion, margemErro); }
if (proportion != null && margemErro != null) {
isProporcaoValida = await validarProporcaoImagem(req.file.buffer, proportion, margemErro);

if (!isProporcaoValida) {
req.session.erroMulter = {
value: '',
msg: 'A imagem deve seguir a proporção exigida!.',
path: campoArquivo
};
if (!isProporcaoValida) {
req.session.erroMulter.push({
value: '',
msg: 'A imagem deve seguir a proporção exigida!',
path: campoArquivo
});
}
}
} catch (error) {
if (!isProporcaoValida) {
req.session.erroMulter = {
value: '',
msg: error.message,
path: campoArquivo
};
}
req.session.erroMulter.push({
value: '',
msg: 'A imagem deve seguir a proporção exigida!',
path: campoArquivo
});
}
}
next();
Expand Down
Loading

0 comments on commit 79c0191

Please sign in to comment.