Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10752413c2 |
No files matched your search
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"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 deleted from 5b1600c210.
Submodule .claude/worktrees/agent-a6424abe deleted from 5b1600c210.
Submodule .claude/worktrees/agent-a85e5c45 deleted from 5b1600c210.
Submodule .claude/worktrees/agent-aa2cb71d deleted from 5b1600c210.
@@ -1,21 +0,0 @@
|
||||
node_modules/
|
||||
.next/
|
||||
dist/
|
||||
build/
|
||||
out/
|
||||
coverage/
|
||||
.git/
|
||||
.pnpm-store/
|
||||
.cache/
|
||||
*.log
|
||||
.env
|
||||
.env.*
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
venv/
|
||||
target/
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,153 +1,124 @@
|
||||
## Ephemeral Downloader
|
||||
<div align="center">
|
||||
|
||||
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.
|
||||
# Ephemeral Downloader
|
||||
|
||||
Em vez de baixar direto de um host congestionado, você aponta o link para o Ephemeral Downloader, que:
|
||||
**Use a sua VPS como ponte de alta velocidade: ela baixa o arquivo do host lento,
|
||||
guarda por até 1 hora e entrega a você — tudo por uma SPA com progresso em tempo real.**
|
||||
|
||||
- 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.
|
||||

|
||||

|
||||

