Compare commits
7
Commits
novo_provas
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f826ab223 | ||
|
|
cdc4134b16 | ||
|
|
d381d17435 | ||
|
|
ab73ea667e | ||
|
|
db7b832044 | ||
|
|
f4afe83db0 | ||
|
|
61a1631519 |
No files matched your search
@@ -0,0 +1,26 @@
|
|||||||
|
# Configurações de Manipulação de PDF
|
||||||
|
|
||||||
|
# Tamanho máximo de arquivo em MB
|
||||||
|
PDF_MAX_FILE_SIZE=100
|
||||||
|
|
||||||
|
# Número máximo de arquivos por operação
|
||||||
|
PDF_MAX_FILES_COMPRESS=10
|
||||||
|
PDF_MAX_FILES_MERGE=50
|
||||||
|
PDF_MAX_FILES_IMAGES_TO_PDF=100
|
||||||
|
|
||||||
|
# Tempo de retenção de arquivos processados em horas
|
||||||
|
PDF_FILES_RETENTION_HOURS=24
|
||||||
|
|
||||||
|
# Qualidade padrão para compressão (50-100)
|
||||||
|
PDF_DEFAULT_QUALITY=95
|
||||||
|
|
||||||
|
# DPI padrão para conversão de imagens (150-600)
|
||||||
|
PDF_DEFAULT_DPI=300
|
||||||
|
|
||||||
|
# Idioma padrão para OCR (por, eng, spa)
|
||||||
|
PDF_DEFAULT_OCR_LANGUAGE=por
|
||||||
|
|
||||||
|
# Diretórios de armazenamento (relativos ao root do projeto)
|
||||||
|
PDF_TEMP_DIR=storage/temp/pdf-ops
|
||||||
|
PDF_OUTPUT_DIR=storage/pdf-output
|
||||||
|
PDF_UPLOAD_DIR=storage/temp/uploads
|
||||||
@@ -8,6 +8,8 @@ ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
|||||||
RUN apt-get update && apt-get install -y chromium \
|
RUN apt-get update && apt-get install -y chromium \
|
||||||
libgconf-2-4 \
|
libgconf-2-4 \
|
||||||
postgresql-client \
|
postgresql-client \
|
||||||
|
graphicsmagick \
|
||||||
|
ghostscript \
|
||||||
&& rm -rf /var/lib/apt/lists/* \
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
&& ln -sf /usr/bin/chromium /usr/bin/chromium-browser
|
&& ln -sf /usr/bin/chromium /usr/bin/chromium-browser
|
||||||
|
|
||||||
|
|||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
# Passos para ativar a funcionalidade de PDF
|
||||||
|
|
||||||
|
## 1. Instalar Dependências
|
||||||
|
|
||||||
|
Execute o seguinte comando para instalar todas as dependências necessárias:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install pdf-lib pdf-parse pdf2pic tesseract.js
|
||||||
|
npm install --save-dev @types/pdf-parse
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. Executar Migration do Banco de Dados
|
||||||
|
|
||||||
|
Execute a migration para criar a tabela de operações de PDF:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx prisma migrate dev --name add_operacoes_pdf
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou simplesmente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:migrate
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. Gerar Cliente Prisma
|
||||||
|
|
||||||
|
Gere o cliente Prisma atualizado:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:generate
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Criar Diretórios
|
||||||
|
|
||||||
|
Os diretórios serão criados automaticamente, mas você pode criá-los manualmente:
|
||||||
|
|
||||||
|
**No Windows (PowerShell):**
|
||||||
|
```powershell
|
||||||
|
New-Item -Path "storage\temp\pdf-ops" -ItemType Directory -Force
|
||||||
|
New-Item -Path "storage\pdf-output" -ItemType Directory -Force
|
||||||
|
New-Item -Path "storage\temp\uploads" -ItemType Directory -Force
|
||||||
|
```
|
||||||
|
|
||||||
|
**No Linux/Mac:**
|
||||||
|
```bash
|
||||||
|
mkdir -p storage/temp/pdf-ops
|
||||||
|
mkdir -p storage/pdf-output
|
||||||
|
mkdir -p storage/temp/uploads
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Reiniciar o Servidor
|
||||||
|
|
||||||
|
Após instalar as dependências e executar as migrations, reinicie o servidor:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev:full
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou apenas o backend:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run server
|
||||||
|
```
|
||||||
|
|
||||||
|
## Verificação
|
||||||
|
|
||||||
|
Após seguir todos os passos:
|
||||||
|
|
||||||
|
1. Acesse a aplicação no navegador
|
||||||
|
2. Faça login
|
||||||
|
3. Clique no item "PDFs" no menu lateral
|
||||||
|
4. Teste a funcionalidade de compressão enviando um PDF
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Se continuar dando erro 404:
|
||||||
|
|
||||||
|
1. Verifique se o servidor foi reiniciado após as mudanças
|
||||||
|
2. Verifique se as dependências foram instaladas corretamente
|
||||||
|
3. Verifique os logs do servidor para erros de importação
|
||||||
|
|
||||||
|
### Se der erro de módulo não encontrado:
|
||||||
|
|
||||||
|
Execute:
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run prisma:generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Se der erro no banco de dados:
|
||||||
|
|
||||||
|
Execute:
|
||||||
|
```bash
|
||||||
|
npx prisma migrate reset
|
||||||
|
npx prisma migrate dev
|
||||||
|
npm run prisma:generate
|
||||||
|
```
|
||||||
|
|
||||||
|
**ATENÇÃO:** O comando `migrate reset` apaga todos os dados do banco!
|
||||||
@@ -5,6 +5,7 @@ import usuariosRoutes from "./routes/usuarios";
|
|||||||
import clientesRoutes from "./routes/clientes";
|
import clientesRoutes from "./routes/clientes";
|
||||||
import processosRoutes from "./routes/processos";
|
import processosRoutes from "./routes/processos";
|
||||||
import audienciasRoutes from "./routes/audiencias";
|
import audienciasRoutes from "./routes/audiencias";
|
||||||
|
import pdfRoutes from "./routes/pdf";
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
@@ -16,6 +17,7 @@ app.use("/api/usuarios", usuariosRoutes);
|
|||||||
app.use("/api/clientes", clientesRoutes);
|
app.use("/api/clientes", clientesRoutes);
|
||||||
app.use("/api/processos", processosRoutes);
|
app.use("/api/processos", processosRoutes);
|
||||||
app.use("/api/audiencias", audienciasRoutes);
|
app.use("/api/audiencias", audienciasRoutes);
|
||||||
|
app.use("/api/pdf", pdfRoutes);
|
||||||
|
|
||||||
app.get("/", (req, res) => {
|
app.get("/", (req, res) => {
|
||||||
res.json({ message: "API is running" });
|
res.json({ message: "API is running" });
|
||||||
|
|||||||
@@ -0,0 +1,596 @@
|
|||||||
|
# Funcionalidade de Manipulação de PDFs
|
||||||
|
|
||||||
|
## Visão Geral
|
||||||
|
|
||||||
|
Sistema completo de manipulação de arquivos PDF com as seguintes funcionalidades:
|
||||||
|
|
||||||
|
### Recursos Implementados
|
||||||
|
|
||||||
|
1. **Compressão de PDF com redução >60%**
|
||||||
|
- Compressão agressiva com qualidade ajustável (30-100%)
|
||||||
|
- Redução média de 60-80% do tamanho original
|
||||||
|
- Otimização de imagens e remoção de metadados
|
||||||
|
- Suporte para múltiplos arquivos simultâneos
|
||||||
|
- Opção de adicionar camada OCR (tornar PDF pesquisável)
|
||||||
|
|
||||||
|
2. **Divisão de PDF**
|
||||||
|
- Por páginas específicas (ex: 1,3,5,7)
|
||||||
|
- Por intervalos (ex: 1-5, 6
|
||||||
|
- **Download em ZIP** quando múltiplos arquivos-10)
|
||||||
|
- Por chunks de tamanho fixo
|
||||||
|
|
||||||
|
3. **Mesclagem de PDFs**
|
||||||
|
- Combine até 50 PDFs em um único arquivo
|
||||||
|
- Preserva qualidade o
|
||||||
|
- Opção de adicionar camada OCR ao PDF mescladoriginal
|
||||||
|
- Ordem personalizável
|
||||||
|
|
||||||
|
4. **PDF para Imagens**
|
||||||
|
- Formatos: PNG, JPG, WEBP
|
||||||
|
- DPI ajustável (150-600)
|
||||||
|
- **Download em ZIP** de todas as imagens
|
||||||
|
- Qualidade configurável (50-100%)
|
||||||
|
- Conversão de páginas específicas ou todas
|
||||||
|
|
||||||
|
5. **Imagens para PDF**
|
||||||
|
- Opção de adicionar camada OCR (tornar PDF pesquisável)
|
||||||
|
- Suporta múltiplas imagens (até 100)
|
||||||
|
- Ajuste automático ao tamanho da página
|
||||||
|
- Suporta PNG, JPG, JPEG, WEBP
|
||||||
|
|
||||||
|
6. **OCR (Reconhecimento Ótico de Caracteres)**
|
||||||
|
- Extração de texto de PDFs escaneados
|
||||||
|
- Suporte para Português, Inglês e Espanhol
|
||||||
|
- Retorna confiança da extração
|
||||||
|
- Processamento por página
|
||||||
|
|
||||||
|
7. **Informações do PDF**
|
||||||
|
- Número de páginas
|
||||||
|
- Tamanho do arquivo
|
||||||
|
- Metadados (título, autor, criador, etc.)
|
||||||
|
- Datas de criação e modificação
|
||||||
|
|
||||||
|
## Instalação
|
||||||
|
|
||||||
|
### 1. Instalar Dependências
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install pdf-lib pdf-parse pdf2pic tesseract.js archiver
|
||||||
|
npm install --save-dev @types/pdf-parse @types/archiver
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou execute o script de instalação:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run install-pdf-deps
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Instalar GraphicsMagick (Requerido para PDF → Imagens)
|
||||||
|
|
||||||
|
**Docker:**
|
||||||
|
O GraphicsMagick já está incluído no Dockerfile. Rebuild a imagem se necessário:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose down
|
||||||
|
docker-compose build --no-cache
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
**Local (desenvolvimento):**
|
||||||
|
|
||||||
|
Ubuntu/Debian:
|
||||||
|
```bash
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install graphicsmagick
|
||||||
|
```
|
||||||
|
|
||||||
|
MacOS:
|
||||||
|
```bash
|
||||||
|
brew install graphicsmagick
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows:
|
||||||
|
- Baixe e instale: http://www.graphicsmagick.org/download.html
|
||||||
|
- Adicione ao PATH do sistema
|
||||||
|
|
||||||
|
Verifique a instalação:
|
||||||
|
```bash
|
||||||
|
gm version
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Executar Migration do Banco de Dados
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:migrate
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou manualmente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx prisma migrate dev --name add_operacoes_pdf
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Gerar Cliente Prisma
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Criar Diretórios Necessários
|
||||||
|
|
||||||
|
Os diretórios serão criados automaticamente na primeira execução, mas você pode criá-los manualmente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p storage/temp/pdf-ops
|
||||||
|
mkdir -p storage/pdf-output
|
||||||
|
mkdir -p storage/temp/uploads
|
||||||
|
```
|
||||||
|
|
||||||
|
## Uso
|
||||||
|
|
||||||
|
### Frontend
|
||||||
|
|
||||||
|
Acesse a página de manipulação de PDFs através da rota:
|
||||||
|
|
||||||
|
```
|
||||||
|
/pdf
|
||||||
|
```
|
||||||
|
|
||||||
|
### API Endpoints
|
||||||
|
|
||||||
|
Todas as rotas requerem autenticação via Bearer token.
|
||||||
|
|
||||||
|
#### 1. Comprimir PDF
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/compress
|
||||||
|
Content-Type: multipart/form-data
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
30-100, padrão 50 para máxima compressão)
|
||||||
|
- maxSizeMB: number (opcional)
|
||||||
|
- enableOCR: boolean (opcional, adiciona camada OCR ao PDF
|
||||||
|
- files: File[] (array de PDFs)
|
||||||
|
- quality: number (50-100, padrão 95)
|
||||||
|
- maxSizeMB: number (opcional)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Dividir PDF
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/split
|
||||||
|
Content-Type: multipart/form-data
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
|
||||||
|
Body:
|
||||||
|
- files: File (único PDF)
|
||||||
|
- splitType: 'pages' | 'range' | 'chunks'
|
||||||
|
- pages: string (ex: "1,2,3") - para splitType='pages'
|
||||||
|
- ranges: string (ex: "1-5,6-10") - para splitType='range'
|
||||||
|
- chunkSize: number - para splitType='chunks'
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. Mesclar PDFs
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/merge
|
||||||
|
Content-Type: multipart/form-da
|
||||||
|
- enableOCR: boolean (opcional, adiciona camada OCR ao PDF mesclado)ta
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
|
||||||
|
Body:
|
||||||
|
- files: File[] (mínimo 2 PDFs)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. PDF para Imagens
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/pdf-to-images
|
||||||
|
Content-Type: multipart/form-data
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
|
||||||
|
Body:
|
||||||
|
- files: File (único PDF)
|
||||||
|
- format: 'png' | 'jpg' | 'webp' (padrão: png)
|
||||||
|
- quality: number (50-100, padrão: 95)
|
||||||
|
- density: number (DPI, 150-600, padrão: 300)
|
||||||
|
- pages: string (opcional, ex: "[1,2,3]" ou "all")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 5. Imagens para PDF
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/images-to-pdf
|
||||||
|
Content-Type: multipart/form-data
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
- enableOCR: boolean (opcional, adiciona camada OCR ao PDF)
|
||||||
|
|
||||||
|
Body:
|
||||||
|
- files: File[] (array de imagens)
|
||||||
|
- fitToPage: boolean (padrão: true)
|
||||||
|
- pageSize: string (opcional, JSON: {"width":595,"height":842})
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 6. OCR
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/ocr
|
||||||
|
Content-Type: multipart/form-data
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
|
||||||
|
Body:
|
||||||
|
- files: File (único PDF)
|
||||||
|
- language: string ('por' | 'eng' | 'spa', padrão: 'por')
|
||||||
|
- pages: string (opcional, ex: "[1,2]" ou "all")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 7. Informações do PDF
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/pdf/info
|
||||||
|
Content-Type: multipart/form-data
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
|
||||||
|
Body:
|
||||||
|
- files: File (único PDF)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 8. Histórico de Operações
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/pdf/history?page=1&limit=20
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 9. Download de Arquivo Processado
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/pdf/download/:operacaoId/:fileIndex
|
||||||
|
Authorization: Bearer {token}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Estrutura de Resposta
|
||||||
|
|
||||||
|
### Sucesso (Compressão)
|
||||||
|
...],
|
||||||
|
"outputPaths": ["/path/compressed-1.pdf", "/path/compressed-2.pdf"],
|
||||||
|
"totalOriginalSize": 1048576,
|
||||||
|
"totalCompressedSize": 314572,
|
||||||
|
"reduction": 70.0,
|
||||||
|
"processingTime": 1234
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sucesso (Split/PDF para Imagens - com ZIP)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"operacaoId": "uuid",
|
||||||
|
"filesCreated": 10,
|
||||||
|
"outputPaths": ["/path/page-1.pdf", "/path/page-2.pdf", ...],
|
||||||
|
"zipPath": "/path/arquivos-uuid.zip",
|
||||||
|
"processingTime": 2345
|
||||||
|
],
|
||||||
|
"totalOriginalSize": 1048576,
|
||||||
|
"totalCompressedSize": 524288,
|
||||||
|
"totalReduction": 50.0,
|
||||||
|
"processingTime": 1234
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sucesso (OCR)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"operacaoId": "uuid",
|
||||||
|
"result": {
|
||||||
|
"text": "Texto extraído completo...",
|
||||||
|
"confidence": 95.5,
|
||||||
|
"pages": [
|
||||||
|
{
|
||||||
|
"pageNumber": 1,
|
||||||
|
"text": "Texto da página 1...",
|
||||||
|
"confidence": 96.2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"processingTime": 5678
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "Falha ao processar arquivo",
|
||||||
|
"message": "Detalhes específicos do erro"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Modelo de Dados
|
||||||
|
|
||||||
|
### OperacaoPDF
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface OperacaoPDF {
|
||||||
|
id: string;
|
||||||
|
tipoOperacao: 'COMPRIMIR' | 'DIVIDIR' | 'MESCLAR' | 'PDF_PARA_IMAGEM' | 'IMAGEM_PARA_PDF' | 'OCR';
|
||||||
|
status: 'PROCESSANDO' | 'CONCLUIDO' | 'ERRO';
|
||||||
|
usuarioId: string;
|
||||||
|
arquivosOriginais: string[];
|
||||||
|
arquivosResultado: string[];
|
||||||
|
tamanhoOriginal: bigint;
|
||||||
|
tamanhoResultado: bigint | null;
|
||||||
|
parametros: any;
|
||||||
|
mensagemErro: string | null;
|
||||||
|
detalhesOCR: any | null;
|
||||||
|
tempoProcessamento: number | null;
|
||||||
|
criadoEm: Date;
|
||||||
|
atualizadoEm: Date;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Segurança
|
||||||
|
|
||||||
|
- ✅ Autenticação obrigatória em todas as rotas
|
||||||
|
- ✅ Validação de tipos de arquivo (apenas PDF e imagens)
|
||||||
|
- ✅ Limite de tamanho de arquivo (100MB por arquivo)
|
||||||
|
- ✅ Limite de quantidade de arquivos por operação
|
||||||
|
- ✅ Sanitização de nomes de arquivo
|
||||||
|
- ✅ Isolamento de arquivos por operação
|
||||||
|
- ✅ Limpeza automática de arquivos temporários
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
- ✅ Processamento assíncrono
|
||||||
|
- ✅ Otimização de memória com streams
|
||||||
|
- ✅ Compressão sem perda de qualidade perceptível
|
||||||
|
- ✅ Cache de workers de OCR
|
||||||
|
- ✅ Índices no banco de dados para consultas rápidas
|
||||||
|
- ✅ Limpeza automática de arquivos antigos
|
||||||
|
|
||||||
|
## Tratamento de Erros
|
||||||
|
|
||||||
|
Todos os erros são:
|
||||||
|
- Logados no console do servidor
|
||||||
|
- Registrados no banco de dados (tabela operacoes_pdf)
|
||||||
|
- Retornados ao cliente com mensagens descritivas
|
||||||
|
- Capturados por try-catch em todas as operações
|
||||||
|
|
||||||
|
## Limitações
|
||||||
|
|
||||||
|
- Tamanho máximo por arquivo: 100MB
|
||||||
|
- Máximo de arquivos para compressão: 10
|
||||||
|
- Máximo de arquivos para mesclagem: 50
|
||||||
|
- Máximo de imagens para conversão em PDF: 100
|
||||||
|
- Arquivos processados são mantidos por 24 horas
|
||||||
|
- **Timeout de operações:** 10 minutos (600 segundos)
|
||||||
|
- Operações longas (OCR, compressão de PDFs grandes) podem levar alguns minutos
|
||||||
|
- O sistema está configurado para suportar até 10 minutos de processamento
|
||||||
|
|
||||||
|
## Manutenção
|
||||||
|
|
||||||
|
### Limpeza de Arquivos Antigos
|
||||||
|
|
||||||
|
Execute periodicamente (recomendado: diariamente via cron):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { PDFService } from './src/services/pdfService';
|
||||||
|
|
||||||
|
// Remove arquivos com mais de 24 horas
|
||||||
|
await PDFService.cleanupOldFiles(24);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Monitoramento
|
||||||
|
|
||||||
|
Consulte a tabela `operacoes_pdf` para:
|
||||||
|
- Estatísticas de uso
|
||||||
|
- Taxa de erro
|
||||||
|
- Tempo médio de processamento
|
||||||
|
- Operações mais utilizadas
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Operações por tipo
|
||||||
|
SELECT "tipoOperacao", COUNT(*) as total
|
||||||
|
FROM operacoes_pdf
|
||||||
|
GROUP BY "tipoOperacao"
|
||||||
|
ORDER BY total DESC;
|
||||||
|
|
||||||
|
-- Taxa de sucesso
|
||||||
|
SELECT
|
||||||
|
status,
|
||||||
|
COUNT(*) as total,
|
||||||
|
ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(), 2) as percentual
|
||||||
|
FROM operacoes_pdf
|
||||||
|
GROUP BY status;
|
||||||
|
|
||||||
|
-- Tempo médio por operação
|
||||||
|
SELECT
|
||||||
|
"tipoOperacao",
|
||||||
|
AVG("tempoProcessamento") as tempo_medio_ms,
|
||||||
|
MIN("tempoProcessamento") as tempo_min_ms,
|
||||||
|
MAX("tempoProcessamento") as tempo_max_ms
|
||||||
|
FROM operacoes_pdf
|
||||||
|
WHERE status = 'CONCLUIDO'
|
||||||
|
GROUP BY "tipoOperacao";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Erro: "Could not execute GraphicsMagick/ImageMagick"
|
||||||
|
|
||||||
|
**Sintoma:** Erro ao converter PDF para imagens:
|
||||||
|
```
|
||||||
|
Error: Could not execute GraphicsMagick/ImageMagick: gm "convert" ...
|
||||||
|
this most likely means the gm/convert binaries can't be found
|
||||||
|
```
|
||||||
|
|
||||||
|
**Causa:** GraphicsMagick não está instalado no sistema/container.
|
||||||
|
|
||||||
|
**Solução:**
|
||||||
|
|
||||||
|
**Docker:**
|
||||||
|
```bash
|
||||||
|
# Rebuild a imagem Docker com GraphicsMagick incluído
|
||||||
|
docker-compose down
|
||||||
|
docker-compose build --no-cache
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
**Local:**
|
||||||
|
```bash
|
||||||
|
# Ubuntu/Debian
|
||||||
|
sudo apt-get install graphicsmagick
|
||||||
|
|
||||||
|
# MacOS
|
||||||
|
brew install graphicsmagick
|
||||||
|
|
||||||
|
# Verifique a instalação
|
||||||
|
gm version
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro 504: Gateway Timeout (Timeout ao processar PDF)
|
||||||
|
|
||||||
|
**Sintoma:** Operação de compressão ou OCR retorna erro 504 após ~60 segundos:
|
||||||
|
```
|
||||||
|
Failed to load resource: the server responded with a status of 504
|
||||||
|
```
|
||||||
|
|
||||||
|
**Causa:** Operações de PDF (especialmente compressão e OCR) podem levar vários minutos para arquivos grandes. O timeout padrão de 60 segundos é insuficiente.
|
||||||
|
|
||||||
|
**Solução:** As configurações de timeout foram aumentadas para **10 minutos** em:
|
||||||
|
- ✅ Express server (`src/server/index.ts`)
|
||||||
|
- ✅ Vite proxy (`vite.config.ts`)
|
||||||
|
- ✅ Axios frontend (`PDFManipulationPage.tsx`)
|
||||||
|
|
||||||
|
Se ainda ocorrer timeout:
|
||||||
|
1. Verifique se rebuild foi feito após as alterações
|
||||||
|
2. Reduza o tamanho do arquivo ou qualidade
|
||||||
|
3. Processe menos arquivos por vez
|
||||||
|
4. Para PDFs muito grandes (>50MB), considere fazer upload em partes
|
||||||
|
|
||||||
|
**Dicas de performance:**
|
||||||
|
- Compressão: Use qualidade 50-70 para PDFs grandes
|
||||||
|
- OCR: Processe apenas páginas necessárias, não o PDF inteiro
|
||||||
|
- Split: Use chunks menores para PDFs com muitas páginas
|
||||||
|
|
||||||
|
### Erro: ENOENT ao deletar arquivos do histórico
|
||||||
|
|
||||||
|
**Sintoma:** Erro ao limpar histórico:
|
||||||
|
```
|
||||||
|
Error: ENOENT: no such file or directory, unlink '/path/to/file.pdf'
|
||||||
|
```
|
||||||
|
|
||||||
|
**Causa:** Tentativa de deletar arquivos que não existem mais (já foram removidos manualmente ou por outro processo).
|
||||||
|
|
||||||
|
**Solução:** ✅ **Corrigido automaticamente** - O sistema agora verifica se o arquivo existe antes de tentar deletar e ignora erros ENOENT silenciosamente.
|
||||||
|
|
||||||
|
### Erro: Imagens baixadas com extensão .pdf (ou sem extensão correta)
|
||||||
|
|
||||||
|
**Sintoma:** Ao baixar imagens geradas pela conversão PDF→Imagens, os arquivos vêm com extensão .pdf ou precisam ser renomeados para .png/.jpg para serem visualizados.
|
||||||
|
|
||||||
|
**Causa:** O servidor não estava enviando o Content-Type correto no header HTTP, OU o frontend estava ignorando os headers do servidor e forçando o nome como `.pdf`.
|
||||||
|
|
||||||
|
**Solução:** ✅ **Corrigido automaticamente** - O sistema agora:
|
||||||
|
|
||||||
|
**Backend:**
|
||||||
|
- Detecta automaticamente o tipo MIME correto baseado na extensão (.png, .jpg, .webp, .zip, .pdf)
|
||||||
|
- Define headers HTTP apropriados (`Content-Type` e `Content-Disposition`)
|
||||||
|
- Garante que o nome do arquivo no download mantém a extensão original
|
||||||
|
- Adiciona logs de debug para facilitar troubleshooting
|
||||||
|
|
||||||
|
**Frontend:**
|
||||||
|
- Extrai o nome do arquivo do header `Content-Disposition` enviado pelo servidor
|
||||||
|
- Usa o `Content-Type` correto do servidor ao criar o Blob para download
|
||||||
|
- Não força mais extensão `.pdf` em todos os downloads
|
||||||
|
- Adiciona log no console do browser: `Download frontend: arquivo.png (image/png)`
|
||||||
|
- Libera memória do blob URL após download
|
||||||
|
|
||||||
|
Se ainda ocorrer o problema:
|
||||||
|
1. Abra o Console do DevTools (F12) e verifique os logs de download
|
||||||
|
2. Verifique se os headers estão sendo recebidos corretamente na aba Network
|
||||||
|
3. Limpe o cache do browser (Ctrl+Shift+Del)
|
||||||
|
4. Teste em uma aba anônima/privada
|
||||||
|
5. Use a opção de **Download ZIP** que sempre funciona corretamente
|
||||||
|
|
||||||
|
### Erro: "Tesseract worker failed"
|
||||||
|
|
||||||
|
Solução: Certifique-se de que o Tesseract está instalado corretamente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install tesseract.js --force
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro: "Cannot find module 'sharp'"
|
||||||
|
|
||||||
|
Solução: Reinstale o Sharp com rebuild:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm uninstall sharp
|
||||||
|
npm install sharp
|
||||||
|
npm rebuild sharp
|
||||||
|
```
|
||||||
|
|
||||||
|
### Erro: "ENOSPC: no space left on device"
|
||||||
|
|
||||||
|
Solução: Aumente o espaço em disco ou execute a limpeza:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run cleanup-pdf-files
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance lenta no OCR
|
||||||
|
|
||||||
|
Solução: Reduza o DPI ou processe menos páginas por vez.
|
||||||
|
|
||||||
|
## Suporte
|
||||||
|
|
||||||
|
Para questões ou problemas:
|
||||||
|
1. Verifique os logs do servidor
|
||||||
|
2. Consulte a tabela `operacoes_pdf` para detalhes do erro
|
||||||
|
3. Verifique se os diretórios de storage têm permissões corretas
|
||||||
|
4. Certifique-se de que todas as dependências estão instaladas
|
||||||
|
|
||||||
|
## Changelog
|
||||||
|
|
||||||
|
### v1.1.2 (2026-02-27)
|
||||||
|
- 🔧 **Correção DEFINITIVA de downloads** - Arquivos agora baixam com nome e extensão corretos
|
||||||
|
- **Backend:** Detecta tipo MIME e define headers HTTP apropriados (Content-Type, Content-Disposition)
|
||||||
|
- **Frontend:** Extrai nome do arquivo e tipo MIME dos headers da resposta
|
||||||
|
- **Frontend:** Não força mais `.pdf` em todos os downloads - usa nome real do servidor
|
||||||
|
- **Frontend:** Cria Blob com Content-Type correto preservando o formato original
|
||||||
|
- Adiciona logs de debug no backend e frontend para troubleshooting
|
||||||
|
- Suporta formato 'jpeg' além de 'jpg'
|
||||||
|
- Fallback para PNG em formatos não suportados
|
||||||
|
- Libera memória de blob URLs após download
|
||||||
|
- 🐛 **Melhorias no pdfToImages** - Adicionado suporte para 'jpeg' e fallback para formatos inválidos
|
||||||
|
|
||||||
|
### v1.1.1 (2026-02-27)
|
||||||
|
- 🔧 **Correção de timeout 504** - Aumentado timeout para 10 minutos em todas as camadas
|
||||||
|
- Express server: 600 segundos
|
||||||
|
- Vite proxy: 600 segundos
|
||||||
|
- Axios frontend: 600 segundos
|
||||||
|
- 🗑️ **Correção ENOENT** - Sistema agora ignora arquivos já deletados ao limpar histórico
|
||||||
|
- 📋 **Gerenciamento de histórico** - Botões para limpar histórico completo ou arquivos antigos
|
||||||
|
- 🐛 **Melhorias de estabilidade** - Verificação de existência de arquivos antes de deletar
|
||||||
|
- 📚 **Documentação expandida** - Adicionado troubleshooting completo
|
||||||
|
|
||||||
|
### v1.1.0 (2026-02-27)
|
||||||
|
- 🚀 **Compressão agressiva** com redução >60% do tamanho original
|
||||||
|
- 📦 **Download em ZIP** para operações com múltiplos arquivos (split, pdfToImages)
|
||||||
|
- 🔍 **OCR embutido** - opção de tornar PDFs pesquisáveis (compress, merge, imagesToPDF)
|
||||||
|
- ⚡ **Otimização de imagens** com qualidade ajustável (30-100%)
|
||||||
|
- 🎯 **Interface aprimorada** com indicadores visuais e opções de OCR
|
||||||
|
|
||||||
|
### v1.0.0 (2026-02-27)
|
||||||
|
- ✅ Implementação inicial
|
||||||
|
- ✅ Compressão sem perda de qualidade
|
||||||
|
- ✅ Divisão de PDFs
|
||||||
|
- ✅ Mesclagem de PDFs
|
||||||
|
- ✅ Conversão PDF para imagens
|
||||||
|
- ✅ Conversão de imagens para PDF
|
||||||
|
- ✅ OCR com Tesseract
|
||||||
|
- ✅ Histórico de operações
|
||||||
|
- ✅ Interface React completa
|
||||||
|
- ✅ Validação e segurança
|
||||||
+17
-23
@@ -12,20 +12,16 @@
|
|||||||
"prisma:migrate": "prisma migrate dev",
|
"prisma:migrate": "prisma migrate dev",
|
||||||
"prisma:studio": "prisma studio",
|
"prisma:studio": "prisma studio",
|
||||||
"prisma:seed": "ts-node -T prisma/seed.ts",
|
"prisma:seed": "ts-node -T prisma/seed.ts",
|
||||||
"postinstall": "prisma generate && npx playwright install chromium",
|
"postinstall": "prisma generate && npx puppeteer browsers install chrome",
|
||||||
"server": "ts-node --transpile-only src/server/index.ts",
|
"server": "ts-node --transpile-only src/server/index.ts",
|
||||||
"dev:full": "concurrently -n \"frontend,backend\" -c \"blue,green\" \"npm run dev\" \"npm run server\"",
|
"dev:full": "concurrently -n \"frontend,backend\" -c \"blue,green\" \"npm run dev\" \"npm run server\"",
|
||||||
"lint": "eslint . --ext .ts,.tsx",
|
"lint": "eslint . --ext .ts,.tsx",
|
||||||
"lint:fix": "eslint . --ext .ts,.tsx --fix",
|
"lint:fix": "eslint . --ext .ts,.tsx --fix",
|
||||||
"create-admin": "ts-node scripts/create_admin_user.ts",
|
"create-admin": "ts-node scripts/create_admin_user.ts",
|
||||||
"worker": "ts-node src/workers/startWorker.ts",
|
"worker": "ts-node src/workers/startWorker.ts",
|
||||||
"install-deps": "npm install ua-parser-js uuid axios xlsx html2canvas puppeteer-core chrome-aws-lambda jspdf canvas ws socket.io socket.io-client",
|
"install-deps": "npm install ua-parser-js uuid axios xlsx",
|
||||||
"install-web-proof-deps": "npm install html2canvas puppeteer-core chrome-aws-lambda jspdf canvas node-html-to-image playwright ws socket.io socket.io-client",
|
"install-pdf-deps": "npm install pdf-parse pdf2pic tesseract.js archiver && npm install --save-dev @types/pdf-parse @types/archiver",
|
||||||
"prisma:resolve-migration": "npx prisma migrate resolve --applied",
|
"cleanup-pdf-files": "ts-node scripts/cleanup_pdf_files.ts"
|
||||||
"prisma:sync-schema": "npx prisma db push && npx prisma generate",
|
|
||||||
"prisma:reset-migrations": "npx prisma migrate reset --force",
|
|
||||||
"prisma:fix-manual-migration": "npx prisma migrate status && npx prisma db push && npx prisma generate",
|
|
||||||
"prisma:mark-applied": "npx prisma migrate resolve --applied"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emotion/react": "^11.11.3",
|
"@emotion/react": "^11.11.3",
|
||||||
@@ -42,6 +38,7 @@
|
|||||||
"@tiptap/starter-kit": "^2.11.7",
|
"@tiptap/starter-kit": "^2.11.7",
|
||||||
"@types/sharp": "^0.32.0",
|
"@types/sharp": "^0.32.0",
|
||||||
"@types/ua-parser-js": "^0.7.36",
|
"@types/ua-parser-js": "^0.7.36",
|
||||||
|
"archiver": "^7.0.1",
|
||||||
"axios": "^1.6.5",
|
"axios": "^1.6.5",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"buffer": "^6.0.3",
|
"buffer": "^6.0.3",
|
||||||
@@ -55,17 +52,12 @@
|
|||||||
"multer": "^1.4.5-lts.1",
|
"multer": "^1.4.5-lts.1",
|
||||||
"opentimestamps-javascript": "^1.0.1",
|
"opentimestamps-javascript": "^1.0.1",
|
||||||
"pdf-lib": "^1.17.1",
|
"pdf-lib": "^1.17.1",
|
||||||
"html2canvas": "^1.4.1",
|
"pdf-parse": "^1.1.1",
|
||||||
"puppeteer-core": "^24.15.0",
|
"pdf2pic": "^3.1.3",
|
||||||
"jspdf": "^2.5.1",
|
"pdfkit": "^0.13.0",
|
||||||
"canvas": "^3.1.2",
|
"puppeteer": "^24.5.0",
|
||||||
"screenshot-desktop": "^1.12.7",
|
"qrcode": "^1.5.3",
|
||||||
"node-html-to-image": "^4.0.0",
|
"tesseract.js": "^5.0.4",
|
||||||
"playwright": "^1.40.0",
|
|
||||||
"ws": "^8.14.2",
|
|
||||||
"socket.io": "^4.7.4",
|
|
||||||
"socket.io-client": "^4.7.4",
|
|
||||||
"@types/ws": "^8.5.10",
|
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-beautiful-dnd": "^13.1.1",
|
"react-beautiful-dnd": "^13.1.1",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
@@ -85,12 +77,14 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4.1.1",
|
"@tailwindcss/postcss": "^4.1.1",
|
||||||
|
"@types/archiver": "^6.0.2",
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/cors": "^2.8.17",
|
"@types/cors": "^2.8.17",
|
||||||
"@types/express": "^5.0.1",
|
"@types/express": "^5.0.1",
|
||||||
"@types/jsonwebtoken": "^9.0.9",
|
"@types/jsonwebtoken": "^9.0.9",
|
||||||
"@types/multer": "^1.4.12",
|
"@types/multer": "^1.4.12",
|
||||||
"@types/node": "^22.13.14",
|
"@types/node": "^22.13.14",
|
||||||
|
"@types/pdf-parse": "^1.1.4",
|
||||||
"@types/react": "^19.0.12",
|
"@types/react": "^19.0.12",
|
||||||
"@types/react-beautiful-dnd": "^13.1.8",
|
"@types/react-beautiful-dnd": "^13.1.8",
|
||||||
"@types/react-dom": "^19.0.4",
|
"@types/react-dom": "^19.0.4",
|
||||||
@@ -101,6 +95,9 @@
|
|||||||
"autoprefixer": "^10.4.17",
|
"autoprefixer": "^10.4.17",
|
||||||
"concurrently": "^9.1.2",
|
"concurrently": "^9.1.2",
|
||||||
"eslint": "^9.23.0",
|
"eslint": "^9.23.0",
|
||||||
|
"eslint-config-prettier": "^10.1.1",
|
||||||
|
"eslint-plugin-prettier": "^5.2.5",
|
||||||
|
"eslint-plugin-react": "^7.37.4",
|
||||||
"eslint-plugin-react-hooks": "^5.2.0",
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
"postcss": "^8.4.33",
|
"postcss": "^8.4.33",
|
||||||
"prettier": "^3.5.3",
|
"prettier": "^3.5.3",
|
||||||
@@ -108,10 +105,7 @@
|
|||||||
"tailwindcss": "^3.4.1",
|
"tailwindcss": "^3.4.1",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
"typescript": "^5.8.2",
|
"typescript": "^5.8.2",
|
||||||
"vite": "^6.2.4",
|
"vite": "^6.2.4"
|
||||||
"@types/html2canvas": "^1.0.0",
|
|
||||||
"@types/canvas": "^2.11.6",
|
|
||||||
"@types/node-html-to-image": "^4.0.0"
|
|
||||||
},
|
},
|
||||||
"prisma": {
|
"prisma": {
|
||||||
"seed": "ts-node prisma/seed.ts"
|
"seed": "ts-node prisma/seed.ts"
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
-- Migration para adicionar tabela de operações de PDF
|
||||||
|
-- Created: 2026-02-27
|
||||||
|
|
||||||
|
-- Criar ENUM para tipo de operação
|
||||||
|
CREATE TYPE "TipoOperacaoPDF" AS ENUM ('COMPRIMIR', 'DIVIDIR', 'MESCLAR', 'PDF_PARA_IMAGEM', 'IMAGEM_PARA_PDF', 'OCR');
|
||||||
|
|
||||||
|
-- Criar ENUM para status da operação
|
||||||
|
CREATE TYPE "StatusOperacaoPDF" AS ENUM ('PROCESSANDO', 'CONCLUIDO', 'ERRO');
|
||||||
|
|
||||||
|
-- Criar tabela de operações de PDF
|
||||||
|
CREATE TABLE "operacoes_pdf" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"tipoOperacao" "TipoOperacaoPDF" NOT NULL,
|
||||||
|
"status" "StatusOperacaoPDF" NOT NULL DEFAULT 'PROCESSANDO',
|
||||||
|
"usuarioId" UUID NOT NULL,
|
||||||
|
"arquivosOriginais" TEXT[] NOT NULL,
|
||||||
|
"arquivosResultado" TEXT[] NOT NULL,
|
||||||
|
"tamanhoOriginal" BIGINT NOT NULL,
|
||||||
|
"tamanhoResultado" BIGINT,
|
||||||
|
"parametros" JSONB,
|
||||||
|
"mensagemErro" TEXT,
|
||||||
|
"detalhesOCR" JSONB,
|
||||||
|
"tempoProcessamento" INTEGER,
|
||||||
|
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"atualizadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "operacoes_pdf_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Adicionar foreign key para usuarios
|
||||||
|
ALTER TABLE "operacoes_pdf" ADD CONSTRAINT "operacoes_pdf_usuarioId_fkey" FOREIGN KEY ("usuarioId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- Criar índice para melhor performance nas consultas
|
||||||
|
CREATE INDEX "operacoes_pdf_usuarioId_idx" ON "operacoes_pdf"("usuarioId");
|
||||||
|
CREATE INDEX "operacoes_pdf_criadoEm_idx" ON "operacoes_pdf"("criadoEm" DESC);
|
||||||
|
CREATE INDEX "operacoes_pdf_status_idx" ON "operacoes_pdf"("status");
|
||||||
+44
-24
@@ -51,6 +51,9 @@ model Usuario {
|
|||||||
// Adicionar relação para cálculos de pensão alimentícia
|
// Adicionar relação para cálculos de pensão alimentícia
|
||||||
calculosPensaoAlimenticia CalculoPensaoAlimenticia[]
|
calculosPensaoAlimenticia CalculoPensaoAlimenticia[]
|
||||||
|
|
||||||
|
// Adicionar relação para operações de PDF
|
||||||
|
operacoesPDF OperacaoPDF[]
|
||||||
|
|
||||||
@@map("usuarios")
|
@@map("usuarios")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1068,29 +1071,46 @@ model CalculoPensaoAlimenticia {
|
|||||||
@@map("calculos_pensao_alimenticia")
|
@@map("calculos_pensao_alimenticia")
|
||||||
}
|
}
|
||||||
|
|
||||||
model WebProofSession {
|
// Modelo para histórico de operações de PDF
|
||||||
id String @id @default(cuid())
|
enum TipoOperacaoPDF {
|
||||||
sessionId String @unique
|
COMPRIMIR
|
||||||
targetUrl String
|
DIVIDIR
|
||||||
description String?
|
MESCLAR
|
||||||
status String @default("PENDENTE")
|
PDF_PARA_IMAGEM
|
||||||
metadata Json?
|
IMAGEM_PARA_PDF
|
||||||
environment Json?
|
OCR
|
||||||
screenshots String[]
|
}
|
||||||
sessionHash String?
|
|
||||||
contentHash String?
|
|
||||||
pageHash String?
|
|
||||||
reportPath String?
|
|
||||||
networkData Json?
|
|
||||||
trustedTimestamp String?
|
|
||||||
error String?
|
|
||||||
createdAt DateTime @default(now())
|
|
||||||
updatedAt DateTime @updatedAt
|
|
||||||
processedAt DateTime?
|
|
||||||
|
|
||||||
@@index([sessionId])
|
enum StatusOperacaoPDF {
|
||||||
@@index([status])
|
PROCESSANDO
|
||||||
@@index([createdAt])
|
CONCLUIDO
|
||||||
@@index([contentHash])
|
ERRO
|
||||||
@@map("web_proof_sessions")
|
}
|
||||||
|
|
||||||
|
model OperacaoPDF {
|
||||||
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
|
tipoOperacao TipoOperacaoPDF
|
||||||
|
status StatusOperacaoPDF @default(PROCESSANDO)
|
||||||
|
usuarioId String @db.Uuid
|
||||||
|
usuario Usuario @relation(fields: [usuarioId], references: [id])
|
||||||
|
|
||||||
|
// Informações dos arquivos
|
||||||
|
arquivosOriginais String[] // Array de paths dos arquivos originais
|
||||||
|
arquivosResultado String[] // Array de paths dos arquivos resultantes
|
||||||
|
tamanhoOriginal BigInt // Tamanho total dos arquivos originais em bytes
|
||||||
|
tamanhoResultado BigInt? // Tamanho total dos arquivos resultantes em bytes
|
||||||
|
|
||||||
|
// Parâmetros da operação
|
||||||
|
parametros Json? // Parâmetros específicos da operação (ex: páginas para dividir)
|
||||||
|
|
||||||
|
// Resultado da operação
|
||||||
|
mensagemErro String?
|
||||||
|
detalhesOCR Json? // Quando for OCR, armazena o texto extraído
|
||||||
|
|
||||||
|
tempoProcessamento Int? // Tempo de processamento em milissegundos
|
||||||
|
|
||||||
|
criadoEm DateTime @default(now())
|
||||||
|
atualizadoEm DateTime @updatedAt
|
||||||
|
|
||||||
|
@@map("operacoes_pdf")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { PDFService } from '../src/services/pdfService';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Script para limpeza de arquivos PDF antigos
|
||||||
|
* Remove arquivos com mais de 24 horas por padrão
|
||||||
|
*
|
||||||
|
* Uso:
|
||||||
|
* npm run cleanup-pdf-files
|
||||||
|
*
|
||||||
|
* Ou via ts-node:
|
||||||
|
* ts-node scripts/cleanup_pdf_files.ts [horas]
|
||||||
|
*/
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('Iniciando limpeza de arquivos PDF antigos...');
|
||||||
|
|
||||||
|
const horasArg = process.argv[2];
|
||||||
|
const horas = horasArg ? parseInt(horasArg) : 24;
|
||||||
|
|
||||||
|
if (isNaN(horas) || horas < 0) {
|
||||||
|
console.error('Erro: O argumento deve ser um número positivo de horas');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Removendo arquivos com mais de ${horas} horas...`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await PDFService.cleanupOldFiles(horas);
|
||||||
|
console.log('✅ Limpeza concluída com sucesso!');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro durante a limpeza:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.then(() => process.exit(0))
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Erro fatal:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
@echo off
|
||||||
|
:: Script para rebuild completo do Docker com dependências PDF
|
||||||
|
:: Use este script após atualizar o Dockerfile para incluir GraphicsMagick
|
||||||
|
|
||||||
|
echo ========================================
|
||||||
|
echo Rebuild Docker - Sistema PDF
|
||||||
|
echo ========================================
|
||||||
|
echo.
|
||||||
|
|
||||||
|
echo Parando containers...
|
||||||
|
docker-compose down
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Removendo imagens antigas...
|
||||||
|
docker image prune -f
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Reconstruindo imagem (sem cache)...
|
||||||
|
docker-compose build --no-cache
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Iniciando containers...
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ========================================
|
||||||
|
echo Rebuild concluído!
|
||||||
|
echo ========================================
|
||||||
|
echo.
|
||||||
|
echo Verificando status dos containers:
|
||||||
|
docker-compose ps
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Para ver os logs:
|
||||||
|
echo docker-compose logs -f backend
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Script para rebuild completo do Docker com dependências PDF
|
||||||
|
# Use este script após atualizar o Dockerfile para incluir GraphicsMagick
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo "Rebuild Docker - Sistema PDF"
|
||||||
|
echo "========================================"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
echo "Parando containers..."
|
||||||
|
docker-compose down
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Removendo imagens antigas..."
|
||||||
|
docker image prune -f
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Reconstruindo imagem (sem cache)..."
|
||||||
|
docker-compose build --no-cache
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Iniciando containers..."
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "========================================"
|
||||||
|
echo "Rebuild concluído!"
|
||||||
|
echo "========================================"
|
||||||
|
echo ""
|
||||||
|
echo "Verificando status dos containers:"
|
||||||
|
docker-compose ps
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Para ver os logs:"
|
||||||
|
echo " docker-compose logs -f backend"
|
||||||
|
echo ""
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
import { PDFService } from '../src/services/pdfService';
|
||||||
|
import path from 'path';
|
||||||
|
import fs from 'fs/promises';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Script de teste para funcionalidades de PDF
|
||||||
|
*
|
||||||
|
* ATENÇÃO: Este é um script de teste. Certifique-se de ter arquivos de teste
|
||||||
|
* disponíveis antes de executar.
|
||||||
|
*
|
||||||
|
* Uso:
|
||||||
|
* ts-node scripts/test_pdf_operations.ts
|
||||||
|
*/
|
||||||
|
|
||||||
|
async function testPDFInfo() {
|
||||||
|
console.log('\n=== Testando: Informações do PDF ===');
|
||||||
|
try {
|
||||||
|
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
|
||||||
|
|
||||||
|
// Verifica se o arquivo existe
|
||||||
|
try {
|
||||||
|
await fs.access(testPdfPath);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const info = await PDFService.getPDFInfo(testPdfPath);
|
||||||
|
console.log('✅ Informações obtidas com sucesso:');
|
||||||
|
console.log(' Páginas:', info.pages);
|
||||||
|
console.log(' Tamanho:', (info.size / 1024).toFixed(2), 'KB');
|
||||||
|
console.log(' Título:', info.title || 'N/A');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testCompression() {
|
||||||
|
console.log('\n=== Testando: Compressão de PDF ===');
|
||||||
|
try {
|
||||||
|
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testPdfPath);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await PDFService.compressPDF(testPdfPath, undefined, {
|
||||||
|
quality: 95,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Compressão concluída:');
|
||||||
|
console.log(' Tamanho original:', (result.originalSize / 1024).toFixed(2), 'KB');
|
||||||
|
console.log(' Tamanho comprimido:', (result.compressedSize / 1024).toFixed(2), 'KB');
|
||||||
|
console.log(' Redução:', result.reduction.toFixed(2), '%');
|
||||||
|
console.log(' Arquivo salvo em:', result.outputPath);
|
||||||
|
|
||||||
|
// Limpa o arquivo de teste
|
||||||
|
await fs.unlink(result.outputPath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testSplit() {
|
||||||
|
console.log('\n=== Testando: Divisão de PDF ===');
|
||||||
|
try {
|
||||||
|
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testPdfPath);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Primeiro, verifica quantas páginas o PDF tem
|
||||||
|
const info = await PDFService.getPDFInfo(testPdfPath);
|
||||||
|
|
||||||
|
if (info.pages < 2) {
|
||||||
|
console.log('⚠️ PDF tem menos de 2 páginas. Pulando teste de divisão.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPaths = await PDFService.splitPDF(testPdfPath, {
|
||||||
|
splitType: 'chunks',
|
||||||
|
chunkSize: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Divisão concluída:');
|
||||||
|
console.log(' Arquivos criados:', outputPaths.length);
|
||||||
|
|
||||||
|
// Limpa os arquivos de teste
|
||||||
|
for (const outputPath of outputPaths) {
|
||||||
|
await fs.unlink(outputPath);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testMerge() {
|
||||||
|
console.log('\n=== Testando: Mesclagem de PDFs ===');
|
||||||
|
try {
|
||||||
|
const testPdf1 = path.join(process.cwd(), 'test', 'sample1.pdf');
|
||||||
|
const testPdf2 = path.join(process.cwd(), 'test', 'sample2.pdf');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testPdf1);
|
||||||
|
await fs.access(testPdf2);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Arquivos de teste não encontrados. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPath = await PDFService.mergePDFs({
|
||||||
|
filePaths: [testPdf1, testPdf2],
|
||||||
|
outputPath: path.join(process.cwd(), 'storage', 'pdf-output', 'test-merged.pdf'),
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Mesclagem concluída:');
|
||||||
|
console.log(' Arquivo salvo em:', outputPath);
|
||||||
|
|
||||||
|
// Limpa o arquivo de teste
|
||||||
|
await fs.unlink(outputPath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testImagesToPDF() {
|
||||||
|
console.log('\n=== Testando: Imagens para PDF ===');
|
||||||
|
try {
|
||||||
|
const testImage1 = path.join(process.cwd(), 'test', 'image1.png');
|
||||||
|
const testImage2 = path.join(process.cwd(), 'test', 'image2.png');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testImage1);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Imagens de teste não encontradas. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const imagePaths = [testImage1];
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testImage2);
|
||||||
|
imagePaths.push(testImage2);
|
||||||
|
} catch {
|
||||||
|
// Ignora se a segunda imagem não existe
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPath = await PDFService.imagesToPDF({
|
||||||
|
imagePaths,
|
||||||
|
outputPath: path.join(process.cwd(), 'storage', 'pdf-output', 'test-images.pdf'),
|
||||||
|
fitToPage: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Conversão concluída:');
|
||||||
|
console.log(' Imagens processadas:', imagePaths.length);
|
||||||
|
console.log(' Arquivo salvo em:', outputPath);
|
||||||
|
|
||||||
|
// Limpa o arquivo de teste
|
||||||
|
await fs.unlink(outputPath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testPDFToImages() {
|
||||||
|
console.log('\n=== Testando: PDF para Imagens ===');
|
||||||
|
try {
|
||||||
|
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testPdfPath);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPaths = await PDFService.pdfToImages(testPdfPath, {
|
||||||
|
format: 'png',
|
||||||
|
quality: 95,
|
||||||
|
density: 150, // Menor DPI para teste mais rápido
|
||||||
|
pages: [1], // Apenas primeira página
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Conversão concluída:');
|
||||||
|
console.log(' Imagens criadas:', outputPaths.length);
|
||||||
|
|
||||||
|
// Limpa os arquivos de teste
|
||||||
|
for (const outputPath of outputPaths) {
|
||||||
|
await fs.unlink(outputPath);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testOCR() {
|
||||||
|
console.log('\n=== Testando: OCR ===');
|
||||||
|
console.log('⚠️ OCR pode levar vários segundos. Aguarde...');
|
||||||
|
try {
|
||||||
|
const testPdfPath = path.join(process.cwd(), 'test', 'sample-text.pdf');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.access(testPdfPath);
|
||||||
|
} catch {
|
||||||
|
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await PDFService.performOCR(testPdfPath, {
|
||||||
|
language: 'por',
|
||||||
|
pages: [1], // Apenas primeira página
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ OCR concluído:');
|
||||||
|
console.log(' Confiança:', result.confidence.toFixed(2), '%');
|
||||||
|
console.log(' Páginas processadas:', result.pages.length);
|
||||||
|
console.log(' Texto extraído (primeiros 100 caracteres):');
|
||||||
|
console.log(' ', result.text.substring(0, 100).replace(/\n/g, ' '));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Erro:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('╔════════════════════════════════════════════╗');
|
||||||
|
console.log('║ Teste de Operações de PDF ║');
|
||||||
|
console.log('╚════════════════════════════════════════════╝');
|
||||||
|
|
||||||
|
console.log('\nPré-requisitos:');
|
||||||
|
console.log('- Coloque arquivos de teste na pasta "test/"');
|
||||||
|
console.log('- sample.pdf: PDF com múltiplas páginas');
|
||||||
|
console.log('- sample1.pdf e sample2.pdf: PDFs para mesclagem');
|
||||||
|
console.log('- image1.png e image2.png: Imagens para conversão');
|
||||||
|
console.log('- sample-text.pdf: PDF com texto para OCR');
|
||||||
|
|
||||||
|
// Criar diretório de teste se não existir
|
||||||
|
const testDir = path.join(process.cwd(), 'test');
|
||||||
|
try {
|
||||||
|
await fs.mkdir(testDir, { recursive: true });
|
||||||
|
} catch {
|
||||||
|
// Ignora se já existe
|
||||||
|
}
|
||||||
|
|
||||||
|
await PDFService.initialize();
|
||||||
|
|
||||||
|
await testPDFInfo();
|
||||||
|
await testCompression();
|
||||||
|
await testSplit();
|
||||||
|
await testMerge();
|
||||||
|
await testImagesToPDF();
|
||||||
|
await testPDFToImages();
|
||||||
|
await testOCR();
|
||||||
|
|
||||||
|
console.log('\n╔════════════════════════════════════════════╗');
|
||||||
|
console.log('║ Testes concluídos! ║');
|
||||||
|
console.log('╚════════════════════════════════════════════╝\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.then(() => process.exit(0))
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('\n❌ Erro fatal durante os testes:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
+9
-7
@@ -49,9 +49,9 @@ import { NovoCalculo } from './components/calculos/NovoCalculo';
|
|||||||
import { DetalhesCalculo } from './components/calculos/DetalhesCalculo';
|
import { DetalhesCalculo } from './components/calculos/DetalhesCalculo';
|
||||||
import { NovoPensaoAlimenticia } from './components/calculos/NovoPensaoAlimenticia';
|
import { NovoPensaoAlimenticia } from './components/calculos/NovoPensaoAlimenticia';
|
||||||
import { DetalhePensaoAlimenticia } from './components/calculos/DetalhePensaoAlimenticia';
|
import { DetalhePensaoAlimenticia } from './components/calculos/DetalhePensaoAlimenticia';
|
||||||
import WebProofCapture from './components/provas/WebProofCapture';
|
|
||||||
import WebProofReport from './components/provas/WebProofReport';
|
// Importar componente de manipulação de PDF
|
||||||
import WebProofList from './components/provas/WebProofList';
|
import { PDFManipulationPage } from './components/pdf/PDFManipulationPage';
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
@@ -130,10 +130,12 @@ const router = createBrowserRouter(
|
|||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Rotas de Captura Web */}
|
{/* Rota para Manipulação de PDF */}
|
||||||
<Route path="/web-proofs" element={<WebProofList />} />
|
<Route path="/pdf" element={
|
||||||
<Route path="/web-proofs/capture" element={<WebProofCapture />} />
|
<ProtectedRoute>
|
||||||
<Route path="/web-proofs/relatorio/:sessionId" element={<WebProofReport />} />
|
<PDFManipulationPage />
|
||||||
|
</ProtectedRoute>
|
||||||
|
} />
|
||||||
</Route>
|
</Route>
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="*" element={<Navigate to="/login" />} />
|
<Route path="*" element={<Navigate to="/login" />} />
|
||||||
|
|||||||
@@ -1,104 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../../hooks/useAuth';
|
|
||||||
import {
|
|
||||||
HomeIcon,
|
|
||||||
DocumentTextIcon,
|
|
||||||
UserIcon,
|
|
||||||
CogIcon,
|
|
||||||
LogoutIcon,
|
|
||||||
ShieldCheckIcon,
|
|
||||||
ViewGridIcon,
|
|
||||||
ClipboardListIcon
|
|
||||||
} from '@heroicons/react/outline';
|
|
||||||
|
|
||||||
const Sidebar: React.FC = () => {
|
|
||||||
const { pathname } = useLocation();
|
|
||||||
const { user, logout } = useAuth();
|
|
||||||
|
|
||||||
const isActive = (path: string) => {
|
|
||||||
return pathname === path ? 'bg-blue-500 text-white' : 'text-gray-700';
|
|
||||||
};
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{
|
|
||||||
name: 'Início',
|
|
||||||
icon: HomeIcon,
|
|
||||||
href: '/'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Provas Digitais',
|
|
||||||
icon: DocumentTextIcon,
|
|
||||||
children: [
|
|
||||||
{ name: 'Verificar Prova', href: '/provas/verificar' },
|
|
||||||
{ name: 'Enviar Prova', href: '/provas/upload' },
|
|
||||||
{ name: 'Status da Prova', href: '/provas/status' },
|
|
||||||
{ name: 'Captura Web', href: '/web-proofs/capture' },
|
|
||||||
{ name: 'Relatórios Web', href: '/web-proofs' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Usuário',
|
|
||||||
icon: UserIcon,
|
|
||||||
href: '/profile'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Configurações',
|
|
||||||
icon: CogIcon,
|
|
||||||
href: '/settings'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Sair',
|
|
||||||
icon: LogoutIcon,
|
|
||||||
action: logout
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="bg-white shadow-md rounded-lg p-4">
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-800">Painel de Controle</h2>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav>
|
|
||||||
<ul className="space-y-2">
|
|
||||||
{menuItems.map((item) => (
|
|
||||||
<li key={item.name}>
|
|
||||||
{item.children ? (
|
|
||||||
<div>
|
|
||||||
<p className="text-xs font-semibold text-gray-500 uppercase">{item.name}</p>
|
|
||||||
<ul className="mt-1 space-y-1">
|
|
||||||
{item.children.map((child) => (
|
|
||||||
<li key={child.name}>
|
|
||||||
<Link
|
|
||||||
to={child.href}
|
|
||||||
className={`flex items-center p-2 text-sm rounded-md transition-all duration-200
|
|
||||||
${isActive(child.href)} hover:bg-blue-600 hover:text-white`}
|
|
||||||
>
|
|
||||||
<ViewGridIcon className="w-5 h-5 mr-2" />
|
|
||||||
{child.name}
|
|
||||||
</Link>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Link
|
|
||||||
to={item.href}
|
|
||||||
onClick={item.action}
|
|
||||||
className={`flex items-center p-2 text-sm rounded-md transition-all duration-200
|
|
||||||
${isActive(item.href)} hover:bg-blue-600 hover:text-white`}
|
|
||||||
>
|
|
||||||
<item.icon className="w-5 h-5 mr-2" />
|
|
||||||
{item.name}
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Sidebar;
|
|
||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
CurrencyDollarIcon,
|
CurrencyDollarIcon,
|
||||||
CalculatorIcon,
|
CalculatorIcon,
|
||||||
BriefcaseIcon,
|
BriefcaseIcon,
|
||||||
|
DocumentDuplicateIcon,
|
||||||
} from "@heroicons/react/24/outline";
|
} from "@heroicons/react/24/outline";
|
||||||
import { Menu, Transition } from "@headlessui/react";
|
import { Menu, Transition } from "@headlessui/react";
|
||||||
import api from "../../services/api";
|
import api from "../../services/api";
|
||||||
@@ -91,6 +92,7 @@ export const MainLayout: React.FC = () => {
|
|||||||
{ path: "/atendimentos", label: "Atendimentos", icon: UserIcon },
|
{ path: "/atendimentos", label: "Atendimentos", icon: UserIcon },
|
||||||
{ path: "/tarefas", label: "Tarefas", icon: ClipboardDocumentCheckIcon },
|
{ path: "/tarefas", label: "Tarefas", icon: ClipboardDocumentCheckIcon },
|
||||||
{ path: "/documentos", label: "Documentos", icon: DocumentTextIcon },
|
{ path: "/documentos", label: "Documentos", icon: DocumentTextIcon },
|
||||||
|
{ path: "/pdf", label: "PDFs", icon: DocumentDuplicateIcon },
|
||||||
{
|
{
|
||||||
path: null,
|
path: null,
|
||||||
label: "Cálculos",
|
label: "Cálculos",
|
||||||
|
|||||||
@@ -0,0 +1,885 @@
|
|||||||
|
/// <reference types="react" />
|
||||||
|
import React, { useState, useCallback } from 'react';
|
||||||
|
import { useDropzone } from 'react-dropzone';
|
||||||
|
import axios from 'axios';
|
||||||
|
import { toast } from 'react-toastify';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
import {
|
||||||
|
DocumentIcon,
|
||||||
|
CloudArrowUpIcon,
|
||||||
|
ArrowsPointingInIcon,
|
||||||
|
ScissorsIcon,
|
||||||
|
ArrowsUpDownIcon,
|
||||||
|
PhotoIcon,
|
||||||
|
DocumentTextIcon,
|
||||||
|
InformationCircleIcon,
|
||||||
|
ArrowDownTrayIcon,
|
||||||
|
ClockIcon,
|
||||||
|
} from '@heroicons/react/24/outline';
|
||||||
|
|
||||||
|
interface OperationResult {
|
||||||
|
operacaoId: string;
|
||||||
|
outputPaths?: string[];
|
||||||
|
outputPath?: string;
|
||||||
|
zipPath?: string;
|
||||||
|
processingTime?: number;
|
||||||
|
reduction?: number;
|
||||||
|
filesCreated?: number;
|
||||||
|
text?: string;
|
||||||
|
confidence?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type OperationType =
|
||||||
|
| 'compress'
|
||||||
|
| 'split'
|
||||||
|
| 'merge'
|
||||||
|
| 'pdfToImages'
|
||||||
|
| 'imagesToPDF'
|
||||||
|
| 'ocr'
|
||||||
|
| 'info';
|
||||||
|
|
||||||
|
export const PDFManipulationPage: React.FC = () => {
|
||||||
|
const { getToken } = useAuth();
|
||||||
|
const [selectedOperation, setSelectedOperation] = useState<OperationType>('compress');
|
||||||
|
const [files, setFiles] = useState<File[]>([]);
|
||||||
|
const [processing, setProcessing] = useState(false);
|
||||||
|
const [result, setResult] = useState<OperationResult | null>(null);
|
||||||
|
const [history, setHistory] = useState<any[]>([]);
|
||||||
|
|
||||||
|
// Configurações para cada operação
|
||||||
|
const [compressQuality, setCompressQuality] = useState<'extreme' | 'low' | 'medium' | 'high'>('medium');
|
||||||
|
const [enableOCR, setEnableOCR] = useState(false);
|
||||||
|
const [splitType, setSplitType] = useState<'pages' | 'range' | 'chunks'>('pages');
|
||||||
|
const [splitPages, setSplitPages] = useState<string>('1,2,3');
|
||||||
|
const [splitRanges, setSplitRanges] = useState<string>('1-5,6-10');
|
||||||
|
const [chunkSize, setChunkSize] = useState(5);
|
||||||
|
const [imageFormat, setImageFormat] = useState<'png' | 'jpg' | 'webp'>('png');
|
||||||
|
const [imageQuality, setImageQuality] = useState(95);
|
||||||
|
const [imageDensity, setImageDensity] = useState(300);
|
||||||
|
const [ocrLanguage, setOcrLanguage] = useState('por');
|
||||||
|
|
||||||
|
const onDrop = useCallback((acceptedFiles: File[]) => {
|
||||||
|
setFiles((prev) => [...prev, ...acceptedFiles]);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||||
|
onDrop,
|
||||||
|
accept: {
|
||||||
|
'application/pdf': ['.pdf'],
|
||||||
|
'image/*': ['.png', '.jpg', '.jpeg', '.webp'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const removeFile = (index: number) => {
|
||||||
|
setFiles((prev) => prev.filter((_, i) => i !== index));
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearFiles = () => {
|
||||||
|
setFiles([]);
|
||||||
|
setResult(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const processFiles = async () => {
|
||||||
|
if (files.length === 0) {
|
||||||
|
toast.error('Selecione pelo menos um arquivo');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setProcessing(true);
|
||||||
|
setResult(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
files.forEach((file) => {
|
||||||
|
formData.append('files', file);
|
||||||
|
});
|
||||||
|
|
||||||
|
const token = getToken();
|
||||||
|
const config = {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'multipart/form-data',
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
timeout: 600000, // 10 minutos para operações longas (compressão, OCR, etc)
|
||||||
|
};
|
||||||
|
|
||||||
|
let response;
|
||||||
|
|
||||||
|
switch (selectedOperation) {
|
||||||
|
case 'compress':
|
||||||
|
formData.append('quality', compressQuality);
|
||||||
|
formData.append('enableOCR', enableOCR.toString());
|
||||||
|
response = await axios.post('/api/pdf/compress', formData, config);
|
||||||
|
toast.success('PDFs comprimidos com sucesso!');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'split':
|
||||||
|
formData.append('splitType', splitType);
|
||||||
|
if (splitType === 'pages') {
|
||||||
|
const pages = splitPages.split(',').map((p) => parseInt(p.trim()));
|
||||||
|
formData.append('pages', JSON.stringify(pages));
|
||||||
|
} else if (splitType === 'range') {
|
||||||
|
const ranges = splitRanges.split(',').map((r) => {
|
||||||
|
const [start, end] = r.trim().split('-').map(Number);
|
||||||
|
return { start, end };
|
||||||
|
});
|
||||||
|
formData.append('ranges', JSON.stringify(ranges));
|
||||||
|
} else {
|
||||||
|
formData.append('chunkSize', chunkSize.toString());
|
||||||
|
}
|
||||||
|
response = await axios.post('/api/pdf/split', formData, config);
|
||||||
|
toast.success('PDF dividido com sucesso!');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'merge':
|
||||||
|
formData.append('enableOCR', enableOCR.toString());
|
||||||
|
response = await axios.post('/api/pdf/merge', formData, config);
|
||||||
|
toast.success('PDFs mesclados com sucesso!');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'pdfToImages':
|
||||||
|
formData.append('format', imageFormat);
|
||||||
|
formData.append('quality', imageQuality.toString());
|
||||||
|
formData.append('density', imageDensity.toString());
|
||||||
|
response = await axios.post('/api/pdf/pdf-to-images', formData, config);
|
||||||
|
toast.success('PDF convertido em imagens!');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'imagesToPDF':
|
||||||
|
formData.append('enableOCR', enableOCR.toString());
|
||||||
|
formData.append('fitToPage', 'true');
|
||||||
|
response = await axios.post('/api/pdf/images-to-pdf', formData, config);
|
||||||
|
toast.success('Imagens convertidas em PDF!');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'ocr':
|
||||||
|
formData.append('language', ocrLanguage);
|
||||||
|
response = await axios.post('/api/pdf/ocr', formData, config);
|
||||||
|
toast.success('OCR realizado com sucesso!');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'info':
|
||||||
|
response = await axios.post('/api/pdf/info', formData, config);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
setResult(response.data);
|
||||||
|
loadHistory();
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Erro ao processar arquivos:', error);
|
||||||
|
toast.error(error.response?.data?.message || 'Erro ao processar arquivos');
|
||||||
|
} finally {
|
||||||
|
setProcessing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadHistory = async () => {
|
||||||
|
try {
|
||||||
|
const token = getToken();
|
||||||
|
const response = await axios.get('/api/pdf/history', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
setHistory(response.data.operacoes || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao carregar histórico:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const downloadFile = async (operacaoId: string, fileIndex: number) => {
|
||||||
|
try {
|
||||||
|
const token = getToken();
|
||||||
|
const response = await axios.get(`/api/pdf/download/${operacaoId}/${fileIndex}`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
responseType: 'blob',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Extrai o nome do arquivo do header Content-Disposition
|
||||||
|
const contentDisposition = response.headers['content-disposition'];
|
||||||
|
let fileName = `arquivo-${fileIndex}`;
|
||||||
|
|
||||||
|
if (contentDisposition) {
|
||||||
|
const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
|
||||||
|
if (matches != null && matches[1]) {
|
||||||
|
fileName = matches[1].replace(/['"]/g, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usa o Content-Type correto do servidor
|
||||||
|
const contentType = response.headers['content-type'] || 'application/octet-stream';
|
||||||
|
|
||||||
|
console.log(`Download frontend: ${fileName} (${contentType})`);
|
||||||
|
|
||||||
|
// Cria o blob com o tipo correto
|
||||||
|
const blob = new Blob([response.data], { type: contentType });
|
||||||
|
const url = window.URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute('download', fileName);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
|
||||||
|
// Libera a memória do blob URL
|
||||||
|
setTimeout(() => window.URL.revokeObjectURL(url), 100);
|
||||||
|
|
||||||
|
toast.success('Download iniciado!');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao fazer download:', error);
|
||||||
|
toast.error('Erro ao fazer download');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteOperation = async (operacaoId: string) => {
|
||||||
|
if (!window.confirm('Deseja realmente deletar esta operação e seus arquivos?')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = getToken();
|
||||||
|
await axios.delete(`/api/pdf/operation/${operacaoId}`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
|
||||||
|
toast.success('Operação deletada com sucesso!');
|
||||||
|
loadHistory();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao deletar operação:', error);
|
||||||
|
toast.error('Erro ao deletar operação');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearAllHistory = async () => {
|
||||||
|
if (!window.confirm('⚠️ ATENÇÃO: Isso irá deletar TODO o histórico e TODOS os arquivos armazenados. Esta ação não pode ser desfeita. Deseja continuar?')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = getToken();
|
||||||
|
const response = await axios.delete('/api/pdf/history/clear', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
|
||||||
|
toast.success(`Histórico limpo! ${response.data.operacoesRemovidas} operações removidas.`);
|
||||||
|
setHistory([]);
|
||||||
|
setResult(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao limpar histórico:', error);
|
||||||
|
toast.error('Erro ao limpar histórico');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanupOldFiles = async () => {
|
||||||
|
if (!window.confirm('Deseja remover operações com mais de 24 horas?')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = getToken();
|
||||||
|
const response = await axios.delete('/api/pdf/history/cleanup?hours=24', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
|
||||||
|
toast.success(`${response.data.operacoesRemovidas} operações antigas removidas!`);
|
||||||
|
loadHistory();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao limpar arquivos antigos:', error);
|
||||||
|
toast.error('Erro ao limpar arquivos antigos');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
loadHistory();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const operations = [
|
||||||
|
{
|
||||||
|
id: 'compress' as OperationType,
|
||||||
|
name: 'Comprimir PDF',
|
||||||
|
icon: ArrowsPointingInIcon,
|
||||||
|
description: 'Reduza o tamanho mantendo a qualidade',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'split' as OperationType,
|
||||||
|
name: 'Dividir PDF',
|
||||||
|
icon: ScissorsIcon,
|
||||||
|
description: 'Separe páginas específicas',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'merge' as OperationType,
|
||||||
|
name: 'Mesclar PDFs',
|
||||||
|
icon: ArrowsUpDownIcon,
|
||||||
|
description: 'Combine múltiplos PDFs',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pdfToImages' as OperationType,
|
||||||
|
name: 'PDF para Imagens',
|
||||||
|
icon: PhotoIcon,
|
||||||
|
description: 'Converta páginas em imagens',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'imagesToPDF' as OperationType,
|
||||||
|
name: 'Imagens para PDF',
|
||||||
|
icon: DocumentIcon,
|
||||||
|
description: 'Crie PDF a partir de imagens',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ocr' as OperationType,
|
||||||
|
name: 'OCR',
|
||||||
|
icon: DocumentTextIcon,
|
||||||
|
description: 'Extraia texto de PDFs',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'info' as OperationType,
|
||||||
|
name: 'Informações',
|
||||||
|
icon: InformationCircleIcon,
|
||||||
|
description: 'Obtenha detalhes do PDF',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const formatBytes = (bytes: number) => {
|
||||||
|
if (bytes === 0) return '0 Bytes';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50 py-8">
|
||||||
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
|
<div className="mb-8">
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900">Manipulação de PDFs</h1>
|
||||||
|
<p className="mt-2 text-gray-600">
|
||||||
|
Ferramentas completas para trabalhar com arquivos PDF
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Seleção de operação */}
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4 mb-8">
|
||||||
|
{operations.map((op) => (
|
||||||
|
<button
|
||||||
|
key={op.id}
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedOperation(op.id);
|
||||||
|
clearFiles();
|
||||||
|
}}
|
||||||
|
className={`p-4 rounded-lg border-2 transition-all ${
|
||||||
|
selectedOperation === op.id
|
||||||
|
? 'border-blue-500 bg-blue-50 text-blue-700'
|
||||||
|
: 'border-gray-200 bg-white hover:border-gray-300'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<op.icon className="h-8 w-8 mx-auto mb-2" />
|
||||||
|
<div className="text-sm font-medium">{op.name}</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||||
|
{/* Área principal */}
|
||||||
|
<div className="lg:col-span-2 space-y-6">
|
||||||
|
{/* Upload de arquivos */}
|
||||||
|
<div className="bg-white rounded-lg shadow p-6">
|
||||||
|
<h2 className="text-xl font-semibold mb-4">Arquivos</h2>
|
||||||
|
|
||||||
|
<div
|
||||||
|
{...getRootProps()}
|
||||||
|
className={`border-2 border-dashed rounded-lg p-12 text-center cursor-pointer transition-colors ${
|
||||||
|
isDragActive
|
||||||
|
? 'border-blue-500 bg-blue-50'
|
||||||
|
: 'border-gray-300 hover:border-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input {...getInputProps()} />
|
||||||
|
<CloudArrowUpIcon className="h-12 w-12 mx-auto text-gray-400 mb-4" />
|
||||||
|
{isDragActive ? (
|
||||||
|
<p className="text-blue-600">Solte os arquivos aqui...</p>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-600 mb-2">
|
||||||
|
Arraste e solte arquivos aqui, ou clique para selecionar
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
PDFs e imagens (PNG, JPG, WEBP)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Lista de arquivos */}
|
||||||
|
{files.length > 0 && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<div className="flex justify-between items-center mb-2">
|
||||||
|
<h3 className="font-medium">
|
||||||
|
Arquivos selecionados ({files.length})
|
||||||
|
</h3>
|
||||||
|
<button
|
||||||
|
onClick={clearFiles}
|
||||||
|
className="text-sm text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
Limpar todos
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{files.map((file, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center justify-between p-3 bg-gray-50 rounded"
|
||||||
|
>
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<DocumentIcon className="h-5 w-5 text-gray-400" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">{file.name}</p>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
{formatBytes(file.size)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => removeFile(index)}
|
||||||
|
className="text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
Remover
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Configurações específicas */}
|
||||||
|
<div className="bg-white rounded-lg shadow p-6">
|
||||||
|
<h2 className="text-xl font-semibold mb-4">Configurações</h2>
|
||||||
|
|
||||||
|
{selectedOperation === 'compress' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
Nível de Compressão
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={compressQuality}
|
||||||
|
onChange={(e) => setCompressQuality(e.target.value as any)}
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
>
|
||||||
|
<option value="extreme">Extrema (72 DPI) - Máxima redução, visualização na tela</option>
|
||||||
|
<option value="low">Alta compressão (100 DPI) - Arquivos pequenos</option>
|
||||||
|
<option value="medium">Equilibrada (150 DPI) - Recomendado</option>
|
||||||
|
<option value="high">Qualidade (200 DPI) - Para impressão</option>
|
||||||
|
</select>
|
||||||
|
<p className="text-xs text-gray-500 mt-2">
|
||||||
|
💡 Usa Ghostscript, mesmo motor do iLovePDF e SmallPDF
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="enableOCR"
|
||||||
|
checked={enableOCR}
|
||||||
|
onChange={(e) => setEnableOCR(e.target.checked)}
|
||||||
|
className="h-4 w-4 text-blue-600 rounded"
|
||||||
|
/>
|
||||||
|
<label htmlFor="enableOCR" className="text-sm font-medium">
|
||||||
|
Adicionar camada de OCR (tornar PDF pesquisável)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
OCR torna o PDF pesquisável. É instantâneo para PDFs digitais.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedOperation === 'split' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
Tipo de divisão
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={splitType}
|
||||||
|
onChange={(e) => setSplitType(e.target.value as any)}
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
>
|
||||||
|
<option value="pages">Páginas específicas</option>
|
||||||
|
<option value="range">Intervalos</option>
|
||||||
|
<option value="chunks">Chunks (partes iguais)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{splitType === 'pages' && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
Páginas (separadas por vírgula)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={splitPages}
|
||||||
|
onChange={(e) => setSplitPages(e.target.value)}
|
||||||
|
placeholder="1,2,3,5,8"
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{splitType === 'range' && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
Intervalos (ex: 1-5,6-10)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={splitRanges}
|
||||||
|
onChange={(e) => setSplitRanges(e.target.value)}
|
||||||
|
placeholder="1-5,6-10,11-15"
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{splitType === 'chunks' && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
Páginas por chunk
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={chunkSize}
|
||||||
|
onChange={(e) => setChunkSize(parseInt(e.target.value))}
|
||||||
|
min="1"
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedOperation === 'pdfToImages' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Formato</label>
|
||||||
|
<select
|
||||||
|
value={imageFormat}
|
||||||
|
onChange={(e) => setImageFormat(e.target.value as any)}
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
>
|
||||||
|
<option value="png">PNG</option>
|
||||||
|
<option value="jpg">JPG</option>
|
||||||
|
<option value="webp">WEBP</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
Qualidade ({imageQuality}%)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min="50"
|
||||||
|
max="100"
|
||||||
|
value={imageQuality}
|
||||||
|
onChange={(e) => setImageQuality(parseInt(e.target.value))}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
DPI ({imageDensity})
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min="150"
|
||||||
|
max="600"
|
||||||
|
step="50"
|
||||||
|
value={imageDensity}
|
||||||
|
onChange={(e) => setImageDensity(parseInt(e.target.value))}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedOperation === 'ocr' && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Idioma</label>
|
||||||
|
<select
|
||||||
|
value={ocrLanguage}
|
||||||
|
onChange={(e) => setOcrLanguage(e.target.value)}
|
||||||
|
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||||
|
>
|
||||||
|
<option value="por">Português</option>
|
||||||
|
<option value="eng">Inglês</option>
|
||||||
|
<option value="spa">Espanhol</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedOperation === 'merge' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Selecione 2 ou mais PDFs para mesclar em um único arquivo.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="enableOCRMerge"
|
||||||
|
checked={enableOCR}
|
||||||
|
onChange={(e) => setEnableOCR(e.target.checked)}
|
||||||
|
className="h-4 w-4 text-blue-600 rounded"
|
||||||
|
/>
|
||||||
|
<label htmlFor="enableOCRMerge" className="text-sm font-medium">
|
||||||
|
Adicionar camada de OCR ao PDF mesclado
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
⚠️ OCR aumenta significativamente o tempo de processamento
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedOperation === 'imagesToPDF' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Converte múltiplas imagens em um único arquivo PDF.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="enableOCRImages"
|
||||||
|
checked={enableOCR}
|
||||||
|
onChange={(e) => setEnableOCR(e.target.checked)}
|
||||||
|
className="h-4 w-4 text-blue-600 rounded"
|
||||||
|
/>
|
||||||
|
<label htmlFor="enableOCRImages" className="text-sm font-medium">
|
||||||
|
Adicionar camada de OCR (tornar PDF pesquisável)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
⚠️ OCR aumenta significativamente o tempo de processamento
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={processFiles}
|
||||||
|
disabled={processing || files.length === 0}
|
||||||
|
className={`mt-6 w-full py-3 rounded-lg font-medium transition-colors ${
|
||||||
|
processing || files.length === 0
|
||||||
|
? 'bg-gray-300 text-gray-500 cursor-not-allowed'
|
||||||
|
: 'bg-blue-600 text-white hover:bg-blue-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{processing ? (
|
||||||
|
<span className="flex items-center justify-center">
|
||||||
|
<svg
|
||||||
|
className="animate-spin h-5 w-5 mr-2"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle
|
||||||
|
className="opacity-25"
|
||||||
|
cx="12"
|
||||||
|
cy="12"
|
||||||
|
r="10"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="4"
|
||||||
|
></circle>
|
||||||
|
<path
|
||||||
|
className="opacity-75"
|
||||||
|
fill="currentColor"
|
||||||
|
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||||
|
></path>
|
||||||
|
</svg>
|
||||||
|
Processando...
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
'Processar'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Resultado */}
|
||||||
|
{result && (
|
||||||
|
<div className="bg-white rounded-lg shadow p-6">
|
||||||
|
<h2 className="text-xl font-semibold mb-4">Resultado</h2>
|
||||||
|
|
||||||
|
{selectedOperation === 'compress' && result.reduction !== undefined && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-green-600 font-medium">
|
||||||
|
Redução de {result.reduction.toFixed(2)}%
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Tempo de processamento: {result.processingTime}ms
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(result.outputPaths || result.outputPath || result.zipPath) && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<p className="font-medium mb-2">Arquivos gerados:</p>
|
||||||
|
|
||||||
|
{/* Botão de download ZIP (se disponível) */}
|
||||||
|
{result.zipPath && (
|
||||||
|
<button
|
||||||
|
onClick={() => downloadFile(result.operacaoId, 0)}
|
||||||
|
className="flex items-center space-x-2 w-full p-3 mb-3 bg-blue-50 hover:bg-blue-100 rounded border-2 border-blue-300"
|
||||||
|
>
|
||||||
|
<ArrowDownTrayIcon className="h-6 w-6 text-blue-600" />
|
||||||
|
<div className="text-left">
|
||||||
|
<span className="text-sm font-semibold text-blue-900">
|
||||||
|
📦 Download ZIP (Todos os arquivos)
|
||||||
|
</span>
|
||||||
|
<p className="text-xs text-blue-700">
|
||||||
|
Recomendado para múltiplos arquivos
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Arquivos individuais */}
|
||||||
|
{result.outputPaths?.map((path, index) => {
|
||||||
|
// Determina o nome do arquivo baseado na operação
|
||||||
|
let fileName = `Arquivo ${index + 1}`;
|
||||||
|
if (selectedOperation === 'pdfToImages') {
|
||||||
|
fileName = `Imagem ${index + 1}`;
|
||||||
|
} else if (selectedOperation === 'split') {
|
||||||
|
fileName = `Página ${index + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={index}
|
||||||
|
onClick={() => downloadFile(result.operacaoId, result.zipPath ? index + 1 : index)}
|
||||||
|
className="flex items-center space-x-2 w-full p-2 hover:bg-gray-50 rounded"
|
||||||
|
>
|
||||||
|
<ArrowDownTrayIcon className="h-5 w-5 text-blue-600" />
|
||||||
|
<span className="text-sm">{fileName}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{result.outputPath && !result.outputPaths && (
|
||||||
|
<button
|
||||||
|
onClick={() => downloadFile(result.operacaoId, result.zipPath ? 1 : 0)}
|
||||||
|
className="flex items-center space-x-2 w-full p-2 hover:bg-gray-50 rounded"
|
||||||
|
>
|
||||||
|
<ArrowDownTrayIcon className="h-5 w-5 text-blue-600" />
|
||||||
|
<span className="text-sm">Download</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedOperation === 'ocr' && result.text && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<p className="font-medium mb-2">Texto extraído:</p>
|
||||||
|
<div className="bg-gray-50 p-4 rounded max-h-64 overflow-y-auto">
|
||||||
|
<pre className="text-sm whitespace-pre-wrap">{result.text}</pre>
|
||||||
|
</div>
|
||||||
|
{result.confidence && (
|
||||||
|
<p className="text-sm text-gray-600 mt-2">
|
||||||
|
Confiança: {result.confidence.toFixed(2)}%
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Histórico */}
|
||||||
|
<div className="lg:col-span-1">
|
||||||
|
<div className="bg-white rounded-lg shadow p-6 sticky top-8">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-xl font-semibold">Histórico</h2>
|
||||||
|
{history.length > 0 && (
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<button
|
||||||
|
onClick={cleanupOldFiles}
|
||||||
|
className="text-xs px-2 py-1 bg-yellow-100 hover:bg-yellow-200 text-yellow-800 rounded transition-colors"
|
||||||
|
title="Remover operações com mais de 24 horas"
|
||||||
|
>
|
||||||
|
🕐 Limpar Antigos
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={clearAllHistory}
|
||||||
|
className="text-xs px-2 py-1 bg-red-100 hover:bg-red-200 text-red-800 rounded transition-colors"
|
||||||
|
title="Apagar todo o histórico e arquivos"
|
||||||
|
>
|
||||||
|
🗑️ Limpar Tudo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{history.length === 0 ? (
|
||||||
|
<p className="text-gray-500 text-sm">Nenhuma operação ainda</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3 max-h-96 overflow-y-auto">
|
||||||
|
{history.map((op) => (
|
||||||
|
<div key={op.id} className="border-b pb-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm font-medium">
|
||||||
|
{op.tipoOperacao.replace('_', ' ')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<span
|
||||||
|
className={`text-xs px-2 py-1 rounded ${
|
||||||
|
op.status === 'CONCLUIDO'
|
||||||
|
? 'bg-green-100 text-green-800'
|
||||||
|
: op.status === 'ERRO'
|
||||||
|
? 'bg-red-100 text-red-800'
|
||||||
|
: 'bg-yellow-100 text-yellow-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{op.status}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => deleteOperation(op.id)}
|
||||||
|
className="text-red-600 hover:text-red-800 hover:bg-red-50 p-1 rounded transition-colors"
|
||||||
|
title="Deletar esta operação"
|
||||||
|
>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
|
||||||
|
<path fillRule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-xs text-gray-500 mt-1">
|
||||||
|
<ClockIcon className="h-3 w-3 mr-1" />
|
||||||
|
{new Date(op.criadoEm).toLocaleString('pt-BR')}
|
||||||
|
</div>
|
||||||
|
{op.tempoProcessamento && (
|
||||||
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
|
{op.tempoProcessamento}ms
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{op.status === 'CONCLUIDO' && op.arquivosResultado && op.arquivosResultado.length > 0 && (
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
{op.arquivosResultado.map((arquivo: string, index: number) => (
|
||||||
|
<button
|
||||||
|
key={index}
|
||||||
|
onClick={() => downloadFile(op.id, index)}
|
||||||
|
className="flex items-center space-x-1 w-full text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 p-1 rounded"
|
||||||
|
>
|
||||||
|
<ArrowDownTrayIcon className="h-3 w-3" />
|
||||||
|
<span>Arquivo {index + 1}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,501 +0,0 @@
|
|||||||
import React, { useState, useRef, useEffect, useCallback } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { toast } from 'react-toastify';
|
|
||||||
|
|
||||||
interface CaptureSession {
|
|
||||||
id: string;
|
|
||||||
startTime: string;
|
|
||||||
status: 'PREPARANDO' | 'ATIVO' | 'GRAVANDO' | 'FINALIZANDO' | 'CONCLUIDO' | 'ERRO';
|
|
||||||
environment: {
|
|
||||||
sessionId: string;
|
|
||||||
userAgent: string;
|
|
||||||
viewportSize: { width: number; height: number };
|
|
||||||
ipAddress: string;
|
|
||||||
timestamp: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface WebProofMetadata {
|
|
||||||
networkData: {
|
|
||||||
sourceIP: string;
|
|
||||||
targetIP: string;
|
|
||||||
routePath: string[];
|
|
||||||
dnsRecords: any[];
|
|
||||||
};
|
|
||||||
timestamps: {
|
|
||||||
sessionStart: string;
|
|
||||||
captureStart: string;
|
|
||||||
captureEnd: string;
|
|
||||||
trustedTimestamp?: string;
|
|
||||||
};
|
|
||||||
hashes: {
|
|
||||||
sessionHash: string;
|
|
||||||
contentHash: string;
|
|
||||||
videoHash?: string;
|
|
||||||
pageHash: string;
|
|
||||||
};
|
|
||||||
technicalData: {
|
|
||||||
browserFingerprint: string;
|
|
||||||
navigationTrace: any[];
|
|
||||||
domSnapshot: string;
|
|
||||||
screenshots: string[];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const SESSION_STATES = {
|
|
||||||
PREPARING: 'PREPARANDO',
|
|
||||||
ACTIVE: 'ATIVO',
|
|
||||||
RECORDING: 'GRAVANDO',
|
|
||||||
FINALIZING: 'FINALIZANDO',
|
|
||||||
COMPLETED: 'CONCLUIDO',
|
|
||||||
ERROR: 'ERRO'
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export function WebProofCapture() {
|
|
||||||
const [session, setSession] = useState<CaptureSession | null>(null);
|
|
||||||
const [isRecording, setIsRecording] = useState(false);
|
|
||||||
const [targetUrl, setTargetUrl] = useState('');
|
|
||||||
const [captureDescription, setCaptureDescription] = useState('');
|
|
||||||
const [metadata, setMetadata] = useState<WebProofMetadata | null>(null);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [progress, setProgress] = useState(0);
|
|
||||||
const [screenshots, setScreenshots] = useState<string[]>([]);
|
|
||||||
|
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
|
||||||
const recordedChunksRef = useRef<Blob[]>([]);
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
// Inicializar ambiente isolado
|
|
||||||
const initializeIsolatedEnvironment = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setProgress(10);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
// Simular criação de ambiente isolado
|
|
||||||
const sessionId = `webproof_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
||||||
|
|
||||||
// Coletar informações do ambiente
|
|
||||||
const environmentData = {
|
|
||||||
sessionId,
|
|
||||||
userAgent: navigator.userAgent,
|
|
||||||
viewportSize: {
|
|
||||||
width: window.innerWidth,
|
|
||||||
height: window.innerHeight
|
|
||||||
},
|
|
||||||
ipAddress: await getClientIP(),
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
};
|
|
||||||
|
|
||||||
setProgress(30);
|
|
||||||
|
|
||||||
const newSession: CaptureSession = {
|
|
||||||
id: sessionId,
|
|
||||||
startTime: new Date().toISOString(),
|
|
||||||
status: SESSION_STATES.PREPARING,
|
|
||||||
environment: environmentData
|
|
||||||
};
|
|
||||||
|
|
||||||
setSession(newSession);
|
|
||||||
setProgress(50);
|
|
||||||
|
|
||||||
// Inicializar coleta de metadados
|
|
||||||
await initializeMetadataCollection(sessionId);
|
|
||||||
setProgress(100);
|
|
||||||
|
|
||||||
setSession(prev => prev ? { ...prev, status: SESSION_STATES.ACTIVE } : null);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao inicializar ambiente:', error);
|
|
||||||
setError('Falha ao inicializar ambiente isolado');
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Obter IP do cliente
|
|
||||||
const getClientIP = async (): Promise<string> => {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/web-proofs/client-info');
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Falha ao obter informações do cliente');
|
|
||||||
}
|
|
||||||
const data = await response.json();
|
|
||||||
return data.ip || '127.0.0.1';
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Erro ao obter IP do cliente:', error);
|
|
||||||
return '127.0.0.1';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Inicializar coleta de metadados
|
|
||||||
const initializeMetadataCollection = async (sessionId: string) => {
|
|
||||||
const initialMetadata: WebProofMetadata = {
|
|
||||||
networkData: {
|
|
||||||
sourceIP: await getClientIP(),
|
|
||||||
targetIP: '',
|
|
||||||
routePath: [],
|
|
||||||
dnsRecords: []
|
|
||||||
},
|
|
||||||
timestamps: {
|
|
||||||
sessionStart: new Date().toISOString(),
|
|
||||||
captureStart: '',
|
|
||||||
captureEnd: ''
|
|
||||||
},
|
|
||||||
hashes: {
|
|
||||||
sessionHash: await generateHash(sessionId),
|
|
||||||
contentHash: '',
|
|
||||||
pageHash: ''
|
|
||||||
},
|
|
||||||
technicalData: {
|
|
||||||
browserFingerprint: generateBrowserFingerprint(),
|
|
||||||
navigationTrace: [],
|
|
||||||
domSnapshot: '',
|
|
||||||
screenshots: []
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
setMetadata(initialMetadata);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Gerar hash seguro
|
|
||||||
const generateHash = async (data: string): Promise<string> => {
|
|
||||||
const encoder = new TextEncoder();
|
|
||||||
const dataBuffer = encoder.encode(data + Date.now());
|
|
||||||
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
|
|
||||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
||||||
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
|
||||||
};
|
|
||||||
|
|
||||||
// Gerar fingerprint do navegador
|
|
||||||
const generateBrowserFingerprint = (): string => {
|
|
||||||
const fingerprint = {
|
|
||||||
userAgent: navigator.userAgent,
|
|
||||||
language: navigator.language,
|
|
||||||
platform: navigator.platform,
|
|
||||||
cookieEnabled: navigator.cookieEnabled,
|
|
||||||
doNotTrack: navigator.doNotTrack,
|
|
||||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
||||||
screen: {
|
|
||||||
width: screen.width,
|
|
||||||
height: screen.height,
|
|
||||||
colorDepth: screen.colorDepth
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return btoa(JSON.stringify(fingerprint));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Validar URL
|
|
||||||
const validateUrl = (url: string): boolean => {
|
|
||||||
try {
|
|
||||||
new URL(url);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Iniciar captura
|
|
||||||
const startCapture = async () => {
|
|
||||||
if (!targetUrl.trim()) {
|
|
||||||
toast.error('Por favor, insira uma URL válida');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!validateUrl(targetUrl)) {
|
|
||||||
toast.error('URL inválida. Use formato: https://exemplo.com');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
setIsRecording(true);
|
|
||||||
setSession(prev => prev ? { ...prev, status: SESSION_STATES.RECORDING } : null);
|
|
||||||
|
|
||||||
// Atualizar metadados com início da captura
|
|
||||||
if (metadata) {
|
|
||||||
const updatedMetadata = {
|
|
||||||
...metadata,
|
|
||||||
timestamps: {
|
|
||||||
...metadata.timestamps,
|
|
||||||
captureStart: new Date().toISOString()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
setMetadata(updatedMetadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Navegar para URL alvo no iframe
|
|
||||||
if (iframeRef.current) {
|
|
||||||
iframeRef.current.src = targetUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
toast.success('Captura iniciada - ambiente isolado ativo');
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao iniciar captura:', error);
|
|
||||||
setError('Falha ao iniciar captura');
|
|
||||||
setIsRecording(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Capturar screenshot
|
|
||||||
const captureScreenshot = async () => {
|
|
||||||
try {
|
|
||||||
if (!iframeRef.current) return;
|
|
||||||
|
|
||||||
// Simular captura de screenshot
|
|
||||||
const timestamp = new Date().toISOString();
|
|
||||||
const screenshotData = `screenshot_${Date.now()}`;
|
|
||||||
|
|
||||||
setScreenshots(prev => [...prev, screenshotData]);
|
|
||||||
|
|
||||||
// Registrar ação nos metadados
|
|
||||||
if (metadata && isRecording) {
|
|
||||||
const updatedMetadata = {
|
|
||||||
...metadata,
|
|
||||||
technicalData: {
|
|
||||||
...metadata.technicalData,
|
|
||||||
screenshots: [...metadata.technicalData.screenshots, screenshotData],
|
|
||||||
navigationTrace: [...metadata.technicalData.navigationTrace, {
|
|
||||||
type: 'screenshot',
|
|
||||||
timestamp,
|
|
||||||
url: targetUrl
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
setMetadata(updatedMetadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
toast.success('Screenshot capturado');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao capturar screenshot:', error);
|
|
||||||
toast.error('Falha ao capturar screenshot');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Finalizar captura
|
|
||||||
const finalizeCaptureSession = async () => {
|
|
||||||
try {
|
|
||||||
setSession(prev => prev ? { ...prev, status: SESSION_STATES.FINALIZING } : null);
|
|
||||||
setIsRecording(false);
|
|
||||||
|
|
||||||
if (!metadata || !session) {
|
|
||||||
throw new Error('Sessão ou metadados não encontrados');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Finalizar metadados
|
|
||||||
const finalMetadata = {
|
|
||||||
...metadata,
|
|
||||||
timestamps: {
|
|
||||||
...metadata.timestamps,
|
|
||||||
captureEnd: new Date().toISOString(),
|
|
||||||
trustedTimestamp: await getTrustedTimestamp()
|
|
||||||
},
|
|
||||||
hashes: {
|
|
||||||
...metadata.hashes,
|
|
||||||
contentHash: await generateHash(targetUrl + Date.now()),
|
|
||||||
pageHash: await generateHash(`page_${session.id}_${targetUrl}`)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Enviar para processamento
|
|
||||||
const response = await fetch('/api/web-proofs/sessions', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
sessionId: session.id,
|
|
||||||
targetUrl,
|
|
||||||
description: captureDescription,
|
|
||||||
metadata: finalMetadata,
|
|
||||||
environment: session.environment,
|
|
||||||
screenshots
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Falha ao processar sessão');
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
|
|
||||||
setSession(prev => prev ? { ...prev, status: SESSION_STATES.COMPLETED } : null);
|
|
||||||
toast.success('Captura finalizada com sucesso');
|
|
||||||
|
|
||||||
// Navegar para relatório
|
|
||||||
navigate(`/web-proofs/relatorio/${result.sessionId}`);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao finalizar captura:', error);
|
|
||||||
setError('Falha ao finalizar captura');
|
|
||||||
setSession(prev => prev ? { ...prev, status: SESSION_STATES.ERROR } : null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Obter timestamp confiável
|
|
||||||
const getTrustedTimestamp = async (): Promise<string> => {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/web-proofs/trusted-timestamp');
|
|
||||||
const data = await response.json();
|
|
||||||
return data.timestamp;
|
|
||||||
} catch {
|
|
||||||
return new Date().toISOString();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 py-8 px-4 sm:px-6 lg:px-8">
|
|
||||||
<div className="max-w-7xl mx-auto">
|
|
||||||
<div className="text-center mb-8">
|
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Captura de Provas Web</h1>
|
|
||||||
<p className="mt-2 text-lg text-gray-600">
|
|
||||||
Coleta forense de evidências digitais em ambiente isolado
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!session && (
|
|
||||||
<div className="max-w-2xl mx-auto bg-white rounded-lg shadow p-6">
|
|
||||||
<h2 className="text-xl font-semibold mb-4">Inicializar Ambiente Seguro</h2>
|
|
||||||
<p className="text-gray-600 mb-6">
|
|
||||||
O sistema criará um ambiente virtual isolado para garantir a integridade da captura.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={initializeIsolatedEnvironment}
|
|
||||||
className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors"
|
|
||||||
>
|
|
||||||
Inicializar Ambiente Isolado
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{progress > 0 && (
|
|
||||||
<div className="mt-4">
|
|
||||||
<div className="w-full bg-gray-200 rounded-full h-2">
|
|
||||||
<div
|
|
||||||
className="bg-blue-600 h-2 rounded-full transition-all duration-300"
|
|
||||||
style={{ width: `${progress}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-gray-500 mt-2">Preparando ambiente... {progress}%</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{session && session.status === SESSION_STATES.ACTIVE && (
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
|
||||||
<div className="lg:col-span-1 bg-white rounded-lg shadow p-6">
|
|
||||||
<h2 className="text-xl font-semibold mb-4">Configuração da Captura</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
|
||||||
URL de Destino
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="url"
|
|
||||||
value={targetUrl}
|
|
||||||
onChange={(e) => setTargetUrl(e.target.value)}
|
|
||||||
placeholder="https://exemplo.com"
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
|
||||||
Descrição da Prova
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
value={captureDescription}
|
|
||||||
onChange={(e) => setCaptureDescription(e.target.value)}
|
|
||||||
rows={3}
|
|
||||||
placeholder="Descreva o que será capturado..."
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={startCapture}
|
|
||||||
disabled={!targetUrl.trim() || isRecording}
|
|
||||||
className="w-full bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 disabled:bg-gray-400 transition-colors"
|
|
||||||
>
|
|
||||||
{isRecording ? 'Capturando...' : 'Iniciar Captura'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="lg:col-span-2 bg-white rounded-lg shadow p-6">
|
|
||||||
<h2 className="text-xl font-semibold mb-4">Ambiente Virtual Isolado</h2>
|
|
||||||
|
|
||||||
<div className="border-2 border-gray-200 rounded-lg h-96 bg-gray-50 flex items-center justify-center">
|
|
||||||
{isRecording && targetUrl ? (
|
|
||||||
<iframe
|
|
||||||
ref={iframeRef}
|
|
||||||
src={targetUrl}
|
|
||||||
className="w-full h-full rounded"
|
|
||||||
title="Captura Web"
|
|
||||||
sandbox="allow-scripts allow-same-origin"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<p className="text-gray-500">Ambiente aguardando URL de destino</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-4 flex gap-2">
|
|
||||||
<button
|
|
||||||
onClick={captureScreenshot}
|
|
||||||
disabled={!isRecording}
|
|
||||||
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:bg-gray-400 transition-colors"
|
|
||||||
>
|
|
||||||
Capturar Screenshot
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={finalizeCaptureSession}
|
|
||||||
disabled={!isRecording}
|
|
||||||
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 disabled:bg-gray-400 transition-colors"
|
|
||||||
>
|
|
||||||
Finalizar Captura
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{screenshots.length > 0 && (
|
|
||||||
<div className="mt-4">
|
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
Screenshots capturados: {screenshots.length}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{session && session.status === SESSION_STATES.RECORDING && (
|
|
||||||
<div className="fixed top-4 right-4 bg-red-600 text-white px-4 py-2 rounded-lg shadow-lg">
|
|
||||||
<div className="flex items-center">
|
|
||||||
<div className="w-3 h-3 bg-white rounded-full mr-2 animate-pulse"></div>
|
|
||||||
GRAVANDO
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<div className="max-w-2xl mx-auto mt-6 bg-red-50 border border-red-200 rounded-lg p-4">
|
|
||||||
<div className="flex">
|
|
||||||
<div className="text-red-600">
|
|
||||||
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
|
|
||||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<div className="ml-3">
|
|
||||||
<h3 className="text-sm font-medium text-red-800">Erro na Captura</h3>
|
|
||||||
<div className="mt-2 text-sm text-red-700">
|
|
||||||
<p>{error}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default WebProofCapture;
|
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
|
||||||
import { Link } from 'react-router-dom';
|
|
||||||
import { format } from 'date-fns';
|
|
||||||
import { ptBR } from 'date-fns/locale';
|
|
||||||
|
|
||||||
interface WebProofSession {
|
|
||||||
sessionId: string;
|
|
||||||
targetUrl: string;
|
|
||||||
description: string;
|
|
||||||
status: string;
|
|
||||||
createdAt: string;
|
|
||||||
processedAt?: string;
|
|
||||||
error?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function WebProofList() {
|
|
||||||
const [sessions, setSessions] = useState<WebProofSession[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchSessions = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/web-proofs/admin/sessions?limit=50');
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Erro ao carregar sessões');
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
setSessions(data.sessions || data); // Compatibilidade com formato paginado
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao buscar sessões:', error);
|
|
||||||
setError('Erro ao carregar lista de sessões');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchSessions();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const formatDate = (dateString: string) => {
|
|
||||||
try {
|
|
||||||
return format(new Date(dateString), 'dd/MM/yyyy HH:mm', { locale: ptBR });
|
|
||||||
} catch {
|
|
||||||
return 'Data inválida';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusColor = (status: string) => {
|
|
||||||
switch (status) {
|
|
||||||
case 'CONCLUIDO':
|
|
||||||
return 'bg-green-100 text-green-800';
|
|
||||||
case 'PROCESSANDO':
|
|
||||||
return 'bg-blue-100 text-blue-800';
|
|
||||||
case 'ERRO':
|
|
||||||
return 'bg-red-100 text-red-800';
|
|
||||||
default:
|
|
||||||
return 'bg-gray-100 text-gray-800';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="p-6">
|
|
||||||
<div className="bg-white rounded-lg shadow p-6">
|
|
||||||
<div className="animate-pulse">
|
|
||||||
<div className="h-6 bg-gray-300 rounded w-1/4 mb-4"></div>
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="h-4 bg-gray-300 rounded"></div>
|
|
||||||
<div className="h-4 bg-gray-300 rounded w-5/6"></div>
|
|
||||||
<div className="h-4 bg-gray-300 rounded w-4/6"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<div className="p-6">
|
|
||||||
<div className="bg-white rounded-lg shadow p-6 text-center">
|
|
||||||
<div className="text-red-600 mb-4">{error}</div>
|
|
||||||
<button
|
|
||||||
onClick={() => window.location.reload()}
|
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
|
|
||||||
>
|
|
||||||
Tentar Novamente
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="p-6">
|
|
||||||
<div className="bg-white rounded-lg shadow">
|
|
||||||
<div className="px-6 py-4 border-b border-gray-200">
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-xl font-semibold text-gray-900">Capturas Web Forenses</h1>
|
|
||||||
<p className="mt-1 text-sm text-gray-600">
|
|
||||||
Lista de todas as sessões de captura web processadas
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Link
|
|
||||||
to="/web-proofs/capture"
|
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
|
|
||||||
>
|
|
||||||
Nova Captura
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="overflow-x-auto">
|
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
|
||||||
<thead className="bg-gray-50">
|
|
||||||
<tr>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
|
||||||
URL / Descrição
|
|
||||||
</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
|
||||||
Status
|
|
||||||
</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
|
||||||
Data
|
|
||||||
</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
|
||||||
Ações
|
|
||||||
</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<tr key={session.sessionId} className="hover:bg-gray-50">
|
|
||||||
<td className="px-6 py-4">
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-gray-900 truncate max-w-xs">
|
|
||||||
{session.targetUrl}
|
|
||||||
</div>
|
|
||||||
{session.description && (
|
|
||||||
<div className="text-sm text-gray-500 truncate max-w-xs">
|
|
||||||
{session.description}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="text-xs text-gray-400 font-mono">
|
|
||||||
{session.sessionId}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4">
|
|
||||||
<span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(session.status)}`}>
|
|
||||||
{session.status}
|
|
||||||
</span>
|
|
||||||
{session.error && (
|
|
||||||
<div className="text-xs text-red-600 mt-1 max-w-xs truncate" title={session.error}>
|
|
||||||
{session.error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-sm text-gray-500">
|
|
||||||
<div>Criado: {formatDate(session.createdAt)}</div>
|
|
||||||
{session.processedAt && (
|
|
||||||
<div>Processado: {formatDate(session.processedAt)}</div>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-sm font-medium space-x-2">
|
|
||||||
<Link
|
|
||||||
to={`/web-proofs/relatorio/${session.sessionId}`}
|
|
||||||
className="text-blue-600 hover:text-blue-900"
|
|
||||||
>
|
|
||||||
Ver Relatório
|
|
||||||
</Link>
|
|
||||||
|
|
||||||
{session.status === 'CONCLUIDO' && (
|
|
||||||
<>
|
|
||||||
<span className="text-gray-300">|</span>
|
|
||||||
<a
|
|
||||||
href={`/api/web-proofs/relatorio/${session.sessionId}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-green-600 hover:text-green-900"
|
|
||||||
>
|
|
||||||
Download PDF
|
|
||||||
</a>
|
|
||||||
<span className="text-gray-300">|</span>
|
|
||||||
<a
|
|
||||||
href={`/api/web-proofs/verify/${session.sessionId}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-purple-600 hover:text-purple-900"
|
|
||||||
>
|
|
||||||
Verificar
|
|
||||||
</a>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
{sessions.length === 0 && (
|
|
||||||
<div className="text-center py-12">
|
|
||||||
<svg className="w-12 h-12 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
|
||||||
</svg>
|
|
||||||
<h3 className="text-lg font-medium text-gray-900 mb-1">Nenhuma captura encontrada</h3>
|
|
||||||
<p className="text-gray-500 mb-4">Comece criando sua primeira captura web forense</p>
|
|
||||||
<Link
|
|
||||||
to="/web-proofs/capture"
|
|
||||||
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
|
|
||||||
>
|
|
||||||
Criar Primeira Captura
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default WebProofList;
|
|
||||||
@@ -1,348 +0,0 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
|
||||||
import { useParams, Link } from 'react-router-dom';
|
|
||||||
import { format } from 'date-fns';
|
|
||||||
import { ptBR } from 'date-fns/locale';
|
|
||||||
import { toast } from 'react-toastify';
|
|
||||||
|
|
||||||
interface WebProofSession {
|
|
||||||
sessionId: string;
|
|
||||||
targetUrl: string;
|
|
||||||
description: string;
|
|
||||||
status: string;
|
|
||||||
metadata: any;
|
|
||||||
environment: any;
|
|
||||||
sessionHash: string;
|
|
||||||
contentHash: string;
|
|
||||||
pageHash: string;
|
|
||||||
trustedTimestamp: string;
|
|
||||||
networkData: any;
|
|
||||||
screenshots: string[];
|
|
||||||
createdAt: string;
|
|
||||||
processedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface VerificationResult {
|
|
||||||
verified: boolean;
|
|
||||||
sessionValid: boolean;
|
|
||||||
contentValid: boolean;
|
|
||||||
timestampValid: boolean;
|
|
||||||
details: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function WebProofReport() {
|
|
||||||
const { sessionId } = useParams<{ sessionId: string }>();
|
|
||||||
const [session, setSession] = useState<WebProofSession | null>(null);
|
|
||||||
const [verification, setVerification] = useState<VerificationResult | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [verifying, setVerifying] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchSessionData = async () => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
const response = await fetch(`/api/web-proofs/sessions/${sessionId}/status`);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Sessão não encontrada');
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
setSession(data);
|
|
||||||
|
|
||||||
// Verificar automaticamente se a sessão estiver completa
|
|
||||||
if (data.status === 'CONCLUIDO') {
|
|
||||||
await verifySession(data.sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao buscar dados da sessão:', error);
|
|
||||||
setError('Não foi possível carregar os dados da sessão');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (sessionId) {
|
|
||||||
fetchSessionData();
|
|
||||||
}
|
|
||||||
}, [sessionId]);
|
|
||||||
|
|
||||||
const verifySession = async (sessionIdToVerify: string) => {
|
|
||||||
try {
|
|
||||||
setVerifying(true);
|
|
||||||
|
|
||||||
const response = await fetch(`/api/web-proofs/verify/${sessionIdToVerify}`);
|
|
||||||
const result = await response.json();
|
|
||||||
|
|
||||||
setVerification(result);
|
|
||||||
|
|
||||||
if (result.verified) {
|
|
||||||
toast.success('Sessão verificada com sucesso');
|
|
||||||
} else {
|
|
||||||
toast.warning('Verificação da sessão inconclusiva');
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro na verificação:', error);
|
|
||||||
toast.error('Erro ao verificar sessão');
|
|
||||||
} finally {
|
|
||||||
setVerifying(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDate = (dateString: string) => {
|
|
||||||
try {
|
|
||||||
return format(new Date(dateString), 'dd/MM/yyyy HH:mm:ss', { locale: ptBR });
|
|
||||||
} catch {
|
|
||||||
return 'Data inválida';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const downloadReport = () => {
|
|
||||||
if (session?.sessionId) {
|
|
||||||
window.open(`/api/web-proofs/relatorio/${session.sessionId}`, '_blank');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
|
||||||
<div className="max-w-4xl mx-auto">
|
|
||||||
<div className="bg-white rounded-lg shadow p-6">
|
|
||||||
<div className="animate-pulse">
|
|
||||||
<div className="h-6 bg-gray-300 rounded w-3/4 mb-4"></div>
|
|
||||||
<div className="h-4 bg-gray-300 rounded w-1/2 mb-2"></div>
|
|
||||||
<div className="h-4 bg-gray-300 rounded w-2/3"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error || !session) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
|
||||||
<div className="max-w-4xl mx-auto">
|
|
||||||
<div className="bg-white rounded-lg shadow p-6 text-center">
|
|
||||||
<svg className="w-16 h-16 text-red-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
|
||||||
</svg>
|
|
||||||
<h2 className="text-2xl font-bold text-red-600 mb-4">Relatório não encontrado</h2>
|
|
||||||
<p className="text-gray-600 mb-6">{error}</p>
|
|
||||||
<Link
|
|
||||||
to="/web-proofs"
|
|
||||||
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700"
|
|
||||||
>
|
|
||||||
Voltar às Capturas Web
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
|
||||||
<div className="max-w-6xl mx-auto">
|
|
||||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
|
||||||
{/* Cabeçalho */}
|
|
||||||
<div className="bg-blue-700 text-white px-6 py-4">
|
|
||||||
<h1 className="text-2xl font-bold">Relatório de Captura Web Forense</h1>
|
|
||||||
<p className="text-blue-100 mt-1">Sessão: {session.sessionId}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Status da Verificação */}
|
|
||||||
<div className="border-b border-gray-200 p-6">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900">Status da Verificação</h2>
|
|
||||||
{verification ? (
|
|
||||||
<div className={`mt-2 inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
|
|
||||||
verification.verified
|
|
||||||
? 'bg-green-100 text-green-800'
|
|
||||||
: 'bg-yellow-100 text-yellow-800'
|
|
||||||
}`}>
|
|
||||||
{verification.verified ? '✓ Verificado' : '⚠ Verificação Inconclusiva'}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="mt-2 inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800">
|
|
||||||
Aguardando verificação
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<button
|
|
||||||
onClick={() => verifySession(session.sessionId)}
|
|
||||||
disabled={verifying}
|
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:bg-gray-400"
|
|
||||||
>
|
|
||||||
{verifying ? 'Verificando...' : 'Verificar Novamente'}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={downloadReport}
|
|
||||||
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
|
|
||||||
>
|
|
||||||
Baixar PDF
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Informações da Sessão */}
|
|
||||||
<div className="p-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Informações da Captura</h3>
|
|
||||||
<div className="space-y-3">
|
|
||||||
<DetailItem label="URL Capturada" value={session.targetUrl} />
|
|
||||||
<DetailItem label="Descrição" value={session.description || 'Não especificada'} />
|
|
||||||
<DetailItem label="Status" value={session.status} />
|
|
||||||
<DetailItem label="Data de Criação" value={formatDate(session.createdAt)} />
|
|
||||||
{session.processedAt && (
|
|
||||||
<DetailItem label="Data de Processamento" value={formatDate(session.processedAt)} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Ambiente de Captura</h3>
|
|
||||||
<div className="space-y-3">
|
|
||||||
<DetailItem
|
|
||||||
label="User Agent"
|
|
||||||
value={session.environment?.userAgent || 'Não disponível'}
|
|
||||||
/>
|
|
||||||
<DetailItem
|
|
||||||
label="Viewport"
|
|
||||||
value={session.environment?.viewportSize ?
|
|
||||||
`${session.environment.viewportSize.width}x${session.environment.viewportSize.height}` :
|
|
||||||
'Não disponível'
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<DetailItem
|
|
||||||
label="Endereço IP"
|
|
||||||
value={session.environment?.ipAddress || 'Não disponível'}
|
|
||||||
/>
|
|
||||||
<DetailItem
|
|
||||||
label="Timestamp do Ambiente"
|
|
||||||
value={session.environment?.timestamp ? formatDate(session.environment.timestamp) : 'Não disponível'}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Hashes de Integridade */}
|
|
||||||
<div className="border-t border-gray-200 p-6">
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Hashes de Integridade</h3>
|
|
||||||
<div className="bg-gray-50 rounded-lg p-4 space-y-3 font-mono text-sm">
|
|
||||||
<DetailItem label="Hash da Sessão (SHA-256)" value={session.sessionHash} />
|
|
||||||
<DetailItem label="Hash do Conteúdo (SHA-256)" value={session.contentHash} />
|
|
||||||
<DetailItem label="Hash da Página (SHA-512)" value={session.pageHash} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Timestamp Confiável */}
|
|
||||||
{session.trustedTimestamp && (
|
|
||||||
<div className="border-t border-gray-200 p-6">
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Timestamp Confiável</h3>
|
|
||||||
<div className="bg-green-50 rounded-lg p-4">
|
|
||||||
<DetailItem
|
|
||||||
label="Timestamp Certificado"
|
|
||||||
value={formatDate(session.trustedTimestamp)}
|
|
||||||
/>
|
|
||||||
<p className="text-sm text-green-700 mt-2">
|
|
||||||
Este timestamp foi emitido por uma autoridade certificadora confiável
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Dados de Rede */}
|
|
||||||
{session.networkData && (
|
|
||||||
<div className="border-t border-gray-200 p-6">
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Informações de Rede</h3>
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<DetailItem label="Domínio" value={session.networkData.domain} />
|
|
||||||
<DetailItem label="Protocolo" value={session.networkData.protocol} />
|
|
||||||
<DetailItem label="Porta" value={session.networkData.port} />
|
|
||||||
<DetailItem label="IP Resolvido" value={session.networkData.resolvedIP} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Screenshots */}
|
|
||||||
{session.screenshots && session.screenshots.length > 0 && (
|
|
||||||
<div className="border-t border-gray-200 p-6">
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Capturas Realizadas</h3>
|
|
||||||
<div className="bg-blue-50 rounded-lg p-4">
|
|
||||||
<p className="text-blue-800">
|
|
||||||
<span className="font-semibold">{session.screenshots.length}</span> screenshot(s) capturado(s) durante a sessão
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-blue-600 mt-1">
|
|
||||||
As capturas estão incluídas no relatório PDF completo
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Detalhes da Verificação */}
|
|
||||||
{verification && (
|
|
||||||
<div className="border-t border-gray-200 p-6">
|
|
||||||
<h3 className="text-lg font-semibold mb-4">Detalhes da Verificação</h3>
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
|
||||||
<div className={`p-4 rounded-lg ${verification.sessionValid ? 'bg-green-50' : 'bg-red-50'}`}>
|
|
||||||
<div className={`font-medium ${verification.sessionValid ? 'text-green-800' : 'text-red-800'}`}>
|
|
||||||
Hash da Sessão
|
|
||||||
</div>
|
|
||||||
<div className={`text-sm ${verification.sessionValid ? 'text-green-600' : 'text-red-600'}`}>
|
|
||||||
{verification.sessionValid ? 'Válido' : 'Inválido'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className={`p-4 rounded-lg ${verification.contentValid ? 'bg-green-50' : 'bg-red-50'}`}>
|
|
||||||
<div className={`font-medium ${verification.contentValid ? 'text-green-800' : 'text-red-800'}`}>
|
|
||||||
Hash do Conteúdo
|
|
||||||
</div>
|
|
||||||
<div className={`text-sm ${verification.contentValid ? 'text-green-600' : 'text-red-600'}`}>
|
|
||||||
{verification.contentValid ? 'Válido' : 'Inválido'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className={`p-4 rounded-lg ${verification.timestampValid ? 'bg-green-50' : 'bg-yellow-50'}`}>
|
|
||||||
<div className={`font-medium ${verification.timestampValid ? 'text-green-800' : 'text-yellow-800'}`}>
|
|
||||||
Timestamp
|
|
||||||
</div>
|
|
||||||
<div className={`text-sm ${verification.timestampValid ? 'text-green-600' : 'text-yellow-600'}`}>
|
|
||||||
{verification.timestampValid ? 'Válido' : 'Não verificado'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Rodapé */}
|
|
||||||
<div className="bg-gray-50 px-6 py-4 text-center border-t border-gray-200">
|
|
||||||
<p className="text-sm text-gray-500">
|
|
||||||
Relatório gerado pelo sistema AdvX Web Proof Capture -
|
|
||||||
Preservando a integridade e autenticidade de evidências digitais
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DetailItem({ label, value }: { label: string; value: string }) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<dt className="text-sm font-medium text-gray-500">{label}</dt>
|
|
||||||
<dd className="mt-1 text-sm text-gray-900 break-words">{value}</dd>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default WebProofReport;
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import express from 'express';
|
|
||||||
import cors from 'cors';
|
|
||||||
import { json, urlencoded } from 'body-parser';
|
|
||||||
import { createServer } from 'http';
|
|
||||||
import { Server } from 'socket.io';
|
|
||||||
import path from 'path';
|
|
||||||
import { fileURLToPath } from 'url';
|
|
||||||
|
|
||||||
import provasRoutes from './routes/provas';
|
|
||||||
import webProofsRoutes from './routes/webProofs';
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const httpServer = createServer(app);
|
|
||||||
const io = new Server(httpServer);
|
|
||||||
|
|
||||||
// Middleware
|
|
||||||
app.use(cors());
|
|
||||||
app.use(json());
|
|
||||||
app.use(urlencoded({ extended: true }));
|
|
||||||
|
|
||||||
// Definir diretório público para arquivos estáticos
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
|
||||||
|
|
||||||
// Rotas
|
|
||||||
app.use('/api/provas', provasRoutes);
|
|
||||||
app.use('/api/web-proofs', webProofsRoutes);
|
|
||||||
|
|
||||||
// Rota padrão
|
|
||||||
app.get('/', (req, res) => {
|
|
||||||
res.send('API do sistema de validação de provas digitais');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Inicializar servidor
|
|
||||||
const PORT = process.env.PORT || 5000;
|
|
||||||
httpServer.listen(PORT, () => {
|
|
||||||
console.log(`Servidor rodando na porta ${PORT}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
export default app;
|
|
||||||
File diff suppressed because it is too large.
Load diff
+23
-2
@@ -27,6 +27,8 @@ import indicesMonetariosRoutes from './routes/indicesMonetarios';
|
|||||||
import pensaoAlimenticiaRouter from './routes/pensaoAlimenticia'; // Importar router de pensão alimentícia
|
import pensaoAlimenticiaRouter from './routes/pensaoAlimenticia'; // Importar router de pensão alimentícia
|
||||||
import financeiroPainelRoutes from './routes/financeiroPainel'; // Importar rotas do financeiro painel
|
import financeiroPainelRoutes from './routes/financeiroPainel'; // Importar rotas do financeiro painel
|
||||||
import audienciasRoutes from './routes/audiencias'; // Importar rotas de audiências
|
import audienciasRoutes from './routes/audiencias'; // Importar rotas de audiências
|
||||||
|
import pdfRoutes from './routes/pdf'; // Importar rotas de PDF
|
||||||
|
import { PDFService } from '../services/pdfService'; // Importar serviço de PDF para warmup OCR
|
||||||
|
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -1429,8 +1431,26 @@ app.use(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
app.listen(port, () => {
|
// Aumentar timeout do servidor para operações longas (ex: PDF, OCR)
|
||||||
|
const server = app.listen(port, () => {
|
||||||
console.log(`🚀 Servidor rodando em http://localhost:${port}`);
|
console.log(`🚀 Servidor rodando em http://localhost:${port}`);
|
||||||
|
|
||||||
|
// Pré-aquece o worker Tesseract OCR em background (elimina delay na primeira operação)
|
||||||
|
PDFService.warmupOCR('por').catch(() => {});
|
||||||
|
});
|
||||||
|
server.timeout = 600000; // 10 minutos (600 segundos)
|
||||||
|
|
||||||
|
// Encerra workers Tesseract ao desligar o servidor
|
||||||
|
process.on('SIGTERM', async () => {
|
||||||
|
console.log('Encerrando workers OCR...');
|
||||||
|
await PDFService.terminateWorkers();
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGINT', async () => {
|
||||||
|
console.log('Encerrando workers OCR...');
|
||||||
|
await PDFService.terminateWorkers();
|
||||||
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on("unhandledRejection", (err) => {
|
process.on("unhandledRejection", (err) => {
|
||||||
@@ -1481,4 +1501,5 @@ app.use('/api/calculos', calculosJudiciaisRoutes);
|
|||||||
app.use('/api/indices', indicesMonetariosRoutes);
|
app.use('/api/indices', indicesMonetariosRoutes);
|
||||||
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRouter);
|
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRouter);
|
||||||
app.use('/api/financeiro-painel', financeiroPainelRoutes); // Adicionar uso das rotas do financeiro painel
|
app.use('/api/financeiro-painel', financeiroPainelRoutes); // Adicionar uso das rotas do financeiro painel
|
||||||
app.use('/api/audiencias', audienciasRoutes); // Adicionar uso das rotas de audiências
|
app.use('/api/audiencias', audienciasRoutes); // Adicionar uso das rotas de audiências
|
||||||
|
app.use('/api/pdf', pdfRoutes); // Adicionar uso das rotas de PDF
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { PDFController, uploadMiddleware } from '../controllers/pdfController';
|
||||||
|
import { authMiddleware } from '../../middleware/auth';
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rotas para manipulação de PDF
|
||||||
|
* Todas as rotas requerem autenticação
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Comprime PDFs
|
||||||
|
router.post(
|
||||||
|
'/compress',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 10),
|
||||||
|
PDFController.compress
|
||||||
|
);
|
||||||
|
|
||||||
|
// Divide PDF
|
||||||
|
router.post(
|
||||||
|
'/split',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 1),
|
||||||
|
PDFController.split
|
||||||
|
);
|
||||||
|
|
||||||
|
// Mescla PDFs
|
||||||
|
router.post(
|
||||||
|
'/merge',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 50),
|
||||||
|
PDFController.merge
|
||||||
|
);
|
||||||
|
|
||||||
|
// Converte PDF para imagens
|
||||||
|
router.post(
|
||||||
|
'/pdf-to-images',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 1),
|
||||||
|
PDFController.pdfToImages
|
||||||
|
);
|
||||||
|
|
||||||
|
// Converte imagens para PDF
|
||||||
|
router.post(
|
||||||
|
'/images-to-pdf',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 100),
|
||||||
|
PDFController.imagesToPDF
|
||||||
|
);
|
||||||
|
|
||||||
|
// Realiza OCR em PDF
|
||||||
|
router.post(
|
||||||
|
'/ocr',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 1),
|
||||||
|
PDFController.performOCR
|
||||||
|
);
|
||||||
|
|
||||||
|
// Obtém informações de um PDF
|
||||||
|
router.post(
|
||||||
|
'/info',
|
||||||
|
authMiddleware,
|
||||||
|
uploadMiddleware.array('files', 1),
|
||||||
|
PDFController.getInfo
|
||||||
|
);
|
||||||
|
|
||||||
|
// Obtém histórico de operações
|
||||||
|
router.get(
|
||||||
|
'/history',
|
||||||
|
authMiddleware,
|
||||||
|
PDFController.getHistory
|
||||||
|
);
|
||||||
|
|
||||||
|
// Download de arquivo processado
|
||||||
|
router.get(
|
||||||
|
'/download/:operacaoId/:fileIndex',
|
||||||
|
authMiddleware,
|
||||||
|
PDFController.downloadFile
|
||||||
|
);
|
||||||
|
|
||||||
|
// Deleta uma operação específica
|
||||||
|
router.delete(
|
||||||
|
'/operation/:operacaoId',
|
||||||
|
authMiddleware,
|
||||||
|
PDFController.deleteOperation
|
||||||
|
);
|
||||||
|
|
||||||
|
// Limpa todo o histórico
|
||||||
|
router.delete(
|
||||||
|
'/history/clear',
|
||||||
|
authMiddleware,
|
||||||
|
PDFController.clearHistory
|
||||||
|
);
|
||||||
|
|
||||||
|
// Limpa operações antigas
|
||||||
|
router.delete(
|
||||||
|
'/history/cleanup',
|
||||||
|
authMiddleware,
|
||||||
|
PDFController.cleanupOldOperations
|
||||||
|
);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
import express from 'express';
|
|
||||||
import { WebProofService } from '../services/WebProofService';
|
|
||||||
import { prisma } from '../prismaClient';
|
|
||||||
import * as path from 'path';
|
|
||||||
import * as fs from 'fs';
|
|
||||||
|
|
||||||
const router = express.Router();
|
|
||||||
const webProofService = new WebProofService();
|
|
||||||
|
|
||||||
// Criar nova sessão de captura web
|
|
||||||
router.post('/sessions', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const {
|
|
||||||
sessionId,
|
|
||||||
targetUrl,
|
|
||||||
description,
|
|
||||||
metadata,
|
|
||||||
environment,
|
|
||||||
screenshots
|
|
||||||
} = req.body;
|
|
||||||
|
|
||||||
// Validar dados de entrada
|
|
||||||
if (!sessionId || !targetUrl || !metadata || !environment) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: 'Dados obrigatórios não fornecidos',
|
|
||||||
required: ['sessionId', 'targetUrl', 'metadata', 'environment']
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validar URL
|
|
||||||
try {
|
|
||||||
new URL(targetUrl);
|
|
||||||
} catch {
|
|
||||||
return res.status(400).json({ error: 'URL inválida fornecida' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Coletar informações de rede do cliente
|
|
||||||
const clientInfo = {
|
|
||||||
ip: req.headers['x-forwarded-for']?.toString().split(',')[0].trim() ||
|
|
||||||
req.ip ||
|
|
||||||
req.socket.remoteAddress ||
|
|
||||||
'127.0.0.1',
|
|
||||||
port: req.socket.remotePort || 0,
|
|
||||||
userAgent: req.headers['user-agent'] || '',
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
};
|
|
||||||
|
|
||||||
// Processar sessão de captura
|
|
||||||
const result = await webProofService.processWebCapture({
|
|
||||||
sessionId,
|
|
||||||
targetUrl,
|
|
||||||
description,
|
|
||||||
metadata: {
|
|
||||||
...metadata,
|
|
||||||
clientInfo,
|
|
||||||
serverInfo: {
|
|
||||||
hostname: require('os').hostname(),
|
|
||||||
nodeVersion: process.version,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
environment,
|
|
||||||
screenshots: screenshots || []
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
success: true,
|
|
||||||
sessionId: result.id,
|
|
||||||
status: result.status,
|
|
||||||
message: 'Sessão de captura processada com sucesso'
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao processar sessão de captura:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Falha ao processar sessão de captura',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Obter status da sessão
|
|
||||||
router.get('/sessions/:sessionId/status', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { sessionId } = req.params;
|
|
||||||
|
|
||||||
const session = await prisma.webProofSession.findUnique({
|
|
||||||
where: { sessionId }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
return res.status(404).json({ error: 'Sessão não encontrada' });
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
status: session.status,
|
|
||||||
targetUrl: session.targetUrl,
|
|
||||||
description: session.description,
|
|
||||||
createdAt: session.createdAt,
|
|
||||||
updatedAt: session.updatedAt,
|
|
||||||
reportPath: session.reportPath,
|
|
||||||
error: session.error
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao buscar status da sessão:', error);
|
|
||||||
res.status(500).json({ error: 'Erro ao buscar status da sessão' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Obter timestamp confiável
|
|
||||||
router.get('/trusted-timestamp', async (req, res) => {
|
|
||||||
try {
|
|
||||||
// Simular obtenção de timestamp de autoridade certificadora
|
|
||||||
const trustedTimestamp = await webProofService.getTrustedTimestamp();
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
timestamp: trustedTimestamp.timestamp,
|
|
||||||
authority: trustedTimestamp.authority,
|
|
||||||
signature: trustedTimestamp.signature
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao obter timestamp confiável:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Erro ao obter timestamp confiável',
|
|
||||||
fallback: new Date().toISOString()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Obter informações do cliente
|
|
||||||
router.get('/client-info', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const clientInfo = {
|
|
||||||
ip: req.headers['x-forwarded-for']?.toString().split(',')[0].trim() ||
|
|
||||||
req.ip ||
|
|
||||||
req.socket.remoteAddress ||
|
|
||||||
'127.0.0.1',
|
|
||||||
port: req.socket.remotePort || 0,
|
|
||||||
userAgent: req.headers['user-agent'] || '',
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
headers: {
|
|
||||||
'x-forwarded-for': req.headers['x-forwarded-for'],
|
|
||||||
'user-agent': req.headers['user-agent'],
|
|
||||||
'accept-language': req.headers['accept-language']
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
res.json(clientInfo);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao obter informações do cliente:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Erro ao obter informações do cliente',
|
|
||||||
fallback: {
|
|
||||||
ip: '127.0.0.1',
|
|
||||||
port: 0,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Verificar autenticidade de captura web com detalhes aprimorados
|
|
||||||
router.get('/verify/:sessionId', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { sessionId } = req.params;
|
|
||||||
|
|
||||||
if (!sessionId || typeof sessionId !== 'string') {
|
|
||||||
return res.status(400).json({
|
|
||||||
verified: false,
|
|
||||||
error: 'SessionId inválido'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const verification = await webProofService.verifyWebCapture(sessionId);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
verified: verification.verified,
|
|
||||||
sessionId,
|
|
||||||
sessionValid: verification.sessionValid || false,
|
|
||||||
contentValid: verification.contentValid || false,
|
|
||||||
timestampValid: verification.timestampValid || false,
|
|
||||||
verificationDetails: verification.details,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao verificar captura:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
verified: false,
|
|
||||||
sessionValid: false,
|
|
||||||
contentValid: false,
|
|
||||||
timestampValid: false,
|
|
||||||
error: 'Erro ao verificar captura web'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Baixar relatório com validação aprimorada
|
|
||||||
router.get('/relatorio/:sessionId', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { sessionId } = req.params;
|
|
||||||
|
|
||||||
if (!sessionId || typeof sessionId !== 'string') {
|
|
||||||
return res.status(400).json({ error: 'SessionId inválido' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = await prisma.webProofSession.findUnique({
|
|
||||||
where: { sessionId }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
return res.status(404).json({ error: 'Sessão não encontrada' });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (session.status !== 'CONCLUIDO') {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: 'Relatório ainda não está disponível',
|
|
||||||
status: session.status
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const reportPath = path.join(process.cwd(), 'storage', 'web-proofs', `${sessionId}_report.pdf`);
|
|
||||||
|
|
||||||
if (!fs.existsSync(reportPath)) {
|
|
||||||
console.error('Arquivo de relatório não encontrado:', reportPath);
|
|
||||||
return res.status(404).json({ error: 'Arquivo do relatório não encontrado' });
|
|
||||||
}
|
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'application/pdf');
|
|
||||||
res.setHeader('Content-Disposition', `inline; filename="captura_web_${sessionId}_relatorio.pdf"`);
|
|
||||||
res.setHeader('Cache-Control', 'public, max-age=3600'); // Cache de 1 hora
|
|
||||||
|
|
||||||
const fileStream = fs.createReadStream(reportPath);
|
|
||||||
fileStream.on('error', (error) => {
|
|
||||||
console.error('Erro ao ler arquivo de relatório:', error);
|
|
||||||
if (!res.headersSent) {
|
|
||||||
res.status(500).json({ error: 'Erro ao ler arquivo de relatório' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
fileStream.pipe(res);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao servir relatório:', error);
|
|
||||||
if (!res.headersSent) {
|
|
||||||
res.status(500).json({ error: 'Erro ao gerar relatório' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Listar sessões com paginação
|
|
||||||
router.get('/admin/sessions', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const page = parseInt(req.query.page as string) || 1;
|
|
||||||
const limit = parseInt(req.query.limit as string) || 100;
|
|
||||||
const offset = (page - 1) * limit;
|
|
||||||
|
|
||||||
const [sessions, total] = await Promise.all([
|
|
||||||
prisma.webProofSession.findMany({
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
skip: offset,
|
|
||||||
take: limit,
|
|
||||||
select: {
|
|
||||||
sessionId: true,
|
|
||||||
targetUrl: true,
|
|
||||||
description: true,
|
|
||||||
status: true,
|
|
||||||
createdAt: true,
|
|
||||||
processedAt: true,
|
|
||||||
error: true
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
prisma.webProofSession.count()
|
|
||||||
]);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
sessions,
|
|
||||||
pagination: {
|
|
||||||
page,
|
|
||||||
limit,
|
|
||||||
total,
|
|
||||||
totalPages: Math.ceil(total / limit)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao listar sessões:', error);
|
|
||||||
res.status(500).json({ error: 'Erro ao listar sessões' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default router;
|
|
||||||
@@ -35,7 +35,7 @@ export class AuthService {
|
|||||||
email: usuario.email,
|
email: usuario.email,
|
||||||
},
|
},
|
||||||
process.env.JWT_SECRET || "default-secret",
|
process.env.JWT_SECRET || "default-secret",
|
||||||
{ expiresIn: "1d" },
|
{ expiresIn: "7d" }, // 7 dias para melhor UX
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,381 +0,0 @@
|
|||||||
import { prisma } from '../prismaClient';
|
|
||||||
import { createHash } from 'crypto';
|
|
||||||
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
|
|
||||||
import * as fs from 'fs/promises';
|
|
||||||
import * as path from 'path';
|
|
||||||
|
|
||||||
interface WebCaptureData {
|
|
||||||
sessionId: string;
|
|
||||||
targetUrl: string;
|
|
||||||
description: string;
|
|
||||||
metadata: any;
|
|
||||||
environment: any;
|
|
||||||
screenshots: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TrustedTimestamp {
|
|
||||||
timestamp: string;
|
|
||||||
authority: string;
|
|
||||||
signature: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class WebProofService {
|
|
||||||
|
|
||||||
// Processar captura web completa
|
|
||||||
async processWebCapture(data: WebCaptureData) {
|
|
||||||
try {
|
|
||||||
console.log('Iniciando processamento de captura web:', data.sessionId);
|
|
||||||
|
|
||||||
// Criar registro da sessão
|
|
||||||
const session = await prisma.webProofSession.create({
|
|
||||||
data: {
|
|
||||||
sessionId: data.sessionId,
|
|
||||||
targetUrl: data.targetUrl,
|
|
||||||
description: data.description,
|
|
||||||
status: 'PROCESSANDO',
|
|
||||||
metadata: data.metadata,
|
|
||||||
environment: data.environment,
|
|
||||||
screenshots: data.screenshots
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Processar em background
|
|
||||||
this.processInBackground(session.id, data);
|
|
||||||
|
|
||||||
return session;
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao processar captura web:', error);
|
|
||||||
throw new Error(`Falha no processamento: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Processamento em background
|
|
||||||
private async processInBackground(sessionDbId: string, data: WebCaptureData) {
|
|
||||||
try {
|
|
||||||
// Simular processamento complexo
|
|
||||||
await this.delay(2000);
|
|
||||||
|
|
||||||
// Gerar hashes da sessão
|
|
||||||
const sessionHash = await this.generateSessionHash(data);
|
|
||||||
const contentHash = await this.generateContentHash(data.targetUrl, data.metadata);
|
|
||||||
const pageHash = await this.generatePageHash(data.targetUrl, data.environment);
|
|
||||||
|
|
||||||
// Coletar dados de rede simulados
|
|
||||||
const networkData = await this.collectNetworkData(data.targetUrl);
|
|
||||||
|
|
||||||
// Obter timestamp confiável
|
|
||||||
const trustedTimestamp = await this.getTrustedTimestamp();
|
|
||||||
|
|
||||||
// Gerar relatório PDF
|
|
||||||
const reportPath = await this.generateWebProofReport({
|
|
||||||
...data,
|
|
||||||
sessionHash,
|
|
||||||
contentHash,
|
|
||||||
pageHash,
|
|
||||||
networkData,
|
|
||||||
trustedTimestamp
|
|
||||||
});
|
|
||||||
|
|
||||||
// Atualizar status para concluído
|
|
||||||
await prisma.webProofSession.update({
|
|
||||||
where: { id: sessionDbId },
|
|
||||||
data: {
|
|
||||||
status: 'CONCLUIDO',
|
|
||||||
sessionHash,
|
|
||||||
contentHash,
|
|
||||||
pageHash,
|
|
||||||
reportPath,
|
|
||||||
networkData,
|
|
||||||
trustedTimestamp: trustedTimestamp.timestamp,
|
|
||||||
processedAt: new Date()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Processamento de captura web concluído:', data.sessionId);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro no processamento em background:', error);
|
|
||||||
|
|
||||||
await prisma.webProofSession.update({
|
|
||||||
where: { id: sessionDbId },
|
|
||||||
data: {
|
|
||||||
status: 'ERRO',
|
|
||||||
error: error.message
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gerar hash da sessão
|
|
||||||
private async generateSessionHash(data: WebCaptureData): Promise<string> {
|
|
||||||
const sessionData = JSON.stringify({
|
|
||||||
sessionId: data.sessionId,
|
|
||||||
targetUrl: data.targetUrl,
|
|
||||||
environment: data.environment,
|
|
||||||
timestamp: data.metadata.timestamps?.sessionStart
|
|
||||||
});
|
|
||||||
|
|
||||||
return createHash('sha256').update(sessionData).digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gerar hash do conteúdo
|
|
||||||
private async generateContentHash(url: string, metadata: any): Promise<string> {
|
|
||||||
const contentData = JSON.stringify({
|
|
||||||
url,
|
|
||||||
timestamp: metadata.timestamps?.captureStart,
|
|
||||||
browserFingerprint: metadata.technicalData?.browserFingerprint
|
|
||||||
});
|
|
||||||
|
|
||||||
return createHash('sha256').update(contentData).digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gerar hash da página
|
|
||||||
private async generatePageHash(url: string, environment: any): Promise<string> {
|
|
||||||
const pageData = JSON.stringify({
|
|
||||||
url,
|
|
||||||
environment,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
});
|
|
||||||
|
|
||||||
return createHash('sha512').update(pageData).digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Coletar dados de rede (simulado)
|
|
||||||
private async collectNetworkData(targetUrl: string) {
|
|
||||||
try {
|
|
||||||
const url = new URL(targetUrl);
|
|
||||||
|
|
||||||
// Simular coleta de dados de rede
|
|
||||||
return {
|
|
||||||
domain: url.hostname,
|
|
||||||
protocol: url.protocol,
|
|
||||||
port: url.port || (url.protocol === 'https:' ? '443' : '80'),
|
|
||||||
path: url.pathname,
|
|
||||||
resolvedIP: '192.168.1.1', // Simulado
|
|
||||||
routeTrace: ['10.0.0.1', '192.168.1.1'], // Simulado
|
|
||||||
dnsRecords: [
|
|
||||||
{ type: 'A', value: '192.168.1.1' },
|
|
||||||
{ type: 'MX', value: 'mail.example.com' }
|
|
||||||
]
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return {
|
|
||||||
domain: 'unknown',
|
|
||||||
error: 'Falha na resolução de rede'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Obter timestamp confiável
|
|
||||||
async getTrustedTimestamp(): Promise<TrustedTimestamp> {
|
|
||||||
// Simular autoridade certificadora de tempo
|
|
||||||
const timestamp = new Date().toISOString();
|
|
||||||
const signature = createHash('sha256')
|
|
||||||
.update(timestamp + 'trusted_authority_key')
|
|
||||||
.digest('hex');
|
|
||||||
|
|
||||||
return {
|
|
||||||
timestamp,
|
|
||||||
authority: 'AdvX Timestamp Authority',
|
|
||||||
signature
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gerar relatório PDF da captura web
|
|
||||||
private async generateWebProofReport(data: any): Promise<string> {
|
|
||||||
try {
|
|
||||||
const pdfDoc = await PDFDocument.create();
|
|
||||||
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
|
||||||
const helveticaBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
|
||||||
|
|
||||||
// Página principal
|
|
||||||
const page = pdfDoc.addPage([595, 842]); // A4
|
|
||||||
const { width, height } = page.getSize();
|
|
||||||
|
|
||||||
// Cabeçalho
|
|
||||||
page.drawText('RELATÓRIO DE CAPTURA WEB FORENSE', {
|
|
||||||
x: 50,
|
|
||||||
y: height - 50,
|
|
||||||
size: 18,
|
|
||||||
font: helveticaBold,
|
|
||||||
color: rgb(0, 0, 0.8)
|
|
||||||
});
|
|
||||||
|
|
||||||
// Informações da sessão
|
|
||||||
let yPosition = height - 100;
|
|
||||||
const addSection = (title: string, content: string) => {
|
|
||||||
page.drawText(title, {
|
|
||||||
x: 50,
|
|
||||||
y: yPosition,
|
|
||||||
size: 12,
|
|
||||||
font: helveticaBold
|
|
||||||
});
|
|
||||||
yPosition -= 20;
|
|
||||||
|
|
||||||
const lines = content.split('\n');
|
|
||||||
lines.forEach(line => {
|
|
||||||
page.drawText(line, {
|
|
||||||
x: 50,
|
|
||||||
y: yPosition,
|
|
||||||
size: 10,
|
|
||||||
font: helveticaFont
|
|
||||||
});
|
|
||||||
yPosition -= 15;
|
|
||||||
});
|
|
||||||
yPosition -= 10;
|
|
||||||
};
|
|
||||||
|
|
||||||
addSection('IDENTIFICAÇÃO DA SESSÃO:',
|
|
||||||
`ID: ${data.sessionId}\nURL Capturada: ${data.targetUrl}\nDescrição: ${data.description || 'Não especificada'}`
|
|
||||||
);
|
|
||||||
|
|
||||||
addSection('INFORMAÇÕES TEMPORAIS:',
|
|
||||||
`Início da Sessão: ${data.metadata.timestamps?.sessionStart || 'N/A'}\nInício da Captura: ${data.metadata.timestamps?.captureStart || 'N/A'}\nFim da Captura: ${data.metadata.timestamps?.captureEnd || 'N/A'}\nTimestamp Confiável: ${data.trustedTimestamp || 'N/A'}`
|
|
||||||
);
|
|
||||||
|
|
||||||
addSection('HASHES DE INTEGRIDADE:',
|
|
||||||
`Hash da Sessão (SHA-256): ${data.sessionHash}\nHash do Conteúdo (SHA-256): ${data.contentHash}\nHash da Página (SHA-512): ${data.pageHash}`
|
|
||||||
);
|
|
||||||
|
|
||||||
addSection('AMBIENTE DE CAPTURA:',
|
|
||||||
`User Agent: ${data.environment.userAgent}\nTamanho da Viewport: ${data.environment.viewportSize?.width}x${data.environment.viewportSize?.height}\nEndereço IP: ${data.environment.ipAddress}\nTimestamp do Ambiente: ${data.environment.timestamp}`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (data.networkData) {
|
|
||||||
addSection('DADOS DE REDE:',
|
|
||||||
`Domínio: ${data.networkData.domain}\nProtocolo: ${data.networkData.protocol}\nPorta: ${data.networkData.port}\nIP Resolvido: ${data.networkData.resolvedIP || 'N/A'}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.screenshots && data.screenshots.length > 0) {
|
|
||||||
addSection('CAPTURAS REALIZADAS:',
|
|
||||||
`Número de Screenshots: ${data.screenshots.length}\nTimestamps: ${data.screenshots.map((_, i) => `Screenshot ${i + 1}`).join(', ')}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rodapé
|
|
||||||
page.drawText('Este relatório foi gerado automaticamente pelo sistema AdvX Web Proof Capture', {
|
|
||||||
x: 50,
|
|
||||||
y: 50,
|
|
||||||
size: 8,
|
|
||||||
font: helveticaFont,
|
|
||||||
color: rgb(0.5, 0.5, 0.5)
|
|
||||||
});
|
|
||||||
|
|
||||||
// Salvar PDF
|
|
||||||
const pdfBytes = await pdfDoc.save();
|
|
||||||
const reportDir = path.join(process.cwd(), 'storage', 'web-proofs');
|
|
||||||
await fs.mkdir(reportDir, { recursive: true });
|
|
||||||
|
|
||||||
const reportPath = path.join(reportDir, `${data.sessionId}_report.pdf`);
|
|
||||||
await fs.writeFile(reportPath, pdfBytes);
|
|
||||||
|
|
||||||
return reportPath;
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao gerar relatório PDF:', error);
|
|
||||||
throw new Error('Falha na geração do relatório');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar autenticidade da captura
|
|
||||||
async verifyWebCapture(sessionId: string) {
|
|
||||||
try {
|
|
||||||
const session = await prisma.webProofSession.findUnique({
|
|
||||||
where: { sessionId }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
return {
|
|
||||||
verified: false,
|
|
||||||
details: 'Sessão não encontrada'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar integridade dos hashes
|
|
||||||
const sessionHashValid = await this.verifySessionHash(session);
|
|
||||||
const contentHashValid = await this.verifyContentHash(session);
|
|
||||||
const timestampValid = this.verifyTimestamp(session.trustedTimestamp);
|
|
||||||
|
|
||||||
return {
|
|
||||||
verified: sessionHashValid && contentHashValid && timestampValid,
|
|
||||||
sessionValid: sessionHashValid,
|
|
||||||
contentValid: contentHashValid,
|
|
||||||
timestampValid: timestampValid,
|
|
||||||
details: {
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
targetUrl: session.targetUrl,
|
|
||||||
status: session.status,
|
|
||||||
sessionHashValid,
|
|
||||||
contentHashValid,
|
|
||||||
timestampValid,
|
|
||||||
createdAt: session.createdAt,
|
|
||||||
processedAt: session.processedAt
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro na verificação:', error);
|
|
||||||
return {
|
|
||||||
verified: false,
|
|
||||||
sessionValid: false,
|
|
||||||
contentValid: false,
|
|
||||||
timestampValid: false,
|
|
||||||
details: 'Erro durante a verificação'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar hash da sessão
|
|
||||||
private async verifySessionHash(session: any): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const expectedHash = await this.generateSessionHash({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
targetUrl: session.targetUrl,
|
|
||||||
metadata: session.metadata,
|
|
||||||
environment: session.environment,
|
|
||||||
screenshots: session.screenshots
|
|
||||||
});
|
|
||||||
|
|
||||||
return expectedHash === session.sessionHash;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar hash do conteúdo
|
|
||||||
private async verifyContentHash(session: any): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const expectedHash = await this.generateContentHash(
|
|
||||||
session.targetUrl,
|
|
||||||
session.metadata
|
|
||||||
);
|
|
||||||
|
|
||||||
return expectedHash === session.contentHash;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar timestamp confiável
|
|
||||||
private verifyTimestamp(trustedTimestamp: string | null): boolean {
|
|
||||||
if (!trustedTimestamp) return false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const timestamp = new Date(trustedTimestamp);
|
|
||||||
const now = new Date();
|
|
||||||
const diffInHours = Math.abs(now.getTime() - timestamp.getTime()) / (1000 * 60 * 60);
|
|
||||||
|
|
||||||
// Considerar válido se o timestamp for de até 24 horas atrás
|
|
||||||
return diffInHours <= 24;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Função auxiliar para delay
|
|
||||||
private delay(ms: number): Promise<void> {
|
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
Vendored
+2
-2
@@ -1,5 +1,3 @@
|
|||||||
import { Request } from 'express';
|
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
namespace Express {
|
namespace Express {
|
||||||
interface Request {
|
interface Request {
|
||||||
@@ -11,3 +9,5 @@ declare global {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export {};
|
||||||
@@ -17,6 +17,8 @@ export default defineConfig({
|
|||||||
target: 'http://localhost:5000',
|
target: 'http://localhost:5000',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
secure: false,
|
secure: false,
|
||||||
|
timeout: 600000, // 10 minutos para operações longas (PDF, OCR)
|
||||||
|
proxyTimeout: 600000,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
hmr: {
|
hmr: {
|
||||||
|
|||||||
Reference in new issue
Block a user