133 lines
4.5 KiB
JavaScript
133 lines
4.5 KiB
JavaScript
|
|
// src/utils/commentSanitizer.js
|
||
|
|
const { logInfo, logWarning } = require('./logger');
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Remove HTML tags e converte entidades HTML - CORRIGIDO
|
||
|
|
*/
|
||
|
|
const stripHTML = (html) => {
|
||
|
|
if (!html) return '';
|
||
|
|
|
||
|
|
// PRIMEIRO: converte entidades HTML para caracteres normais
|
||
|
|
let cleaned = html
|
||
|
|
.replace(/</g, '<') // < para <
|
||
|
|
.replace(/>/g, '>') // > para >
|
||
|
|
.replace(/&/g, '&') // & para &
|
||
|
|
.replace(/ /g, ' ') // para espaço
|
||
|
|
.replace(/</g, '<') // < para <
|
||
|
|
.replace(/>/g, '>') // > para >
|
||
|
|
.replace(/&/g, '&') // & para &
|
||
|
|
.replace(/"/g, '"'); // " para "
|
||
|
|
|
||
|
|
// DEPOIS: remove tags HTML
|
||
|
|
cleaned = cleaned
|
||
|
|
.replace(/<br\s*\/?>/gi, '\n') // <br> para quebra de linha
|
||
|
|
.replace(/<p>/gi, '') // Remove <p>
|
||
|
|
.replace(/<\/p>/gi, '\n\n') // </p> para duas quebras
|
||
|
|
.replace(/<strong>/gi, '**') // <strong> para **
|
||
|
|
.replace(/<\/strong>/gi, '**') // </strong> para **
|
||
|
|
.replace(/<em>/gi, '*') // <em> para *
|
||
|
|
.replace(/<\/em>/gi, '*') // </em> para *
|
||
|
|
.replace(/<blockquote>/gi, '> ') // <blockquote> para citação
|
||
|
|
.replace(/<\/blockquote>/gi, '') // </blockquote>
|
||
|
|
.replace(/<div[^>]*>/gi, '') // Remove <div> com qualquer atributo
|
||
|
|
.replace(/<\/div>/gi, '\n') // </div> para quebra
|
||
|
|
.replace(/<[^>]*>/g, '') // Remove todas outras tags HTML
|
||
|
|
.replace(/\n\s*\n\s*\n/g, '\n\n') // Remove múltiplas quebras
|
||
|
|
.replace(/^\s+|\s+$/g, '') // Remove espaços no início/fim
|
||
|
|
.trim();
|
||
|
|
|
||
|
|
return cleaned;
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Detecta e trata imagens do GLPI
|
||
|
|
*/
|
||
|
|
const handleImages = (content) => {
|
||
|
|
const imgRegex = /<img[^>]+src="([^"]+)"[^>]*>/gi;
|
||
|
|
const hasImages = imgRegex.test(content);
|
||
|
|
|
||
|
|
if (hasImages) {
|
||
|
|
logWarning('📷 Imagem detectada no comentário GLPI');
|
||
|
|
// Remove toda a tag de imagem mas mantém o texto around
|
||
|
|
return content.replace(/<a[^>]*>.*?<img[^>]*>.*?<\/a>/gi, '[IMAGEM ANEXA NO GLPI]');
|
||
|
|
}
|
||
|
|
|
||
|
|
return content;
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Limpa metadados JSON do GLPI
|
||
|
|
*/
|
||
|
|
const cleanJSONMetadata = (content) => {
|
||
|
|
if (typeof content === 'string' && content.includes('{id=') && content.includes('content=')) {
|
||
|
|
try {
|
||
|
|
// Extrai o conteúdo do campo content= do objeto
|
||
|
|
const contentMatch = content.match(/content=([^,]+),/);
|
||
|
|
if (contentMatch && contentMatch[1]) {
|
||
|
|
let extracted = contentMatch[1].trim();
|
||
|
|
// Remove aspas se existirem
|
||
|
|
extracted = extracted.replace(/^['"]|['"]$/g, '');
|
||
|
|
return extracted;
|
||
|
|
}
|
||
|
|
} catch (error) {
|
||
|
|
logWarning('Não foi possível extrair conteúdo do metadado GLPI', { content });
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return content;
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Função principal de sanitização
|
||
|
|
*/
|
||
|
|
const sanitizeGLPIComment = (commentObj) => {
|
||
|
|
if (!commentObj || typeof commentObj !== 'object') {
|
||
|
|
logWarning('Comentário inválido recebido', { comment: commentObj });
|
||
|
|
return '';
|
||
|
|
}
|
||
|
|
|
||
|
|
// Pega o conteúdo do objeto comment
|
||
|
|
let content = commentObj.content || '';
|
||
|
|
|
||
|
|
// Se for string vazia, retorna vazio
|
||
|
|
if (!content) return '';
|
||
|
|
|
||
|
|
// Aplica as limpezas em sequência
|
||
|
|
content = cleanJSONMetadata(content.toString());
|
||
|
|
content = handleImages(content);
|
||
|
|
content = stripHTML(content);
|
||
|
|
|
||
|
|
// Log para debugging
|
||
|
|
if (content !== commentObj.content) {
|
||
|
|
logInfo('🔧 Comentário sanitizado', {
|
||
|
|
original: commentObj.content.substring(0, 100) + '...',
|
||
|
|
cleaned: content.substring(0, 100) + '...'
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
return content;
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Esse módulo fornece funções para sanitizar comentários importados do GLPI.
|
||
|
|
* Ele remove tags HTML, trata imagens e limpa metadados JSON específicos do GLPI.
|
||
|
|
* O objetivo é garantir que os comentários sejam legíveis e seguros para exibição.
|
||
|
|
*
|
||
|
|
* Funções principais:
|
||
|
|
* - sanitizeGLPIComment: Função principal que aplica todas as sanitizações.
|
||
|
|
* - stripHTML: Remove tags HTML e converte algumas entidades para texto simples.
|
||
|
|
* - handleImages: Detecta imagens e substitui por um marcador de imagem.
|
||
|
|
* - cleanJSONMetadata: Remove metadados JSON do GLPI, extraindo apenas o conteúdo relevante.
|
||
|
|
*
|
||
|
|
* Logs são gerados para ajudar no debugging e monitoramento do processo de sanitização.
|
||
|
|
*/
|
||
|
|
|
||
|
|
module.exports = {
|
||
|
|
sanitizeGLPIComment,
|
||
|
|
stripHTML,
|
||
|
|
handleImages,
|
||
|
|
cleanJSONMetadata
|
||
|
|
};
|
||
|
|
|
||
|
|
|
||
|
|
|