|
||||
|
||||
Simples, focado e pensado para quem vive baixando ISOs, ROMs e arquivos grandes.
|
||||
[Como funciona](#como-funciona) · [Execução local](#execu%C3%A7%C3%A3o-local) · [Produção](#produ%C3%A7%C3%A3o) · [Limitações](#limita%C3%A7%C3%B5es-conhecidas)
|
||||
|
||||
---
|
||||
</div>
|
||||
|
||||
## Como funciona (visão rápida)
|
||||
> [!NOTE]
|
||||
> **Estado do projeto:** funcional, sem testes automatizados e sem CI (7 commits,
|
||||
> o último em 2026-02-14). O fluxo atual **baixa primeiro para o disco da VPS** e
|
||||
> só depois entrega o arquivo ao navegador — o modelo antigo de streaming direto
|
||||
> (`GET /stream`, retomada por `offset`) foi aposentado e a rota responde `410`.
|
||||
|
||||
- **Frontend (React + Vite)**
|
||||
> [!IMPORTANT]
|
||||
> **Não há autenticação, cota nem lista de destinos permitidos.** Qualquer cliente
|
||||
> que alcance a porta pode mandar o servidor buscar uma URL e ocupar disco. Coloque
|
||||
> atrás de VPN, proxy com autenticação ou firewall.
|
||||
|
||||
- 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.
|
||||
## Como funciona
|
||||
|
||||
- **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.
|
||||
Por que existe: às vezes o gargalo não é a sua internet nem o servidor de origem, e
|
||||
sim o caminho entre eles. Com uma VPS no meio, o arquivo vem por uma rota melhor até
|
||||
ela, e dela até você.
|
||||
|
||||
---
|
||||
| Etapa | O que acontece |
|
||||
|---|---|
|
||||
| 1. Sessão | A SPA pede `/api/session`; o servidor cria uma sessão (UUID + pasta própria) e o navegador guarda o id em `localStorage` |
|
||||
| 2. Fila | Você cola um link e o servidor começa o download na hora (`queued` → `downloading` → `completed` ou `error`) |
|
||||
| 3. Progresso | A SPA consulta `/api/tasks` a cada 2 s: bytes recebidos/total, porcentagem e velocidade em MB/s e Mbps |
|
||||
| 4. Entrega | Com a tarefa concluída, **Save to Disk** baixa o arquivo da VPS para a sua máquina |
|
||||
| 5. Limpeza | Sem atividade por **1 hora**, a sessão expira e a pasta com os arquivos é apagada; um cronômetro na tela mostra o tempo restante |
|
||||
|
||||
## Requisitos
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant N as Navegador (SPA React)
|
||||
participant V as Fastify (VPS)
|
||||
participant O as Servidor de origem
|
||||
N->>V: GET /api/session
|
||||
V-->>N: x-session-id + expiresAt
|
||||
N->>V: POST /api/queue { url }
|
||||
V->>O: GET url (undici)
|
||||
O-->>V: bytes
|
||||
V->>V: grava em storage/{sessão}/{id}_{arquivo}
|
||||
loop a cada 2 s
|
||||
N->>V: GET /api/tasks
|
||||
V-->>N: progresso, velocidade
|
||||
end
|
||||
N->>V: GET /api/download/{taskId}
|
||||
V-->>N: arquivo
|
||||
Note over V: 1 h sem atividade → sessão e arquivos apagados
|
||||
```
|
||||
|
||||
- Node.js **>= 20**
|
||||
- `pnpm` **>= 8**
|
||||
<details>
|
||||
<summary>API do servidor e detalhes técnicos</summary>
|
||||
|
||||
---
|
||||
| Rota | Função |
|
||||
|---|---|
|
||||
| `GET /health` | `{ "status": "ok" }` |
|
||||
| `GET /api/session` | Cria ou recupera a sessão (cabeçalho `x-session-id`); devolve `sessionId`, `expiresAt` e `remainingMs` |
|
||||
| `POST /api/queue` | Corpo `{ "url": "..." }`; `400` se a URL for inválida; devolve a tarefa |
|
||||
| `GET /api/tasks` | Tarefas da sessão |
|
||||
| `GET /api/download/:taskId` | `404` se não existe, `403` se é de outra sessão, `400` se não concluída; senão envia o arquivo e renova o prazo da sessão |
|
||||
| `GET /stream` | Descontinuada: `410` |
|
||||
| `GET /` e demais `GET` | `index.html` do build do Vite (`web/dist`) |
|
||||
|
||||
## Instalação
|
||||
| Item | Implementação |
|
||||
|---|---|
|
||||
| Servidor | Fastify 5 + `@fastify/cors` (`origin: true`) + `@fastify/static`, validação com `zod` |
|
||||
| Cliente HTTP | `undici` com agente global (até 500 conexões, `keepAliveTimeout` 10 s, `connect` 30 s) e `User-Agent: Ephemeral-Downloader/2.0` |
|
||||
| Nome do arquivo | Da URL; sobrescrito por `Content-Disposition` quando existir |
|
||||
| Armazenamento | `server/storage/{sessão}/{id}_{nome}`, relativo ao diretório de trabalho (`process.cwd()`); coletor a cada 1 min remove sessões expiradas e pastas órfãs com mais de 1 h |
|
||||
| Frontend | React 19, Vite 7, Tailwind CSS 4, `lucide-react`; componentes em `web/src/components/{ui,feature}` |
|
||||
| Estado das tarefas | Em memória (`Map`) — um restart do servidor perde a lista de tarefas |
|
||||
|
||||
Clone o repositório e instale as dependências:
|
||||
</details>
|
||||
|
||||
## Limitações conhecidas
|
||||
|
||||
- **Sem retomada e sem lote de links.** Não há `Range`/`offset` no fluxo atual: download interrompido vira `error` e precisa ser refeito. O formulário aceita uma URL por vez.
|
||||
- **Redirecionamentos.** O `DownloadManager` não define `maxRedirections`, e o `undici.request` não segue redirects por padrão; links que respondem `3xx` (comum em hosts de mirror) podem não resultar no arquivo esperado.
|
||||
- **Entrega via memória do navegador.** O **Save to Disk** faz `fetch` do arquivo inteiro como `blob` antes de salvar; arquivos muito grandes pesam na memória da aba.
|
||||
- **Sessão sem validação de formato.** O `x-session-id` enviado pelo cliente é usado direto para montar o caminho da pasta da sessão.
|
||||
- **Sem limite de tamanho, de downloads simultâneos ou de espaço em disco** — todo link enfileirado começa imediatamente.
|
||||
- `server/dist/index.js` está versionado e é do modelo antigo (só `/stream`, sem `/api/queue`): rode `pnpm build` antes de `pnpm start`.
|
||||
|
||||
## Execução local
|
||||
|
||||
Requisitos: **Node.js ≥ 20** e **pnpm ≥ 8**.
|
||||
|
||||
```bash
|
||||
git clone <seu-fork-ou-repo> Downloader
|
||||
cd Downloader
|
||||
pnpm install
|
||||
pnpm dev # servidor em :3000 (tsx) e Vite em :5173
|
||||
pnpm build # compila server (tsc) e web (tsc -b + vite build)
|
||||
pnpm start # Fastify serve a API e o build do front pela porta 3000
|
||||
```
|
||||
|
||||
---
|
||||
> [!WARNING]
|
||||
> **Defina `VITE_API_URL`.** O `SessionContext` usa `""` (mesma origem) quando a
|
||||
> variável falta, e o `vite.config.ts` não tem proxy — em `pnpm dev` as chamadas a
|
||||
> `/api` batem no Vite e falham. Já o botão **Save to Disk** (`DownloadItem.tsx`)
|
||||
> cai em `http://localhost:3000` quando falta. Crie `web/.env` com
|
||||
> `VITE_API_URL=http://localhost:3000` no dev e, em produção, defina a URL
|
||||
> pública **antes do `pnpm build`** (o valor é embutido no bundle).
|
||||
|
||||
## Scripts principais
|
||||
## Produção
|
||||
|
||||
Na raiz do projeto:
|
||||
O [`nixpacks.toml`](nixpacks.toml) descreve o build (`pnpm install --frozen-lockfile`
|
||||
e `pnpm build`) e o start (`pnpm start`). O servidor lê `PORT` e usa `3000` se a
|
||||
variável não existir; escuta em `0.0.0.0`.
|
||||
|
||||
- **Desenvolvimento (backend + frontend juntos)**:
|
||||
## Avisos
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
Isso sobe:
|
||||
|
||||
- Fastify em `http://localhost:3000`
|
||||
- Vite em `http://localhost:5173`
|
||||
|
||||
- **Build de produção (server + web)**:
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
- **Start de produção (tudo pela porta 3000)**:
|
||||
|
||||
```bash
|
||||
pnpm start
|
||||
```
|
||||
|
||||
O servidor Fastify:
|
||||
|
||||
- Servirá o build do Vite na raiz (`/`).
|
||||
- Continuará expondo `GET /stream` para o proxy de download.
|
||||
|
||||
---
|
||||
|
||||
## 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";
|
||||
```
|
||||
|
||||
Se você mudar a porta ou rodar o backend em outro host, basta criar um arquivo `.env` dentro de `web/`:
|
||||
|
||||
```bash
|
||||
VITE_API_URL=http://seu-backend:3000
|
||||
```
|
||||
|
||||
### Produção (Nixpacks ou similar)
|
||||
|
||||
- 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`
|
||||
|
||||
---
|
||||
|
||||
## Fluxo de uso típico
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Limitações intencionais
|
||||
|
||||
- **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**.
|
||||
- A pasta [`.agent/`](.agent) contém um kit de agentes, skills e workflows para
|
||||
assistentes de IA (*Antigravity Kit*, segundo o `ARCHITECTURE.md`) e não faz
|
||||
parte da aplicação.
|
||||
- Use apenas para baixar conteúdo que você tem direito de baixar.
|
||||
+4
-3
@@ -13,6 +13,7 @@
|
||||
"workspaces": [
|
||||
"server",
|
||||
"web"
|
||||
],
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
.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;
|
||||
}
|
||||
}
|
||||
+42
-86
@@ -1,43 +1,26 @@
|
||||
import { AlertCircle, HardDrive, Server } from "lucide-react";
|
||||
import "./App.css";
|
||||
import { DownloadForm } from "./components/feature/DownloadForm";
|
||||
import { DownloadItem } from "./components/feature/DownloadItem";
|
||||
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";
|
||||
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";
|
||||
|
||||
function DownloadList() {
|
||||
const { tasks, expiresAt } = useSession();
|
||||
|
||||
return (
|
||||
<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 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} />
|
||||
</div>
|
||||
|
||||
{tasks.length === 0 ? (
|
||||
<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 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>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
@@ -46,77 +29,50 @@ function DownloadList() {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Main() {
|
||||
const { queueDownload, sessionId } = useSession();
|
||||
const { queueDownload } = useSession();
|
||||
|
||||
const handleDownload = async (url: string): Promise<void> => {
|
||||
await queueDownload(url);
|
||||
const handleDownload = async (url: string) => {
|
||||
try {
|
||||
await queueDownload(url);
|
||||
} catch (error) {
|
||||
console.error("Failed to queue", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<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.
|
||||
<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.
|
||||
</p>
|
||||
</div>
|
||||
<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>
|
||||
<DownloadForm onDownload={handleDownload} />
|
||||
</section>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
{/* Right Column: Downloads List */}
|
||||
<div className="lg:col-span-8">
|
||||
<DownloadList />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,22 @@
|
||||
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) => Promise<void> | void;
|
||||
isReady: boolean;
|
||||
onDownload: (url: string) => void;
|
||||
}
|
||||
|
||||
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) {
|
||||
export function DownloadForm({ onDownload }: DownloadFormProps) {
|
||||
const [url, setUrl] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
@@ -37,53 +27,26 @@ export function DownloadForm({ onDownload, isReady }: DownloadFormProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
onDownload(url);
|
||||
setUrl("");
|
||||
};
|
||||
|
||||
return (
|
||||
<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>
|
||||
<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>}
|
||||
</div>
|
||||
{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 type="submit">
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,218 +1,138 @@
|
||||
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";
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || "";
|
||||
const createdAtFormatter = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
const API_URL = import.meta.env.VITE_API_URL || "http://localhost:3000";
|
||||
|
||||
interface DownloadItemProps {
|
||||
item: DownloadTask;
|
||||
}
|
||||
export type DownloadStatus = "queued" | "downloading" | "completed" | "error";
|
||||
|
||||
const statusLabel: Record<DownloadStatus, string> = {
|
||||
queued: "Queued",
|
||||
downloading: "Transferring",
|
||||
completed: "Ready",
|
||||
error: "Issue",
|
||||
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;
|
||||
};
|
||||
|
||||
function getDownloadErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return "Failed to download file.";
|
||||
interface DownloadItemProps {
|
||||
item: DownloadItemData;
|
||||
}
|
||||
|
||||
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 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 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 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.");
|
||||
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 (e) {
|
||||
alert("Failed to download file");
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
download();
|
||||
};
|
||||
|
||||
return (
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<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 ? (
|
||||
<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 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" />
|
||||
</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="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 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>
|
||||
{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>
|
||||
)}
|
||||
</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>
|
||||
|
||||
@@ -12,9 +12,7 @@ export function SessionTimer({ expiresAt, className }: SessionTimerProps) {
|
||||
const [isCritical, setIsCritical] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!expiresAt) {
|
||||
return;
|
||||
}
|
||||
if (!expiresAt) return;
|
||||
|
||||
const tick = () => {
|
||||
const now = Date.now();
|
||||
@@ -31,47 +29,20 @@ 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);
|
||||
setIsCritical(minutes < 5); // Critical if less than 5 minutes
|
||||
};
|
||||
|
||||
tick();
|
||||
tick(); // Initial call
|
||||
const interval = setInterval(tick, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [expiresAt]);
|
||||
|
||||
if (!expiresAt) {
|
||||
return null;
|
||||
}
|
||||
if (!expiresAt) return null;
|
||||
|
||||
return (
|
||||
<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 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>
|
||||
);
|
||||
}
|
||||
@@ -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-[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",
|
||||
"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",
|
||||
variant === "destructive" &&
|
||||
"border-destructive/30 bg-destructive/10 text-destructive-foreground [&>svg]:text-destructive",
|
||||
"border-destructive/50 text-destructive dark:border-destructive [&>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-semibold leading-none tracking-tight", className)}
|
||||
className={cn("mb-1 font-medium 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 text-muted-foreground [&_p]:leading-relaxed", className)}
|
||||
className={cn("text-sm [&_p]:leading-relaxed", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDescription.displayName = "AlertDescription";
|
||||
))
|
||||
AlertDescription.displayName = "AlertDescription"
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription };
|
||||
export { Alert, AlertTitle, AlertDescription }
|
||||
@@ -1,7 +1,8 @@
|
||||
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";
|
||||
}
|
||||
@@ -11,22 +12,21 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"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",
|
||||
"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",
|
||||
{
|
||||
"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)]":
|
||||
"bg-primary text-primary-foreground hover:bg-primary/90":
|
||||
variant === "default",
|
||||
"border-border/70 bg-secondary/80 text-secondary-foreground hover:bg-secondary":
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80":
|
||||
variant === "secondary",
|
||||
"border-border/70 bg-background/60 text-foreground hover:bg-accent/70":
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground":
|
||||
variant === "outline",
|
||||
"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":
|
||||
"hover:bg-accent hover:text-accent-foreground": variant === "ghost",
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90":
|
||||
variant === "destructive",
|
||||
"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",
|
||||
"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",
|
||||
},
|
||||
className
|
||||
)}
|
||||
|
||||
@@ -8,7 +8,7 @@ const Card = React.forwardRef<
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"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",
|
||||
"rounded-lg border bg-card text-card-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -22,11 +22,11 @@ const CardHeader = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-2 p-6", className)}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardHeader.displayName = "CardHeader";
|
||||
Card.displayName = "CardHeader";
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> { }
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
@@ -9,7 +10,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"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",
|
||||
"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",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
@@ -7,48 +7,31 @@ type LayoutProps = {
|
||||
|
||||
export function Layout({ children }: LayoutProps) {
|
||||
return (
|
||||
<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" />
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
<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" />
|
||||
</div>
|
||||
<span className="hidden font-bold sm:inline-block">
|
||||
Ephemeral Downloader
|
||||
</span>
|
||||
</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 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>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<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">
|
||||
<main className="container max-w-screen-xl py-6 md:py-10 px-4 md:px-8">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -15,14 +15,14 @@ const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative h-2.5 w-full overflow-hidden rounded-full bg-white/6",
|
||||
"relative h-2 w-full overflow-hidden rounded-full bg-secondary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"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",
|
||||
"h-full w-full flex-1 bg-primary transition-all duration-200 ease-in-out",
|
||||
indicatorClassName
|
||||
)}
|
||||
style={{ transform: `translateX(-${100 - (percent / max) * 100}%)` }}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
|
||||
export interface TextareaProps
|
||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { }
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"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",
|
||||
"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",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
@@ -1,5 +1,34 @@
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { DownloadTask, SessionContext, SessionData } from "./session-context";
|
||||
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);
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || "";
|
||||
|
||||
@@ -10,106 +39,83 @@ 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 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;
|
||||
const res = await fetch(`${API_URL}/api/session`, { headers });
|
||||
const data = (await res.json()) as SessionData;
|
||||
|
||||
if (data.sessionId && data.sessionId !== sessionId) {
|
||||
setSessionId(data.sessionId);
|
||||
localStorage.setItem("downloader_session_id", data.sessionId);
|
||||
}
|
||||
setExpiresAt(data.expiresAt);
|
||||
} catch {
|
||||
setExpiresAt(null);
|
||||
} catch (err) {
|
||||
console.error("Failed to init session", err);
|
||||
}
|
||||
};
|
||||
|
||||
void initSession();
|
||||
initSession();
|
||||
}, [sessionId]);
|
||||
|
||||
const refreshTasks = useCallback(async (): Promise<void> => {
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Poll Tasks
|
||||
const refreshTasks = async () => {
|
||||
if (!sessionId) return;
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/api/tasks`, {
|
||||
const res = await fetch(`${API_URL}/api/tasks`, {
|
||||
headers: { "x-session-id": sessionId },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch tasks.");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setTasks(data);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as DownloadTask[];
|
||||
setTasks(data);
|
||||
} catch {
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch tasks", err);
|
||||
}
|
||||
}, [sessionId]);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
if (!sessionId) return;
|
||||
|
||||
const syncTasks = async (): Promise<void> => {
|
||||
await refreshTasks();
|
||||
};
|
||||
|
||||
void syncTasks();
|
||||
|
||||
const interval = setInterval(() => {
|
||||
void refreshTasks();
|
||||
}, 2000);
|
||||
// Initial fetch
|
||||
refreshTasks();
|
||||
|
||||
// Poll every 2 seconds
|
||||
const interval = setInterval(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();
|
||||
}, [sessionId]);
|
||||
|
||||
const queueDownload = async (url: string) => {
|
||||
if (!sessionId) return;
|
||||
try {
|
||||
const sessionResponse = await fetch(`${API_URL}/api/session`, {
|
||||
headers: { "x-session-id": sessionId },
|
||||
const res = await fetch(`${API_URL}/api/queue`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-session-id": sessionId,
|
||||
},
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
|
||||
if (!sessionResponse.ok) {
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error("Failed to queue download");
|
||||
|
||||
const sessionData = (await sessionResponse.json()) as SessionData;
|
||||
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();
|
||||
setExpiresAt(sessionData.expiresAt);
|
||||
} catch {
|
||||
return;
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -119,3 +125,9 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSession() {
|
||||
const context = useContext(SessionContext);
|
||||
if (!context) throw new Error("useSession must be used within SessionProvider");
|
||||
return context;
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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;
|
||||
}
|
||||
+20
-75
@@ -4,9 +4,6 @@
|
||||
--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));
|
||||
|
||||
@@ -27,94 +24,42 @@
|
||||
--color-ring: hsl(var(--ring));
|
||||
|
||||
--radius-lg: var(--radius);
|
||||
--radius-md: calc(var(--radius) - 4px);
|
||||
--radius-sm: calc(var(--radius) - 8px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 222 36% 8%;
|
||||
--foreground: 210 40% 96%;
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
|
||||
--card: 222 31% 12%;
|
||||
--card-foreground: 210 40% 96%;
|
||||
--primary: 210 40% 98%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--primary: 191 95% 67%;
|
||||
--primary-foreground: 222 47% 11%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
|
||||
--secondary: 223 24% 18%;
|
||||
--secondary-foreground: 210 40% 96%;
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
|
||||
--muted: 223 19% 22%;
|
||||
--muted-foreground: 214 18% 70%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
|
||||
--accent: 222 24% 17%;
|
||||
--accent-foreground: 210 40% 96%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
|
||||
--destructive: 0 72% 56%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 212.7 26.8% 83.9%;
|
||||
|
||||
--border: 223 17% 22%;
|
||||
--input: 223 17% 22%;
|
||||
--ring: 191 95% 67%;
|
||||
|
||||
--radius: 1.5rem;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
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%);
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user