Author SHA1 Message Date
evandro 49795981eb wip: snapshot das alterações não commitadas (2026-10-20)
Origem: D:/Documents/Github/Downloader
Arquivos omitidos (segredos, bancos de dados, logs, >50 MB): 0
2026-10-20 00:49:26 -03:00
31 changed files with 960 additions and 815 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
{
"permissions": {
"allow": [
"mcp__plugin_context-mode_context-mode__ctx_batch_execute",
"mcp__context-mode__ctx_batch_execute",
"mcp__context-mode__ctx_execute_file"
]
}
}
Submodule .claude/worktrees/agent-a0cb243b added at 5b1600c210.
Submodule .claude/worktrees/agent-a6424abe added at 5b1600c210.
Submodule .claude/worktrees/agent-a85e5c45 added at 5b1600c210.
Submodule .claude/worktrees/agent-aa2cb71d added at 5b1600c210.
-3
View File
@@ -5,9 +5,6 @@ build/
coverage/
.npm/
# Arquivos baixados pelas sessoes do Ephemeral Downloader
server/storage/
# Environment
.env
.env.local
+21
View File
@@ -0,0 +1,21 @@
node_modules/
.next/
dist/
build/
out/
coverage/
.git/
.pnpm-store/
.cache/
*.log
.env
.env.*
__pycache__/
*.pyc
.venv/
venv/
target/
*.exe
*.dll
*.so
*.dylib
+9
View File
@@ -0,0 +1,9 @@
{
"profile": "codex",
"env": {
"OPENAI_BASE_URL": "https://chatgpt.com/backend-api/codex",
"OPENAI_MODEL": "codexplan",
"CHATGPT_ACCOUNT_ID": "6dbec33c-c751-4383-b112-bfc776f39ed7"
},
"createdAt": "2026-04-05T18:55:08.995Z"
}
+109 -106
View File
@@ -1,150 +1,153 @@
# Ephemeral Downloader
## Ephemeral Downloader
**Proxy de download efêmero: a sua VPS baixa o arquivo por uma rota melhor e entrega para o seu navegador, com os arquivos apagados automaticamente depois.**
Um proxy de download efêmero para você usar a **sua VPS como ponte de alta velocidade** entre servidores lentos e a sua máquina local.
![Node](https://img.shields.io/badge/Node-%3E%3D20.19-5FA04E?logo=nodedotjs&logoColor=white)
![TypeScript](https://img.shields.io/badge/TypeScript-5.9-3178C6?logo=typescript&logoColor=white)
![Fastify](https://img.shields.io/badge/Fastify-5-000000?logo=fastify&logoColor=white)
![React](https://img.shields.io/badge/React-19-61DAFB?logo=react&logoColor=black)
![Vite](https://img.shields.io/badge/Vite-7-646CFF?logo=vite&logoColor=white)
![pnpm](https://img.shields.io/badge/pnpm-9%2B-F69220?logo=pnpm&logoColor=white)
Em vez de baixar direto de um host congestionado, você aponta o link para o Ephemeral Downloader, que:
## Sobre
- Faz o download via VPS (geralmente com rota/peering melhor).
- Transmite o arquivo por **streaming** para o seu navegador.
- Libera os recursos assim que o download termina.
Baixar um arquivo grande direto de um host congestionado costuma ser lento, e muitas vezes o gargalo não é a sua internet nem o servidor de origem, e sim o caminho entre eles. O Ephemeral Downloader coloca a sua VPS no meio: o servidor faz o download (normalmente com peering melhor), mostra o progresso em tempo real e entrega o arquivo para você pelo navegador.
Simples, focado e pensado para quem vive baixando ISOs, ROMs e arquivos grandes.
O projeto é focado em uso efêmero. O arquivo fica em um diretório temporário da sessão no servidor e é apagado quando a sessão expira (1 hora sem interação). Não é um proxy de streaming puro: o download passa pelo disco do servidor antes de chegar até você.
---
## Como funciona
## Como funciona (visão rápida)
```
navegador (React + Vite)
│ POST /api/queue {url} GET /api/tasks (polling de 2 s)
▼ ▲
Fastify (server/) ──undici GET──▶ host de origem │
│ │
▼ │
server/storage/<id-da-sessao>/<task>_<arquivo> ────────┘
▲
│ GET /api/download/:taskId (arquivo concluído)
navegador
```
- **Frontend (React + Vite)**
- `POST /api/queue` enfileira a URL e o backend baixa com `undici`, gravando em `server/storage/<id-da-sessão>/` por um pipeline (respeita backpressure e só marca a task como concluída depois do arquivo em disco).
- O frontend faz polling de `GET /api/tasks` a cada 2 segundos e mostra status, progresso, bytes recebidos, total e velocidade em MB/s e Mbps.
- Quando a task conclui, o botão "Save to Disk" busca `GET /api/download/:taskId` e salva o arquivo.
- Em produção o próprio Fastify serve o build do Vite na raiz, com fallback da SPA.
- `GET /stream` é o proxy antigo, mantido apenas respondendo 410 (descontinuado).
- Interface SPA com campo de texto para múltiplos links (um por linha).
- Lista de downloads recentes com:
- Progresso em tempo real.
- Tamanho total e já baixado.
- Velocidade em **MB/s** e **Mbps**.
- Botão para **retomar downloads** que falharam dentro da mesma sessão.
## Stack
- **Backend (Fastify + Streams)**
- Rota `GET /stream?url=...&offset=...` que:
- Faz `HEAD` na origem para validar o link e obter `Content-Length`.
- Faz `GET` (ou `Range: bytes=offset-` para retomada).
- Faz o **streaming direto** para o cliente, sem guardar arquivo em disco.
- Em produção, também serve o build do frontend (Vite) na própria porta do servidor.
| Camada | Escolha |
|---|---|
| Runtime | Node.js 20.19 ou superior |
| Backend | Fastify 5, undici 7 (cliente HTTP), zod (validação) |
| Frontend | React 19, Vite 7, Tailwind CSS 4, lucide-react |
| Linguagem | TypeScript 5.9 |
| Monorepo | pnpm workspaces (`server` e `web`) |
| Deploy | nixpacks (`nixpacks.toml`) |
---
## Requisitos
- Node.js 20.19 ou superior (exigência do Vite 7 e do undici 7; verificado no Node 24.20.0)
- pnpm 9 ou superior (verificado no pnpm 12.4.1; o lockfile é o formato 9.0)
- Portas livres: backend (padrão 3000) e Vite (5173) em desenvolvimento
- Node.js **>= 20**
- `pnpm` **>= 8**
Observação sobre pnpm: a seção `overrides` do `pnpm-workspace.yaml` (fastify e undici com versão mínima de segurança) só é aplicada pelo pnpm 10 ou superior. Com pnpm 9 ela é ignorada.
---
## Início rápido
## Instalação
Clone o repositório e instale as dependências:
```bash
git clone <seu-fork-ou-repo> Downloader
cd Downloader
pnpm install
```
# desenvolvimento: Fastify (3000) + Vite (5173) juntos
---
## Scripts principais
Na raiz do projeto:
- **Desenvolvimento (backend + frontend juntos)**:
```bash
pnpm dev
# abra http://localhost:5173
```
Em desenvolvimento o Vite encaminha `/api` para o backend (proxy configurado em `web/vite.config.ts`), então não é preciso arquivo `.env`. Se a porta 3000 estiver ocupada:
Isso sobe:
- Fastify em `http://localhost:3000`
- Vite em `http://localhost:5173`
- **Build de produção (server + web)**:
```bash
PORT=3100 VITE_API_PROXY=http://localhost:3100 pnpm dev
pnpm build
```
## Uso
1. Cole a URL direta (http ou https) de um arquivo e clique em **Download**.
2. A lista de downloads mostra status, progresso, tamanho e velocidade, atualizada a cada 2 segundos.
3. Quando o download conclui, use **Save to Disk** para salvar o arquivo na sua máquina.
4. A sessão dura 1 hora de inatividade (o contador reinicia a cada interação) e depois os arquivos são apagados do servidor.
## API
| Método | Rota | O que faz |
|---|---|---|
| GET | `/health` | Devolve `{"status":"ok"}`. |
| GET | `/` | Serve a SPA (build do Vite). |
| GET | `/api/session` | Cria ou recupera a sessão e devolve `sessionId`, `expiresAt` e `remainingMs`. O id também vem no header `x-session-id`. |
| POST | `/api/queue` | Corpo `{"url":"https://..."}`. Enfileira e inicia o download, devolvendo a task criada. |
| GET | `/api/tasks` | Lista as tasks da sessão (usado no polling da interface). |
| GET | `/api/download/:taskId` | Entrega o arquivo concluído da task. |
| GET | `/stream` | Descontinuado: responde 410. |
A sessão é identificada pelo header `x-session-id` (a interface guarda o id em `localStorage`). Erros observados: 400 para URL inválida (`{"error":"Invalid URL"}`) ou download não pronto, 403 para task de outra sessão e 404 para task inexistente. Se a origem falhar (por exemplo, 404 no host de origem), a task fica com `status: "error"` e a mensagem em `error`.
## Produção
- **Start de produção (tudo pela porta 3000)**:
```bash
pnpm build # server: tsc | web: tsc -b && vite build
PORT=3000 pnpm start # node server/dist/index.js: API + build do front na mesma porta
pnpm start
```
O `nixpacks.toml` descreve esse fluxo: build em `pnpm install --frozen-lockfile && pnpm build` e start em `pnpm start`.
O servidor Fastify:
Variáveis de ambiente: `PORT` (padrão 3000) e `STORAGE_ROOT` (padrão `server/storage`) no backend; `VITE_API_URL` (host da API no frontend) e `VITE_API_PROXY` (alvo do proxy em dev).
- Servirá o build do Vite na raiz (`/`).
- Continuará expondo `GET /stream` para o proxy de download.
## Estrutura do projeto
---
```
server/ backend Fastify
├── src/index.ts rotas (/health, /api/*), CORS e static do front
└── src/lib/
├── DownloadManager.ts download da origem com undici e gravação na sessão
└── SessionManager.ts sessões, expiração (1 h) e limpeza dos arquivos
web/ frontend React + Vite
├── src/context/ SessionContext (sessão e polling das tasks)
├── src/components/ ui/ (Input, Button, Card, Alert...) e feature/ (form, item, timer)
└── vite.config.ts proxy de /api em desenvolvimento
.agent/ scaffolding de agentes de IA (não faz parte do runtime)
docs/PLAN.md vazio (placeholder nunca preenchido)
nixpacks.toml comandos de build e start do deploy
pnpm-workspace.yaml workspaces, allowBuilds e overrides
## Configuração de ambiente
### Desenvolvimento
Por padrão o frontend conversa com o backend em:
```ts
const API_URL = import.meta.env.VITE_API_URL ?? "http://localhost:3000";
```
## Verificação
Se você mudar a porta ou rodar o backend em outro host, basta criar um arquivo `.env` dentro de `web/`:
Não há testes automatizados neste repositório. O que existe de fato:
```bash
VITE_API_URL=http://seu-backend:3000
```
- `pnpm build` roda o `tsc` do server e `tsc -b && vite build` do web, e é o gate atual;
- `pnpm --filter web lint` roda o eslint (passa com 1 warning de `exhaustive-deps` em `SessionContext.tsx`);
- verificação manual executada em 14/09/2026 (Linux, Node 24.20.0, pnpm 12.4.1): `pnpm install` e `pnpm build` com exit 0; 13 checagens de API passando (`/health`, `/`, `/api/session`, `/api/queue` com URL inválida e válida, `/api/tasks`, `/api/download/:id`, 400/403/404 e `/stream` respondendo 410); download de 10 MB conferido por sha256 idêntico ao da origem; interface verificada em Chrome headless (sessão inicializada, task concluída e "Save to Disk" baixando o arquivo com o mesmo sha256).
### Produção (Nixpacks ou similar)
Adicionar testes automatizados é o próximo passo natural do projeto.
- Defina a variável `PORT` (a maioria das plataformas faz isso automaticamente).
- O servidor Fastify faz fallback para `3000` se `PORT` não estiver definida.
- O arquivo `nixpacks.toml` já descreve:
- Comando de build: `pnpm build`
- Comando de start: `pnpm start`
## Estado atual e limitações
---
- Sessões e tasks ficam em memória: reiniciar o servidor perde a lista de tasks (os arquivos em disco são removidos pelo coletor depois de 1 hora).
- Sem autenticação: qualquer um que alcance o servidor pode enfileirar downloads. Coloque atrás de VPN, autenticação reversa ou firewall.
- Não há retomada de download nem uso de `Range` no fluxo atual (o parâmetro `offset` do antigo `/stream` não existe mais).
- Não há limite de tamanho, banda ou cota: um link muito grande ocupa o disco do servidor até a sessão expirar.
- URLs que não sejam http/https são aceitas na fila e falham depois com `status: "error"`.
- Sem CI configurada e sem arquivo de licença.
- O diretório `.agent/` é scaffolding de ferramentas de IA e não é usado pela aplicação.
## Fluxo de uso típico
## Documentação
1. Você tem uma **VPS bem localizada** (por exemplo, no mesmo continente do servidor de origem).
2. No seu desktop/notebook, abre o Ephemeral Downloader.
3. Cola um ou mais links HTTP/HTTPS diretos (por exemplo, ROMs no SourceForge).
4. Clica em **“Iniciar download”**.
5. A VPS baixa em alta velocidade e o app:
- Mostra o progresso.
- Indica tamanho total / baixado.
- Mostra velocidade agregada em MB/s e Mbps.
6. Se a conexão cair, você pode **retomar** dentro da mesma sessão.
Não há documentação interna além deste README: `docs/PLAN.md` está vazio e `web/README.md` é o texto padrão do template do Vite.
---
## Licença
## Limitações intencionais
Sem licença definida no repositório: não existe arquivo `LICENSE` e o `package.json` está marcado como `private`. Defina uma licença antes de reutilizar ou publicar o código.
- **Retomada entre sessões** (fechar aba / desligar máquina) **não é suportada**.
- O projeto é focado em uso efêmero, sem manter arquivos em disco no servidor.
- O servidor realiza apenas:
- Validação básica de URL (somente `http`/`https`).
- Proxy por streaming com **backpressure** nativo do Node.js.
- Nenhuma autenticação ou controle de cota por usuário (idealmente coloque atrás de VPN, auth reverso ou firewall).
---
## Ideias futuras
- Autenticação simples para restringir o painel.
- Limite de banda por IP/usuário.
- Modo “linha de comando” usando a mesma API do servidor.
---
## Por que esse projeto existe?
Porque às vezes o problema não é a sua internet nem o servidor de origem, e sim o **caminho entre eles**.
Colocando uma VPS no meio do caminho, você “puxa” o arquivo por uma rota melhor até a VPS e, de lá, faz o streaming até você com muito mais previsibilidade.
O Ephemeral Downloader encapsula essa ideia em uma interface simples, focada em quem só quer **colar o link, apertar um botão e acompanhar o progresso**.
+3 -4
View File
@@ -13,7 +13,6 @@
"workspaces": [
"server",
"web"
]
}
],
"packageManager": "[email protected]"
}
-8
View File
@@ -2,17 +2,9 @@ packages:
- server
- web
# pnpm 11/12: sem isto o install falha com ERR_PNPM_IGNORED_BUILDS,
# porque o esbuild (usado pelo Vite) precisa rodar script de build.
allowBuilds:
esbuild: true
# Chave equivalente para pnpm 9/10 (ignorada pelo pnpm 12).
onlyBuiltDependencies:
- esbuild
# Overrides de segurança. Atenção: pnpm 9 e anterior ignoram esta seção
# (o pnpm 10+ lê overrides de pnpm-workspace.yaml).
overrides:
fastify@<5.7.2: '>=5.7.2'
fastify@<=5.7.2: '>=5.7.3'
+153
View File
@@ -0,0 +1,153 @@
import Fastify from "fastify";
import cors from "@fastify/cors";
import fastifyStatic from "@fastify/static";
import { z } from "zod";
import { request } from "undici";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
const app = Fastify({
logger: true,
});
// Registro de CORS básico para permitir o frontend em desenvolvimento/produção.
await app.register(cors, {
origin: true,
});
// Servir frontend buildado (Vite) em produção, similar ao Next.js.
const currentFile = fileURLToPath(import.meta.url);
const currentDir = dirname(currentFile);
const clientDistPath = resolve(currentDir, "../../web/dist");
await app.register(fastifyStatic, {
root: clientDistPath,
prefix: "/",
index: ["index.html"],
});
// Rota explícita para a SPA na raiz, útil especialmente em ambientes de deploy.
app.get("/", (_request, reply) => {
return reply.sendFile("index.html");
});
app.get("/health", async () => {
return { status: "ok" };
});
const streamQuerySchema = z.object({
url: z
.string()
.url("URL inválida")
.refine((value) => {
// Evita SSRF localizando apenas http/https genérico.
return value.startsWith("http://") || value.startsWith("https://");
}, { message: "Apenas URLs HTTP/HTTPS são permitidas." }),
// Offset opcional em bytes para retomar download dentro da mesma sessão.
offset: z
.string()
.regex(/^\d+$/)
.transform((value) => Number.parseInt(value, 10))
.optional(),
});
app.get("/stream", async (requestFastify, reply) => {
const parseResult = streamQuerySchema.safeParse(requestFastify.query);
if (!parseResult.success) {
const firstError = parseResult.error.errors[0]?.message ?? "Parâmetros inválidos";
reply.status(400);
return { error: firstError };
}
const { url, offset } = parseResult.data;
try {
// HEAD para validar link e obter metadados.
const headResponse = await request(url, {
method: "HEAD",
// timeout conservador, em produção pode ser configurável.
headersTimeout: 15000,
});
if (headResponse.statusCode && headResponse.statusCode >= 400) {
reply.status(502);
return { error: "Não foi possível acessar o recurso de origem." };
}
const contentType = headResponse.headers["content-type"] ?? "application/octet-stream";
const contentLength = headResponse.headers["content-length"];
const originDisposition = headResponse.headers["content-disposition"];
// Nome de arquivo derivado do header Content-Disposition ou da URL.
const fallbackName = (() => {
try {
const parsedUrl = new URL(url);
const nameFromPath = parsedUrl.pathname.split("/").filter(Boolean).pop();
return nameFromPath ?? "download.bin";
}
catch {
return "download.bin";
}
})();
const filename = (() => {
if (typeof originDisposition === "string") {
const match = /filename\*?=(?:UTF-8''|")?([^";]+)/i.exec(originDisposition);
if (match?.[1]) {
return decodeURIComponent(match[1].replace(/"/g, ""));
}
}
return fallbackName;
})();
const headers = {};
if (typeof offset === "number" && Number.isFinite(offset) && offset > 0) {
headers.Range = `bytes=${offset}-`;
}
// GET streaming da origem (possivelmente com Range para retomada).
const originResponse = await request(url, {
method: "GET",
headers,
headersTimeout: 30000,
maxRedirections: 3,
});
if (!originResponse.body) {
reply.status(502);
return { error: "Resposta de origem sem corpo para streaming." };
}
if (originResponse.statusCode && originResponse.statusCode >= 400) {
reply.status(originResponse.statusCode);
return { error: "Falha ao obter o arquivo de origem." };
}
const normalizedLength = Array.isArray(contentLength)
? contentLength[0]
: contentLength;
// Configura headers de resposta para o cliente final.
reply.headers({
"Content-Type": Array.isArray(contentType) ? contentType[0] : contentType,
...(normalizedLength
? {
"Content-Length": normalizedLength,
"X-Origin-Content-Length": normalizedLength,
}
: {}),
"Content-Disposition": `attachment; filename="${filename}"`,
});
// Entregamos o stream diretamente para o Fastify gerenciar (pipe + backpressure).
return reply.send(originResponse.body);
}
catch (error) {
requestFastify.log.error({ err: error, url }, "Erro durante o streaming do arquivo");
if (!reply.sent) {
// Em caso de falha antes de iniciar o streaming, respondemos com JSON.
return reply
.status(502)
.send({ error: "Erro ao realizar o proxy do arquivo." });
}
// Se a resposta já foi enviada/fechada, apenas não fazemos mais nada.
}
});
// Fallback para SPA: qualquer rota GET não atendida cai no index.html.
app.setNotFoundHandler((requestFastify, reply) => {
if (requestFastify.method === "GET") {
return reply.sendFile("index.html");
}
reply.status(404).send({ error: "Recurso não encontrado." });
});
const port = Number(process.env.PORT) || 3000;
try {
await app.listen({
port,
host: "0.0.0.0",
});
app.log.info(`Server listening on port ${port}`);
}
catch (err) {
app.log.error(err);
process.exit(1);
}
+4 -7
View File
@@ -5,8 +5,8 @@ import { z } from "zod";
import { Agent, setGlobalDispatcher } from "undici";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import { sessionManager } from "./lib/SessionManager.js";
import { DownloadManager } from "./lib/DownloadManager.js";
import { sessionManager } from "./lib/SessionManager";
import { DownloadManager } from "./lib/DownloadManager";
// Otimização: Agente HTTP global com conexões persistentes e timeout relaxado.
// Isso ajuda a manter a performance em downloads paralelos e evita gargalos de socket.
@@ -118,14 +118,11 @@ app.get("/api/download/:taskId", async (request, reply) => {
if (task.status !== "completed") return reply.status(400).send({ error: "Download not ready" });
const sessionPath = sessionManager.getSessionPath(session.id);
const fileName = `${task.id}_${task.filename}`;
const filePath = resolve(sessionPath, `${task.id}_${task.filename}`);
try {
sessionManager.touch(session.id); // Reset timer on interaction
// O @fastify/static resolve caminhos a partir do `root` do plugin (web/dist),
// então o root do diretório da sessão é passado por requisição.
// Sem isso a resposta era o index.html da SPA, não o arquivo baixado.
return reply.sendFile(fileName, sessionPath);
return reply.download(filePath, task.filename); // requires @fastify/static or sendFile
} catch (e) {
return reply.status(404).send({ error: "File removed or missing" });
}
+22 -38
View File
@@ -1,10 +1,8 @@
import { createWriteStream, existsSync } from "node:fs";
import { basename, join } from "node:path";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";
import { createWriteStream, existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { request, Dispatcher } from "undici";
import { randomUUID } from "node:crypto";
import { sessionManager } from "./SessionManager.js";
import { sessionManager } from "./SessionManager";
type DownloadStatus = "queued" | "downloading" | "completed" | "error";
@@ -47,7 +45,7 @@ export class DownloadManager {
try {
const u = new URL(url);
const p = u.pathname.split("/").pop();
if (p) filename = basename(p);
if (p) filename = p;
} catch { }
const task: DownloadTask = {
@@ -96,12 +94,7 @@ export class DownloadManager {
if (typeof disposition === "string") {
const match = /filename\*?=(?:UTF-8''|")?([^";]+)/i.exec(disposition);
if (match?.[1]) {
// O header vem do host de origem: usar apenas o nome base evita
// caminho relativo (../) escrevendo fora do diretório da sessão.
const headerName = basename(decodeURIComponent(match[1].replace(/"/g, "")));
if (headerName) {
task.filename = headerName;
}
task.filename = decodeURIComponent(match[1].replace(/"/g, ""));
}
}
@@ -117,38 +110,29 @@ export class DownloadManager {
let lastUpdate = Date.now();
let bytesAtLastUpdate = 0;
// Contador de progresso no meio do pipeline: mantém o cálculo de
// velocidade/progresso sem ler o stream manualmente.
const progressTracker = new Transform({
transform(chunk, _encoding, callback) {
task.receivedBytes += chunk.length;
for await (const chunk of response.body) {
fileStream.write(chunk);
task.receivedBytes += chunk.length;
const now = Date.now();
if (now - lastUpdate > 500) { // Update speed every 500ms
const diff = now - lastUpdate;
const bytesDiff = task.receivedBytes - bytesAtLastUpdate;
task.speed = (bytesDiff / diff) * 1000;
const now = Date.now();
if (now - lastUpdate > 500) { // Update speed every 500ms
const diff = now - lastUpdate;
const bytesDiff = task.receivedBytes - bytesAtLastUpdate;
task.speed = (bytesDiff / diff) * 1000;
if (task.totalBytes > 0) {
task.progress = Math.round((task.receivedBytes / task.totalBytes) * 100);
}
lastUpdate = now;
bytesAtLastUpdate = task.receivedBytes;
// Touch session to keep it alive during download
sessionManager.touch(task.sessionId);
if (task.totalBytes > 0) {
task.progress = Math.round((task.receivedBytes / task.totalBytes) * 100);
}
callback(null, chunk);
},
});
lastUpdate = now;
bytesAtLastUpdate = task.receivedBytes;
// `pipeline` espera o flush em disco e propaga erro de escrita.
// Antes o status virava "completed" antes do arquivo terminar de
// ser gravado e o download podia sair truncado.
await pipeline(response.body, progressTracker, fileStream);
// Touch session to keep it alive during download
sessionManager.touch(task.sessionId);
}
}
fileStream.end();
task.status = "completed";
task.progress = 100;
task.speed = 0;
+2 -11
View File
@@ -1,17 +1,8 @@
import { existsSync, mkdirSync, rmSync, readdirSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { join, resolve } from "node:path";
import { randomUUID } from "node:crypto";
// A raiz de armazenamento é ancorada no diretório do próprio módulo (server/),
// e não no `process.cwd()`: com o cwd errado (por exemplo rodando via
// `pnpm --filter server start`, que executa dentro de server/) os arquivos
// acabavam em server/server/storage. STORAGE_ROOT permite sobrescrever.
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
const SERVER_ROOT = resolve(MODULE_DIR, "..", "..");
const STORAGE_ROOT = process.env.STORAGE_ROOT
? resolve(process.env.STORAGE_ROOT)
: resolve(SERVER_ROOT, "storage");
const STORAGE_ROOT = resolve(process.cwd(), "server/storage");
const SESSION_TIMEOUT_MS = 60 * 60 * 1000; // 1 Hour
type SessionData = {
-290
View File
@@ -1,290 +0,0 @@
.app-root {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2.5rem 1.5rem 3rem;
gap: 2.5rem;
background: radial-gradient(circle at top, #27272a 0, #09090b 45%, #020617 100%);
}
.app-header {
max-width: 640px;
text-align: center;
}
.app-header h1 {
font-size: 2rem;
margin-bottom: 0.5rem;
}
.app-header p {
font-size: 0.98rem;
color: #e4e4e7;
}
.app-header-meta {
margin-top: 0.5rem;
display: flex;
justify-content: center;
gap: 1rem;
flex-wrap: wrap;
font-size: 0.8rem;
color: #a1a1aa;
}
.app-main {
width: 100%;
display: flex;
justify-content: center;
align-items: flex-start;
gap: 2rem;
max-width: 1200px;
margin: 0 auto;
}
.download-form {
width: 100%;
max-width: 560px;
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1.5rem 1.75rem;
border-radius: 1rem;
border: 1px solid rgba(63, 63, 70, 0.9);
background: radial-gradient(circle at top left, #18181b 0, #020617 60%);
box-shadow:
0 18px 40px rgba(0, 0, 0, 0.7),
0 0 0 1px rgba(24, 24, 27, 0.9);
}
.field-label {
font-size: 0.9rem;
font-weight: 500;
}
.field-helper {
font-size: 0.78rem;
color: #a1a1aa;
margin-top: -0.1rem;
}
.url-input {
padding: 0.75rem 0.9rem;
border-radius: 0.5rem;
border: 1px solid #27272a;
background-color: #09090b;
color: #f4f4f5;
font-size: 0.95rem;
resize: vertical;
}
.url-input--multiline {
line-height: 1.4;
}
.url-input:focus {
outline: 2px solid #4f46e5;
outline-offset: 1px;
border-color: transparent;
}
.primary-button {
margin-top: 0.5rem;
padding: 0.75rem 1rem;
border-radius: 0.5rem;
border: none;
background: #4f46e5;
color: #f9fafb;
font-weight: 600;
font-size: 0.95rem;
cursor: pointer;
transition: background 180ms ease-out, transform 160ms ease-out;
}
.primary-button:hover {
background: #4338ca;
}
.primary-button:active {
transform: translateY(1px) scale(0.99);
}
.primary-button:focus-visible {
outline: 2px solid #a5b4fc;
outline-offset: 2px;
}
.error-text {
font-size: 0.85rem;
color: #f97373;
}
.downloads-section {
width: 100%;
max-width: 620px;
margin-top: 0;
padding: 1.25rem 1.5rem;
border-radius: 1rem;
border: 1px solid rgba(63, 63, 70, 0.9);
background-color: rgba(9, 9, 11, 0.9);
backdrop-filter: blur(14px);
}
.downloads-title {
font-size: 1rem;
margin-bottom: 0.5rem;
}
.downloads-empty {
margin-top: 0.5rem;
font-size: 0.85rem;
color: #a1a1aa;
}
.downloads-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.download-item {
padding: 0.6rem 0.1rem 0.7rem;
border-bottom: 1px solid rgba(39, 39, 42, 0.8);
}
.download-item:last-of-type {
border-bottom: none;
}
.download-main {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.35rem;
}
.download-url {
font-size: 0.8rem;
color: #e5e5e5;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge {
padding: 0.2rem 0.55rem;
border-radius: 999px;
font-size: 0.7rem;
font-weight: 500;
}
.badge--pending {
background-color: rgba(39, 39, 42, 0.9);
color: #e5e5e5;
}
.badge--downloading {
background-color: rgba(37, 99, 235, 0.18);
color: #bfdbfe;
}
.badge--completed {
background-color: rgba(22, 163, 74, 0.25);
color: #bbf7d0;
}
.badge--error {
background-color: rgba(239, 68, 68, 0.18);
color: #fecaca;
}
.progress-wrapper {
display: flex;
align-items: center;
gap: 0.5rem;
}
.progress-bar {
flex: 1;
height: 0.4rem;
border-radius: 999px;
background-color: #18181b;
overflow: hidden;
}
.progress-bar__fill {
height: 100%;
border-radius: inherit;
background: linear-gradient(to right, #4f46e5, #22c55e);
transition: width 160ms ease-out;
}
.progress-label {
font-size: 0.75rem;
color: #e4e4e7;
width: 3ch;
text-align: right;
}
.download-error {
margin-top: 0.1rem;
font-size: 0.78rem;
color: #fecaca;
}
.download-meta {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin-top: 0.25rem;
font-size: 0.8rem;
color: #d4d4d8;
}
.download-footer {
margin-top: 0.35rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
}
.secondary-button {
padding: 0.35rem 0.75rem;
border-radius: 999px;
border: 1px solid #3f3f46;
background-color: transparent;
color: #e4e4e7;
font-size: 0.78rem;
font-weight: 500;
cursor: pointer;
transition:
background-color 160ms ease-out,
border-color 160ms ease-out,
transform 120ms ease-out;
}
.secondary-button:hover {
background-color: rgba(63, 63, 70, 0.4);
border-color: #71717a;
}
.secondary-button:active {
transform: translateY(1px) scale(0.99);
}
@media (min-width: 768px) {
.app-header h1 {
font-size: 2.25rem;
}
.download-form {
padding: 1.75rem 2rem;
}
}
+86 -42
View File
@@ -1,26 +1,43 @@
import "./App.css";
import { AlertCircle, HardDrive, Server } from "lucide-react";
import { DownloadForm } from "./components/feature/DownloadForm";
import { DownloadItem } from "./components/feature/DownloadItem";
import { Layout } from "./components/ui/Layout";
import { Alert, AlertDescription, AlertTitle } from "./components/ui/Alert";
import { AlertCircle } from "lucide-react";
import { SessionProvider, useSession } from "./context/SessionContext";
import { SessionTimer } from "./components/feature/SessionTimer";
import { Alert, AlertDescription, AlertTitle } from "./components/ui/Alert";
import { Layout } from "./components/ui/Layout";
import { SessionProvider } from "./context/SessionContext";
import { useSession } from "./context/session-context";
function DownloadList() {
const { tasks, expiresAt } = useSession();
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold tracking-tight">Active Downloads</h2>
<SessionTimer expiresAt={expiresAt} />
<section className="space-y-5">
<div className="flex flex-col gap-4 rounded-[2rem] border border-border/70 bg-card/60 p-6 shadow-[0_24px_80px_-40px_rgba(15,23,42,0.95)] backdrop-blur-xl md:flex-row md:items-center md:justify-between">
<div className="space-y-2">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-primary/80">
Transfer activity
</p>
<h2 className="text-2xl font-semibold tracking-tight text-foreground">
Downloads in this session
</h2>
<p className="max-w-2xl text-sm leading-6 text-muted-foreground">
Monitor queue status, transfer speed and final files from a single workspace.
</p>
</div>
<SessionTimer expiresAt={expiresAt} className="md:min-w-[260px]" />
</div>
{tasks.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground border-2 border-dashed rounded-lg bg-card/50">
<p>No downloads in session</p>
<p className="text-xs opacity-70">Files are removed after 1 hour of inactivity</p>
<div className="rounded-[2rem] border border-dashed border-border/80 bg-card/35 px-6 py-14 text-center shadow-[0_24px_80px_-50px_rgba(15,23,42,0.95)]">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-primary/75">
Queue is empty
</p>
<h3 className="mt-3 text-2xl font-semibold tracking-tight text-foreground">
No downloads yet
</h3>
<p className="mx-auto mt-3 max-w-xl text-sm leading-6 text-muted-foreground">
Your queued, active and completed transfers will appear here with progress, speed and the final save action.
</p>
</div>
) : (
<div className="grid gap-4">
@@ -29,50 +46,77 @@ function DownloadList() {
))}
</div>
)}
</div>
</section>
);
}
function Main() {
const { queueDownload } = useSession();
const { queueDownload, sessionId } = useSession();
const handleDownload = async (url: string) => {
try {
await queueDownload(url);
} catch (error) {
console.error("Failed to queue", error);
}
const handleDownload = async (url: string): Promise<void> => {
await queueDownload(url);
};
return (
<Layout>
<div className="grid gap-8 lg:grid-cols-12">
{/* Left Column: Input Form */}
<div className="lg:col-span-4 space-y-6">
<div className="sticky top-24 space-y-6">
<section className="space-y-4">
<div className="space-y-2">
<h2 className="text-xl font-semibold tracking-tight">New Download</h2>
<p className="text-sm text-muted-foreground">
Paste a link to start. Files are downloaded to the server first.
<div className="grid gap-8 xl:grid-cols-[minmax(0,430px)_minmax(0,1fr)] xl:items-start">
<div className="space-y-6 xl:sticky xl:top-28">
<section className="rounded-[2rem] border border-border/70 bg-card/55 p-6 shadow-[0_24px_90px_-45px_rgba(15,23,42,0.98)] backdrop-blur-xl md:p-7">
<span className="inline-flex rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-primary">
Private download workspace
</span>
<div className="mt-5 space-y-3">
<h1 className="max-w-lg text-3xl font-semibold tracking-tight text-foreground md:text-[2.5rem] md:leading-[1.05]">
Queue secure transfers from a cleaner control panel.
</h1>
<p className="max-w-xl text-sm leading-7 text-muted-foreground md:text-[0.95rem]">
Paste a file URL, let the server fetch it first, then keep every transfer visible until the session window expires.
</p>
</div>
<div className="mt-6 grid gap-3 sm:grid-cols-2">
<div className="rounded-[1.5rem] border border-white/6 bg-background/45 p-4">
<Server className="h-5 w-5 text-primary" />
<p className="mt-4 text-sm font-semibold text-foreground">Server-side transfer</p>
<p className="mt-2 text-sm leading-6 text-muted-foreground">
Downloads are fetched on the VPS first, then exposed as a final file in your session.
</p>
</div>
<DownloadForm onDownload={handleDownload} />
</section>
<div className="rounded-[1.5rem] border border-white/6 bg-background/45 p-4">
<HardDrive className="h-5 w-5 text-primary" />
<p className="mt-4 text-sm font-semibold text-foreground">Ephemeral storage</p>
<p className="mt-2 text-sm leading-6 text-muted-foreground">
Files stay available for one hour of activity and are removed automatically after expiration.
</p>
</div>
</div>
</section>
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Ephemeral Session</AlertTitle>
<AlertDescription>
Files are stored for <strong>1 hour</strong>. The timer resets on interaction.
After expiration, all files are permanently deleted.
</AlertDescription>
</Alert>
</div>
<section className="rounded-[2rem] border border-border/70 bg-card/70 p-6 shadow-[0_24px_90px_-45px_rgba(15,23,42,0.98)] backdrop-blur-xl md:p-7">
<div className="space-y-2">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-primary/80">New transfer</p>
<h2 className="text-2xl font-semibold tracking-tight text-foreground">Start a new download</h2>
<p className="text-sm leading-6 text-muted-foreground">
Paste a direct file URL to add it to the active session queue.
</p>
</div>
<div className="mt-6">
<DownloadForm onDownload={handleDownload} isReady={Boolean(sessionId)} />
</div>
</section>
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Ephemeral session policy</AlertTitle>
<AlertDescription>
Files are stored for <strong>1 hour</strong>. The timer resets on activity, and once the session expires every stored file is deleted permanently.
</AlertDescription>
</Alert>
</div>
{/* Right Column: Downloads List */}
<div className="lg:col-span-8">
<div className="min-w-0">
<DownloadList />
</div>
</div>
+58 -21
View File
@@ -1,22 +1,32 @@
import { useState } from "react";
import { Download, Loader2 } from "lucide-react";
import { z } from "zod";
import { Button } from "../ui/Button";
import { Input } from "../ui/Input";
import { Download } from "lucide-react";
import { z } from "zod";
const formSchema = z.object({
url: z.string().url("Please enter a valid URL"),
});
interface DownloadFormProps {
onDownload: (url: string) => void;
onDownload: (url: string) => Promise<void> | void;
isReady: boolean;
}
export function DownloadForm({ onDownload }: DownloadFormProps) {
function getErrorMessage(error: unknown): string {
if (error instanceof Error && error.message) {
return error.message;
}
return "Unable to queue the download right now.";
}
export function DownloadForm({ onDownload, isReady }: DownloadFormProps) {
const [url, setUrl] = useState("");
const [error, setError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setError(null);
@@ -27,26 +37,53 @@ export function DownloadForm({ onDownload }: DownloadFormProps) {
return;
}
onDownload(url);
setUrl("");
if (!isReady) {
setError("Session is still initializing. Try again in a moment.");
return;
}
try {
setIsSubmitting(true);
await onDownload(url);
setUrl("");
} catch (submitError: unknown) {
setError(getErrorMessage(submitError));
} finally {
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit} className="flex w-full flex-col gap-4">
<div className="flex w-full items-start gap-2">
<div className="flex-1 space-y-1">
<Input
type="url"
placeholder="https://example.com/file.zip"
value={url}
onChange={(e) => setUrl(e.target.value)}
className={error ? "border-destructive focus-visible:ring-destructive" : ""}
/>
{error && <p className="text-xs text-destructive">{error}</p>}
<form onSubmit={handleSubmit} className="flex w-full flex-col gap-5">
<div className="space-y-3">
<label htmlFor="download-url" className="text-sm font-semibold text-foreground">
File URL
</label>
<Input
id="download-url"
type="url"
placeholder="https://example.com/file.zip"
value={url}
onChange={(e) => setUrl(e.target.value)}
disabled={isSubmitting}
className={error ? "border-destructive/60 focus-visible:ring-destructive/15" : ""}
/>
<div className="flex flex-col gap-2 text-xs text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
<span>Use a direct file link whenever possible for faster server-side fetching.</span>
<span className="font-medium text-primary/80">
{isReady ? "Validated before queueing" : "Preparing session"}
</span>
</div>
<Button type="submit">
<Download className="mr-2 h-4 w-4" />
Download
{error ? <p className="text-sm text-destructive">{error}</p> : null}
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="max-w-sm text-sm leading-6 text-muted-foreground">
The transfer starts on the server first, then becomes available in your session list.
</p>
<Button type="submit" disabled={!isReady || isSubmitting} className="w-full gap-2 sm:w-auto sm:min-w-[180px]">
{isSubmitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
{isSubmitting ? "Queueing..." : "Queue download"}
</Button>
</div>
</form>
+183 -105
View File
@@ -1,140 +1,218 @@
import { useState } from "react";
import {
FileCheck,
FileWarning,
HardDrive,
Loader2,
Server,
HardDrive
} from "lucide-react";
import { DownloadStatus, DownloadTask, useSession } from "../../context/session-context";
import { formatBytes, formatSpeed } from "../../lib/utils";
import { Button } from "../ui/Button";
import { Card, CardContent } from "../ui/Card";
import { Progress } from "../ui/ProgressBar";
import { formatBytes, formatSpeed } from "../../lib/utils";
// Mesma origem por padrão (em produção o Fastify serve a API e o build do front).
// Defina VITE_API_URL para apontar para outro host.
const API_URL = import.meta.env.VITE_API_URL || "";
export type DownloadStatus = "queued" | "downloading" | "completed" | "error";
export type DownloadItemData = {
id: string;
sessionId: string;
url: string;
filename: string;
status: DownloadStatus;
progress: number;
totalBytes: number;
receivedBytes: number;
speed: number;
error?: string;
createdAt: number;
};
const createdAtFormatter = new Intl.DateTimeFormat(undefined, {
hour: "2-digit",
minute: "2-digit",
});
interface DownloadItemProps {
item: DownloadItemData;
item: DownloadTask;
}
const statusLabel: Record<DownloadStatus, string> = {
queued: "Queued",
downloading: "Transferring",
completed: "Ready",
error: "Issue",
};
function getDownloadErrorMessage(error: unknown): string {
if (error instanceof Error && error.message) {
return error.message;
}
return "Failed to download file.";
}
export function DownloadItem({ item }: DownloadItemProps) {
const { sessionId } = useSession();
const [downloadError, setDownloadError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const isCompleted = item.status === "completed";
const isError = item.status === "error";
const isQueued = item.status === "queued";
const handleDownloadFile = () => {
const download = async () => {
try {
const sessionId = localStorage.getItem("downloader_session_id") || "";
const res = await fetch(`${API_URL}/api/download/${item.id}`, {
headers: { "x-session-id": sessionId }
});
if (!res.ok) throw new Error("Download failed");
const statusBadgeClass = isCompleted
? "border-emerald-400/20 bg-emerald-400/10 text-emerald-300"
: isError
? "border-destructive/30 bg-destructive/10 text-destructive"
: isQueued
? "border-amber-400/20 bg-amber-400/10 text-amber-300"
: "border-primary/20 bg-primary/10 text-primary";
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = item.filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch {
alert("Failed to download file");
const statusDetail = isCompleted
? "File cached and ready to be saved locally."
: isError
? "The transfer stopped before completion."
: isQueued
? "Waiting for the server to start processing."
: "Receiving data from the source URL.";
const handleDownloadFile = async (): Promise<void> => {
try {
setDownloadError(null);
setIsSaving(true);
const response = await fetch(`${API_URL}/api/download/${item.id}`, {
headers: { "x-session-id": sessionId },
});
if (!response.ok) {
throw new Error("Failed to fetch the stored file.");
}
};
download();
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = item.filename;
document.body.appendChild(anchor);
anchor.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(anchor);
} catch (error: unknown) {
setDownloadError(getDownloadErrorMessage(error));
} finally {
setIsSaving(false);
}
};
return (
<Card className="overflow-hidden transition-all hover:bg-muted/50">
<CardContent className="p-4">
<div className="flex items-start gap-4">
<div className="mt-1">
{isCompleted ? (
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-green-500/10 text-green-500">
<FileCheck className="h-5 w-5" />
<Card className="group overflow-hidden border-border/80 bg-card/75 transition-all duration-200 hover:-translate-y-0.5 hover:border-primary/25 hover:bg-card/90">
<CardContent className="p-5">
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div className="flex min-w-0 gap-4">
<div className="mt-1">
{isCompleted ? (
<div className="flex h-12 w-12 items-center justify-center rounded-[1.25rem] border border-emerald-400/20 bg-emerald-400/10 text-emerald-300">
<FileCheck className="h-5 w-5" />
</div>
) : isError ? (
<div className="flex h-12 w-12 items-center justify-center rounded-[1.25rem] border border-destructive/30 bg-destructive/10 text-destructive">
<FileWarning className="h-5 w-5" />
</div>
) : isQueued ? (
<div className="flex h-12 w-12 items-center justify-center rounded-[1.25rem] border border-amber-400/20 bg-amber-400/10 text-amber-300">
<Server className="h-5 w-5" />
</div>
) : (
<div className="flex h-12 w-12 items-center justify-center rounded-[1.25rem] border border-primary/20 bg-primary/10 text-primary">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
)}
</div>
) : isError ? (
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-destructive/10 text-destructive">
<FileWarning className="h-5 w-5" />
</div>
) : isQueued ? (
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-secondary text-secondary-foreground">
<Server className="h-5 w-5 animate-pulse" />
</div>
) : (
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
)}
</div>
<div className="flex-1 space-y-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<div className="space-y-1 truncate">
<h3 className="font-medium leading-none truncate" title={item.filename || item.url}>
{item.filename || item.url}
</h3>
<p className="text-xs text-muted-foreground truncate" title={item.url}>
{item.url}
</p>
<div className="min-w-0 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<span className={`inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] ${statusBadgeClass}`}>
{statusLabel[item.status]}
</span>
<span className="text-xs text-muted-foreground">
Created at {createdAtFormatter.format(item.createdAt)}
</span>
</div>
<div className="space-y-1">
<h3 className="truncate text-base font-semibold tracking-tight text-foreground" title={item.filename || item.url}>
{item.filename || item.url}
</h3>
<p className="truncate text-sm text-muted-foreground" title={item.url}>
{item.url}
</p>
</div>
</div>
{isCompleted && (
<Button size="sm" onClick={handleDownloadFile} className="shrink-0 gap-2">
<HardDrive className="w-4 h-4" />
Save to Disk
</Button>
)}
</div>
{/* Progress Section */}
{!isCompleted && !isError && (
<div className="space-y-2 pt-2">
<div className="flex justify-between text-xs text-muted-foreground">
<span>{isQueued ? "Queued on server..." : item.status}</span>
<span>{formatBytes(item.receivedBytes || 0)} / {item.totalBytes ? formatBytes(item.totalBytes) : "??"}</span>
</div>
<Progress value={item.progress || 0} className="h-1.5" />
<div className="flex justify-between text-xs text-muted-foreground">
<span>{item.speed ? formatSpeed(item.speed) : "0 B/s"}</span>
<span>{item.progress ? `${Math.round(item.progress)}%` : "0%"}</span>
</div>
</div>
)}
{isCompleted && (
<div className="pt-2 flex items-center gap-2 text-xs text-green-500">
<FileCheck className="w-3 h-3" />
<span>Ready for download ({formatBytes(item.totalBytes)})</span>
</div>
)}
{isError && (
<div className="text-sm text-destructive pt-1">
{item.error || "Unknown error occurred"}
</div>
)}
{isCompleted ? (
<Button size="sm" onClick={handleDownloadFile} disabled={isSaving} className="w-full gap-2 lg:w-auto lg:shrink-0">
{isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <HardDrive className="h-4 w-4" />}
{isSaving ? "Saving..." : "Save file"}
</Button>
) : null}
</div>
<div className="grid gap-3 md:grid-cols-3">
<div className="rounded-[1.25rem] border border-white/6 bg-background/35 p-4">
<p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground/75">
Status
</p>
<p className="mt-2 text-sm font-medium text-foreground">{statusDetail}</p>
</div>
<div className="rounded-[1.25rem] border border-white/6 bg-background/35 p-4">
<p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground/75">
Size
</p>
<p className="mt-2 text-sm font-medium text-foreground">
{item.totalBytes ? formatBytes(item.totalBytes) : "Unknown until available"}
</p>
</div>
<div className="rounded-[1.25rem] border border-white/6 bg-background/35 p-4">
<p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground/75">
Throughput
</p>
<p className="mt-2 text-sm font-medium text-foreground">
{item.speed ? formatSpeed(item.speed) : "Waiting for activity"}
</p>
</div>
</div>
{!isCompleted && !isError ? (
<div className="rounded-[1.5rem] border border-white/6 bg-background/45 p-4">
<div className="flex items-center justify-between text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground/75">
<span>{isQueued ? "Waiting on server" : "Transfer progress"}</span>
<span>{item.progress ? `${Math.round(item.progress)}%` : "0%"}</span>
</div>
<Progress
value={item.progress || 0}
className="mt-3"
indicatorClassName={isQueued ? "opacity-60" : undefined}
/>
<div className="mt-3 flex flex-col gap-2 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
<span>
{formatBytes(item.receivedBytes || 0)} / {item.totalBytes ? formatBytes(item.totalBytes) : "Unknown"}
</span>
<span>{item.speed ? formatSpeed(item.speed) : "No transfer speed yet"}</span>
</div>
</div>
) : null}
{isCompleted ? (
<div className="rounded-[1.5rem] border border-emerald-400/20 bg-emerald-400/10 p-4 text-sm text-foreground">
<p className="font-semibold text-emerald-300">Transfer completed successfully</p>
<p className="mt-2 text-muted-foreground">
The file is ready in the current session and can be saved to disk at any time before expiration.
</p>
</div>
) : null}
{downloadError ? (
<div className="rounded-[1.5rem] border border-destructive/30 bg-destructive/10 p-4 text-sm text-foreground">
<p className="font-semibold text-destructive">Unable to save file</p>
<p className="mt-2 text-muted-foreground">{downloadError}</p>
</div>
) : null}
{isError ? (
<div className="rounded-[1.5rem] border border-destructive/30 bg-destructive/10 p-4 text-sm text-foreground">
<p className="font-semibold text-destructive">Transfer failed</p>
<p className="mt-2 text-muted-foreground">
{item.error || "Unknown error occurred during the transfer."}
</p>
</div>
) : null}
</div>
</CardContent>
</Card>
+36 -7
View File
@@ -12,7 +12,9 @@ export function SessionTimer({ expiresAt, className }: SessionTimerProps) {
const [isCritical, setIsCritical] = useState(false);
useEffect(() => {
if (!expiresAt) return;
if (!expiresAt) {
return;
}
const tick = () => {
const now = Date.now();
@@ -29,20 +31,47 @@ export function SessionTimer({ expiresAt, className }: SessionTimerProps) {
const seconds = Math.floor((diff % 60000) / 1000);
setTimeLeft(`${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`);
setIsCritical(minutes < 5); // Critical if less than 5 minutes
setIsCritical(minutes < 5);
};
tick(); // Initial call
tick();
const interval = setInterval(tick, 1000);
return () => clearInterval(interval);
}, [expiresAt]);
if (!expiresAt) return null;
if (!expiresAt) {
return null;
}
return (
<div className={cn("flex items-center gap-2 text-sm font-medium", isCritical ? "text-destructive" : "text-muted-foreground", className)}>
<Clock className="w-4 h-4" />
<span>Session: {timeLeft}</span>
<div
className={cn(
"inline-flex items-center justify-between gap-4 rounded-[1.5rem] border px-4 py-3 shadow-[0_20px_60px_-40px_rgba(15,23,42,0.95)] backdrop-blur-xl",
isCritical
? "border-destructive/30 bg-destructive/10"
: "border-primary/20 bg-primary/10",
className
)}
>
<div className="flex items-center gap-3">
<div
className={cn(
"flex h-10 w-10 items-center justify-center rounded-[1rem] border",
isCritical
? "border-destructive/30 bg-destructive/10 text-destructive"
: "border-primary/20 bg-primary/10 text-primary"
)}
>
<Clock className="h-4 w-4" />
</div>
<div>
<p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground/75">
Session window
</p>
<p className="mt-1 text-sm font-semibold text-foreground">Expires in {timeLeft}</p>
</div>
</div>
<span className="text-xs font-medium text-muted-foreground">Auto cleanup</span>
</div>
);
}
+13 -13
View File
@@ -1,5 +1,5 @@
import * as React from "react"
import { cn } from "../../lib/utils"
import * as React from "react";
import { cn } from "../../lib/utils";
const Alert = React.forwardRef<
HTMLDivElement,
@@ -9,15 +9,15 @@ const Alert = React.forwardRef<
ref={ref}
role="alert"
className={cn(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
"relative w-full rounded-[1.5rem] border border-border/70 bg-card/70 p-5 text-foreground shadow-[0_24px_80px_-40px_rgba(15,23,42,0.9)] backdrop-blur-xl [&>svg~*]:pl-8 [&>svg+div]:translate-y-[-2px] [&>svg]:absolute [&>svg]:left-5 [&>svg]:top-5 [&>svg]:text-foreground",
variant === "destructive" &&
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
"border-destructive/30 bg-destructive/10 text-destructive-foreground [&>svg]:text-destructive",
className
)}
{...props}
/>
))
Alert.displayName = "Alert"
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
@@ -25,11 +25,11 @@ const AlertTitle = React.forwardRef<
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
className={cn("mb-1 font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
@@ -37,10 +37,10 @@ const AlertDescription = React.forwardRef<
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
className={cn("text-sm text-muted-foreground [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription }
export { Alert, AlertTitle, AlertDescription };
+12 -12
View File
@@ -1,8 +1,7 @@
import * as React from "react";
import { cn } from "../../lib/utils";
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "default" | "secondary" | "outline" | "ghost" | "destructive";
size?: "default" | "sm" | "lg" | "icon";
}
@@ -12,21 +11,22 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
return (
<button
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
"inline-flex items-center justify-center whitespace-nowrap rounded-2xl border border-transparent text-sm font-semibold tracking-[-0.01em] text-foreground shadow-[0_18px_40px_-24px_rgba(15,23,42,0.9)] transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",
{
"bg-primary text-primary-foreground hover:bg-primary/90":
"bg-[linear-gradient(135deg,rgba(125,211,252,1),rgba(34,211,238,0.9))] text-slate-950 hover:brightness-105 hover:shadow-[0_22px_48px_-24px_rgba(34,211,238,0.6)]":
variant === "default",
"bg-secondary text-secondary-foreground hover:bg-secondary/80":
"border-border/70 bg-secondary/80 text-secondary-foreground hover:bg-secondary":
variant === "secondary",
"border border-input bg-background hover:bg-accent hover:text-accent-foreground":
"border-border/70 bg-background/60 text-foreground hover:bg-accent/70":
variant === "outline",
"hover:bg-accent hover:text-accent-foreground": variant === "ghost",
"bg-destructive text-destructive-foreground hover:bg-destructive/90":
"border-transparent bg-transparent text-muted-foreground shadow-none hover:bg-accent/60 hover:text-foreground":
variant === "ghost",
"border-destructive/40 bg-destructive/90 text-destructive-foreground hover:bg-destructive":
variant === "destructive",
"h-10 px-4 py-2": size === "default",
"h-9 rounded-md px-3": size === "sm",
"h-11 rounded-md px-8": size === "lg",
"h-10 w-10": size === "icon",
"h-11 px-5 py-2.5": size === "default",
"h-10 rounded-xl px-4": size === "sm",
"h-12 px-6 text-sm": size === "lg",
"h-11 w-11 rounded-2xl": size === "icon",
},
className
)}
+3 -3
View File
@@ -8,7 +8,7 @@ const Card = React.forwardRef<
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
"rounded-[1.75rem] border border-border/70 bg-card/80 text-card-foreground shadow-[0_24px_80px_-40px_rgba(15,23,42,0.95)] backdrop-blur-xl",
className
)}
{...props}
@@ -22,11 +22,11 @@ const CardHeader = React.forwardRef<
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
className={cn("flex flex-col space-y-2 p-6", className)}
{...props}
/>
));
Card.displayName = "CardHeader";
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLParagraphElement,
+1 -1
View File
@@ -9,7 +9,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
"flex h-12 w-full rounded-2xl border border-input/80 bg-background/70 px-4 py-3 text-sm text-foreground shadow-[inset_0_1px_0_rgba(255,255,255,0.03)] outline-none ring-offset-background transition-all placeholder:text-muted-foreground/80 focus-visible:border-primary/60 focus-visible:ring-4 focus-visible:ring-primary/15 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
+36 -19
View File
@@ -7,31 +7,48 @@ type LayoutProps = {
export function Layout({ children }: LayoutProps) {
return (
<div className="min-h-screen bg-background text-foreground font-sans antialiased selection:bg-primary selection:text-primary-foreground">
<div className="absolute inset-0 -z-10 h-full w-full bg-background bg-[linear-gradient(to_right,#8080800a_1px,transparent_1px),linear-gradient(to_bottom,#8080800a_1px,transparent_1px)] bg-[size:14px_24px]"></div>
<div className="absolute left-0 right-0 top-0 -z-10 m-auto h-[310px] w-[310px] rounded-full bg-primary/20 opacity-20 blur-[100px]"></div>
<div className="relative min-h-screen overflow-hidden bg-background text-foreground selection:bg-primary/20 selection:text-foreground">
<div className="pointer-events-none absolute inset-0 -z-20 bg-[radial-gradient(circle_at_top,rgba(34,211,238,0.14),transparent_0_30%),linear-gradient(to_right,rgba(148,163,184,0.04)_1px,transparent_1px),linear-gradient(to_bottom,rgba(148,163,184,0.04)_1px,transparent_1px)] bg-[auto,72px_72px,72px_72px]" />
<div className="pointer-events-none absolute inset-x-0 top-[-120px] -z-10 mx-auto h-[360px] w-[min(760px,100%)] rounded-full bg-[radial-gradient(circle,rgba(56,189,248,0.18),transparent_65%)] blur-3xl" />
<div className="pointer-events-none absolute bottom-[-180px] right-[-80px] -z-10 h-[340px] w-[340px] rounded-full bg-[radial-gradient(circle,rgba(34,211,238,0.14),transparent_70%)] blur-3xl" />
<header className="sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="container flex h-14 max-w-screen-2xl items-center px-4 md:px-8">
<div className="mr-4 flex items-center space-x-2">
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
<MoveDown className="size-5" />
<header className="sticky top-0 z-50 border-b border-white/6 bg-[rgba(8,13,22,0.78)] backdrop-blur-2xl">
<div className="mx-auto flex h-20 w-full max-w-[1400px] items-center justify-between px-4 md:px-8">
<div className="flex items-center gap-4">
<div className="flex h-12 w-12 items-center justify-center rounded-[1.25rem] border border-primary/20 bg-primary/10 text-primary shadow-[0_18px_48px_-28px_rgba(34,211,238,0.8)]">
<MoveDown className="h-5 w-5" />
</div>
<span className="hidden font-bold sm:inline-block">
Ephemeral Downloader
</span>
</div>
<div className="flex flex-1 items-center justify-end space-x-2 md:justify-end">
<nav className="flex items-center space-x-2 text-sm font-medium text-muted-foreground">
<div className="flex items-center gap-2 rounded-full border border-border bg-secondary/50 px-3 py-1 text-xs">
<Server className="size-3" />
<span>VPS Proxy Active</span>
<div>
<p className="text-[11px] font-semibold uppercase tracking-[0.28em] text-primary/80">
Downloader
</p>
<div className="mt-1 flex flex-wrap items-center gap-3">
<span className="text-sm font-semibold text-foreground md:text-base">
Ephemeral transfer console
</span>
<span className="hidden text-sm text-muted-foreground md:inline">
Download workflow with session-bound storage
</span>
</div>
</nav>
</div>
</div>
<div className="hidden items-center gap-3 md:flex">
<div className="rounded-full border border-white/6 bg-white/4 px-4 py-2 text-right">
<p className="text-[11px] font-semibold uppercase tracking-[0.2em] text-muted-foreground">
Environment
</p>
<p className="mt-1 text-sm font-medium text-foreground">Production-ready shell</p>
</div>
<div className="inline-flex items-center gap-2 rounded-full border border-primary/20 bg-primary/10 px-4 py-2 text-sm font-medium text-primary">
<Server className="h-4 w-4" />
<span>Proxy active</span>
</div>
</div>
</div>
</header>
<main className="container max-w-screen-xl py-6 md:py-10 px-4 md:px-8">
<main className="relative mx-auto w-full max-w-[1400px] px-4 pb-10 pt-8 md:px-8 md:pb-16 md:pt-10">
{children}
</main>
</div>
+2 -2
View File
@@ -15,14 +15,14 @@ const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
<div
ref={ref}
className={cn(
"relative h-2 w-full overflow-hidden rounded-full bg-secondary",
"relative h-2.5 w-full overflow-hidden rounded-full bg-white/6",
className
)}
{...props}
>
<div
className={cn(
"h-full w-full flex-1 bg-primary transition-all duration-200 ease-in-out",
"h-full w-full flex-1 rounded-full bg-[linear-gradient(90deg,rgba(125,211,252,0.95),rgba(34,211,238,0.95))] transition-all duration-300 ease-out",
indicatorClassName
)}
style={{ transform: `translateX(-${100 - (percent / max) * 100}%)` }}
+1 -1
View File
@@ -8,7 +8,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
"flex min-h-[120px] w-full rounded-2xl border border-input/80 bg-background/70 px-4 py-3 text-sm text-foreground shadow-[inset_0_1px_0_rgba(255,255,255,0.03)] outline-none ring-offset-background transition-all placeholder:text-muted-foreground/80 focus-visible:border-primary/60 focus-visible:ring-4 focus-visible:ring-primary/15 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
+74 -89
View File
@@ -1,34 +1,5 @@
import React, { createContext, useContext, useEffect, useState } from "react";
type SessionData = {
sessionId: string;
expiresAt: string;
remainingMs: number;
};
type DownloadTask = {
id: string;
sessionId: string;
url: string;
filename: string;
status: "queued" | "downloading" | "completed" | "error";
progress: number;
totalBytes: number;
receivedBytes: number;
speed: number;
error?: string;
createdAt: number;
};
type SessionContextType = {
sessionId: string;
tasks: DownloadTask[];
expiresAt: string | null;
queueDownload: (url: string) => Promise<void>;
refreshTasks: () => void;
};
const SessionContext = createContext<SessionContextType | null>(null);
import React, { useCallback, useEffect, useState } from "react";
import { DownloadTask, SessionContext, SessionData } from "./session-context";
const API_URL = import.meta.env.VITE_API_URL || "";
@@ -39,83 +10,106 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
const [tasks, setTasks] = useState<DownloadTask[]>([]);
const [expiresAt, setExpiresAt] = useState<string | null>(null);
// Initialize Session
useEffect(() => {
const initSession = async () => {
try {
const headers: Record<string, string> = {};
if (sessionId) headers["x-session-id"] = sessionId;
if (sessionId) {
headers["x-session-id"] = sessionId;
}
const res = await fetch(`${API_URL}/api/session`, { headers });
const data = (await res.json()) as SessionData;
const response = await fetch(`${API_URL}/api/session`, { headers });
if (!response.ok) {
throw new Error("Failed to initialize session.");
}
const data = (await response.json()) as SessionData;
if (data.sessionId && data.sessionId !== sessionId) {
setSessionId(data.sessionId);
localStorage.setItem("downloader_session_id", data.sessionId);
}
setExpiresAt(data.expiresAt);
} catch (err) {
console.error("Failed to init session", err);
} catch {
setExpiresAt(null);
}
};
initSession();
void initSession();
}, [sessionId]);
// Poll Tasks
const refreshTasks = async () => {
if (!sessionId) return;
const refreshTasks = useCallback(async (): Promise<void> => {
if (!sessionId) {
return;
}
try {
const res = await fetch(`${API_URL}/api/tasks`, {
const response = await fetch(`${API_URL}/api/tasks`, {
headers: { "x-session-id": sessionId },
});
if (res.ok) {
const data = await res.json();
setTasks(data);
if (!response.ok) {
throw new Error("Failed to fetch tasks.");
}
} catch (err) {
console.error("Failed to fetch tasks", err);
const data = (await response.json()) as DownloadTask[];
setTasks(data);
} catch {
return;
}
};
useEffect(() => {
if (!sessionId) return;
// Initial fetch
refreshTasks();
// Poll every 2 seconds
const interval = setInterval(refreshTasks, 2000);
return () => clearInterval(interval);
}, [sessionId]);
const queueDownload = async (url: string) => {
if (!sessionId) return;
useEffect(() => {
if (!sessionId) {
return;
}
const syncTasks = async (): Promise<void> => {
await refreshTasks();
};
void syncTasks();
const interval = setInterval(() => {
void refreshTasks();
}, 2000);
return () => clearInterval(interval);
}, [refreshTasks, sessionId]);
const queueDownload = async (url: string): Promise<void> => {
if (!sessionId) {
throw new Error("Session is still initializing. Try again in a moment.");
}
const response = await fetch(`${API_URL}/api/queue`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-session-id": sessionId,
},
body: JSON.stringify({ url }),
});
if (!response.ok) {
throw new Error("Failed to queue download.");
}
await refreshTasks();
try {
const res = await fetch(`${API_URL}/api/queue`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-session-id": sessionId,
},
body: JSON.stringify({ url }),
const sessionResponse = await fetch(`${API_URL}/api/session`, {
headers: { "x-session-id": sessionId },
});
if (!res.ok) throw new Error("Failed to queue download");
if (!sessionResponse.ok) {
return;
}
await refreshTasks(); // Immediate refresh
// Update expiration from action
// Ideally we should re-fetch /api/session here too, or just rely on the side-effect
const sessionRes = await fetch(`${API_URL}/api/session`, {
headers: { "x-session-id": sessionId }
});
const sessionData = await sessionRes.json();
const sessionData = (await sessionResponse.json()) as SessionData;
setExpiresAt(sessionData.expiresAt);
} catch (err) {
console.error(err);
throw err;
} catch {
return;
}
};
@@ -125,12 +119,3 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
</SessionContext.Provider>
);
}
// O hook é exportado junto do provider de propósito: o arquivo é o módulo do
// contexto da sessão. A regra abaixo só afeta o Fast Refresh em desenvolvimento.
// eslint-disable-next-line react-refresh/only-export-components
export function useSession() {
const context = useContext(SessionContext);
if (!context) throw new Error("useSession must be used within SessionProvider");
return context;
}
+43
View File
@@ -0,0 +1,43 @@
import { createContext, useContext } from "react";
export type SessionData = {
sessionId: string;
expiresAt: string;
remainingMs: number;
};
export type DownloadStatus = "queued" | "downloading" | "completed" | "error";
export type DownloadTask = {
id: string;
sessionId: string;
url: string;
filename: string;
status: DownloadStatus;
progress: number;
totalBytes: number;
receivedBytes: number;
speed: number;
error?: string;
createdAt: number;
};
export type SessionContextType = {
sessionId: string;
tasks: DownloadTask[];
expiresAt: string | null;
queueDownload: (url: string) => Promise<void>;
refreshTasks: () => Promise<void>;
};
export const SessionContext = createContext<SessionContextType | null>(null);
export function useSession(): SessionContextType {
const context = useContext(SessionContext);
if (!context) {
throw new Error("useSession must be used within SessionProvider");
}
return context;
}
+76 -21
View File
@@ -4,6 +4,9 @@
--color-background: hsl(var(--background));
--color-foreground: hsl(var(--foreground));
--color-card: hsl(var(--card));
--color-card-foreground: hsl(var(--card-foreground));
--color-primary: hsl(var(--primary));
--color-primary-foreground: hsl(var(--primary-foreground));
@@ -24,42 +27,94 @@
--color-ring: hsl(var(--ring));
--radius-lg: var(--radius);
--radius-md: calc(var(--radius) - 2px);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 4px);
--radius-sm: calc(var(--radius) - 8px);
}
@layer base {
:root {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--background: 222 36% 8%;
--foreground: 210 40% 96%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--card: 222 31% 12%;
--card-foreground: 210 40% 96%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--primary: 191 95% 67%;
--primary-foreground: 222 47% 11%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--secondary: 223 24% 18%;
--secondary-foreground: 210 40% 96%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--muted: 223 19% 22%;
--muted-foreground: 214 18% 70%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--accent: 222 24% 17%;
--accent-foreground: 210 40% 96%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
--destructive: 0 72% 56%;
--destructive-foreground: 0 0% 100%;
--radius: 0.5rem;
--border: 223 17% 22%;
--input: 223 17% 22%;
--ring: 191 95% 67%;
--radius: 1.5rem;
}
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
html {
color-scheme: dark;
}
}
body {
@apply min-h-screen bg-background text-foreground antialiased;
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
background-image:
radial-gradient(circle at top, rgba(56, 189, 248, 0.12), transparent 0 32%),
radial-gradient(circle at 80% 18%, rgba(14, 165, 233, 0.08), transparent 0 22%),
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 28%),
linear-gradient(135deg, #080d16 0%, #0d1320 52%, #090d16 100%);
}
#root {
min-height: 100vh;
}
::selection {
background: hsl(var(--primary) / 0.25);
color: hsl(var(--foreground));
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: rgba(15, 23, 42, 0.35);
}
::-webkit-scrollbar-thumb {
background: rgba(148, 163, 184, 0.22);
border-radius: 999px;
border: 2px solid transparent;
background-clip: padding-box;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(148, 163, 184, 0.32);
border-radius: 999px;
border: 2px solid transparent;
background-clip: padding-box;
}
}
-12
View File
@@ -4,16 +4,4 @@ import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
// O frontend chama a API na mesma origem (URL relativa). Em produção quem
// serve o build é o próprio Fastify; em desenvolvimento este proxy encaminha
// /api para o backend. Ajuste o alvo com VITE_API_PROXY se o backend não
// estiver na porta padrão (3000).
proxy: {
'/api': {
target: process.env.VITE_API_PROXY ?? 'http://localhost:3000',
changeOrigin: true,
},
},
},
})