feat: Inicializa a aplicação Downloader com backend para gerenciamento de sessões e downloads, e frontend para interação.
This commit is contained in:
1 parent
c2cadc25f3
commit
5b1600c210
13 files changed
+1308
-738
No files matched your search
Generated
+516
-253
File diff suppressed because it is too large.
Load diff
@@ -4,3 +4,8 @@ packages:
|
||||
|
||||
onlyBuiltDependencies:
|
||||
- esbuild
|
||||
|
||||
overrides:
|
||||
fastify@<5.7.2: '>=5.7.2'
|
||||
fastify@<=5.7.2: '>=5.7.3'
|
||||
undici@<6.23.0: '>=6.23.0'
|
||||
+6
-6
@@ -10,15 +10,15 @@
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^4.28.0",
|
||||
"@fastify/cors": "^9.0.0",
|
||||
"@fastify/static": "^6.12.0",
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"fastify": "^5.7.4",
|
||||
"undici": "^6.21.0",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.9.0",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.6.3"
|
||||
"@types/node": "^25.2.3",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
+69
-101
@@ -1,10 +1,12 @@
|
||||
import Fastify from "fastify";
|
||||
import Fastify, { FastifyRequest, FastifyReply } from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
import { z } from "zod";
|
||||
import { Agent, setGlobalDispatcher, request } from "undici";
|
||||
import { Agent, setGlobalDispatcher } from "undici";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, resolve } from "node:path";
|
||||
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.
|
||||
@@ -59,112 +61,78 @@ const streamQuerySchema = z.object({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
app.get("/stream", async (requestFastify, reply) => {
|
||||
const parseResult = streamQuerySchema.safeParse(requestFastify.query);
|
||||
const downloadManager = new DownloadManager(agent);
|
||||
|
||||
if (!parseResult.success) {
|
||||
const firstError = parseResult.error.errors[0]?.message ?? "Parâmetros inválidos";
|
||||
reply.status(400);
|
||||
return { error: firstError };
|
||||
}
|
||||
// Helper to get session from header
|
||||
const getSession = (req: FastifyRequest, reply: FastifyReply) => {
|
||||
const authHeader = req.headers["x-session-id"];
|
||||
const id = Array.isArray(authHeader) ? authHeader[0] : authHeader;
|
||||
const session = sessionManager.getSession(id);
|
||||
|
||||
const { url, offset } = parseResult.data;
|
||||
// Return the ID for the client to store if it's new
|
||||
reply.header("x-session-id", session.id);
|
||||
return session;
|
||||
};
|
||||
|
||||
// 1. Session Status & Timer
|
||||
app.get("/api/session", async (request, reply) => {
|
||||
const session = getSession(request, reply);
|
||||
return {
|
||||
sessionId: session.id,
|
||||
expiresAt: sessionManager.getExpiresAt(session.id),
|
||||
remainingMs: sessionManager.getSessionTimeRemaining(session.id),
|
||||
};
|
||||
});
|
||||
|
||||
// 2. Queue Download
|
||||
const queueSchema = z.object({
|
||||
url: z.string().url(),
|
||||
});
|
||||
|
||||
app.post("/api/queue", async (request, reply) => {
|
||||
const session = getSession(request, reply);
|
||||
|
||||
const parse = queueSchema.safeParse(request.body);
|
||||
if (!parse.success) return reply.status(400).send({ error: "Invalid URL" });
|
||||
|
||||
const task = await downloadManager.queueDownload(session.id, parse.data.url);
|
||||
return task;
|
||||
});
|
||||
|
||||
// 3. List Tasks (Polling)
|
||||
app.get("/api/tasks", async (request, reply) => {
|
||||
const session = getSession(request, reply);
|
||||
const tasks = downloadManager.getTasks(session.id);
|
||||
return tasks;
|
||||
});
|
||||
|
||||
// 4. Download Completed File (Local -> User)
|
||||
app.get("/api/download/:taskId", async (request, reply) => {
|
||||
const session = getSession(request, reply);
|
||||
const { taskId } = request.params as { taskId: string };
|
||||
|
||||
const task = downloadManager.getTask(taskId);
|
||||
|
||||
if (!task) return reply.status(404).send({ error: "Task not found" });
|
||||
if (task.sessionId !== session.id) return reply.status(403).send({ error: "Unauthorized" });
|
||||
if (task.status !== "completed") return reply.status(400).send({ error: "Download not ready" });
|
||||
|
||||
const sessionPath = sessionManager.getSessionPath(session.id);
|
||||
const filePath = resolve(sessionPath, `${task.id}_${task.filename}`);
|
||||
|
||||
try {
|
||||
// HEAD para validar link e obter metadados.
|
||||
const headResponse = await request(url, {
|
||||
method: "HEAD",
|
||||
headersTimeout: 15000,
|
||||
headers: {
|
||||
"User-Agent": "Ephemeral-Downloader/1.0",
|
||||
},
|
||||
dispatcher: agent,
|
||||
});
|
||||
|
||||
if (headResponse.statusCode && headResponse.statusCode >= 400) {
|
||||
reply.status(502);
|
||||
return { error: `Erro na origem: ${headResponse.statusCode}` };
|
||||
}
|
||||
|
||||
const contentType =
|
||||
headResponse.headers["content-type"] ?? "application/octet-stream";
|
||||
const contentLength = headResponse.headers["content-length"];
|
||||
const originDisposition = headResponse.headers["content-disposition"];
|
||||
|
||||
// Nome de arquivo fallback.
|
||||
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: Record<string, string> = {
|
||||
"User-Agent": "Ephemeral-Downloader/1.0",
|
||||
};
|
||||
|
||||
if (typeof offset === "number" && Number.isFinite(offset) && offset > 0) {
|
||||
headers.Range = `bytes=${offset}-`;
|
||||
}
|
||||
|
||||
// GET streaming da origem.
|
||||
const originResponse = await request(url, {
|
||||
method: "GET",
|
||||
headers,
|
||||
headersTimeout: 30000,
|
||||
maxRedirections: 5,
|
||||
dispatcher: agent,
|
||||
});
|
||||
|
||||
if (!originResponse.body) {
|
||||
reply.status(502);
|
||||
return { error: "Sem corpo de resposta na origem." };
|
||||
}
|
||||
|
||||
if (originResponse.statusCode && originResponse.statusCode >= 400) {
|
||||
reply.status(originResponse.statusCode);
|
||||
return { error: "Falha ao baixar arquivo da origem." };
|
||||
}
|
||||
|
||||
const normalizedLength = Array.isArray(contentLength)
|
||||
? contentLength[0]
|
||||
: contentLength;
|
||||
|
||||
// Configura headers de resposta.
|
||||
reply.headers({
|
||||
"Content-Type": Array.isArray(contentType) ? contentType[0] : contentType,
|
||||
...(normalizedLength
|
||||
? {
|
||||
"Content-Length": normalizedLength,
|
||||
"X-Origin-Content-Length": normalizedLength,
|
||||
}
|
||||
: {}),
|
||||
"Content-Disposition": `attachment; filename="${filename}"`,
|
||||
});
|
||||
|
||||
// Pipe direto.
|
||||
return reply.send(originResponse.body);
|
||||
} catch (error) {
|
||||
requestFastify.log.error({ err: error, url }, "Erro no proxy");
|
||||
if (!reply.sent) {
|
||||
return reply.status(502).send({ error: "Erro interno no proxy." });
|
||||
}
|
||||
sessionManager.touch(session.id); // Reset timer on interaction
|
||||
return reply.download(filePath, task.filename); // requires @fastify/static or sendFile
|
||||
} catch (e) {
|
||||
return reply.status(404).send({ error: "File removed or missing" });
|
||||
}
|
||||
});
|
||||
|
||||
// Legacy Stream (Redirect or Deprecate)
|
||||
app.get("/stream", async (req, reply) => {
|
||||
reply.status(410).send({ error: "Direct streaming is deprecated. Use the new Dashboard." });
|
||||
});
|
||||
|
||||
// Fallback para SPA.
|
||||
app.setNotFoundHandler((requestFastify, reply) => {
|
||||
if (requestFastify.method === "GET") {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
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";
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
// Map to store active task metadata in memory (for speed)
|
||||
// Ideally this would be persisted to JSON in the session folder for crash recovery
|
||||
const tasks = new Map<string, DownloadTask>();
|
||||
const agent = new Dispatcher(); // Should use the global agent from index.ts ideally, or pass it in.
|
||||
|
||||
export class DownloadManager {
|
||||
|
||||
constructor(private globalAgent: Dispatcher) { }
|
||||
|
||||
public getTasks(sessionId: string): DownloadTask[] {
|
||||
return Array.from(tasks.values()).filter(t => t.sessionId === sessionId);
|
||||
}
|
||||
|
||||
public getTask(taskId: string): DownloadTask | undefined {
|
||||
return tasks.get(taskId);
|
||||
}
|
||||
|
||||
public async queueDownload(sessionId: string, url: string): Promise<DownloadTask> {
|
||||
const id = randomUUID();
|
||||
|
||||
// Try to determine filename
|
||||
let filename = "download.bin";
|
||||
try {
|
||||
const u = new URL(url);
|
||||
const p = u.pathname.split("/").pop();
|
||||
if (p) filename = p;
|
||||
} catch { }
|
||||
|
||||
const task: DownloadTask = {
|
||||
id,
|
||||
sessionId,
|
||||
url,
|
||||
filename, // Will be updated after HEAD request if possible
|
||||
status: "queued",
|
||||
progress: 0,
|
||||
totalBytes: 0,
|
||||
receivedBytes: 0,
|
||||
speed: 0,
|
||||
createdAt: Date.now()
|
||||
};
|
||||
|
||||
tasks.set(id, task);
|
||||
this.startDownload(task);
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
private async startDownload(task: DownloadTask) {
|
||||
const sessionPath = sessionManager.getSessionPath(task.sessionId);
|
||||
if (!existsSync(sessionPath)) {
|
||||
task.status = "error";
|
||||
task.error = "Session expired or missing";
|
||||
return;
|
||||
}
|
||||
|
||||
task.status = "downloading";
|
||||
|
||||
try {
|
||||
// Step 1: HEAD/GET to stream
|
||||
const response = await request(task.url, {
|
||||
dispatcher: this.globalAgent,
|
||||
headersTimeout: 15000,
|
||||
headers: { "User-Agent": "Ephemeral-Downloader/2.0" }
|
||||
});
|
||||
|
||||
if (response.statusCode >= 400) {
|
||||
throw new Error(`HTTP Error ${response.statusCode}`);
|
||||
}
|
||||
|
||||
// Update filename from headers if available
|
||||
const disposition = response.headers["content-disposition"];
|
||||
if (typeof disposition === "string") {
|
||||
const match = /filename\*?=(?:UTF-8''|")?([^";]+)/i.exec(disposition);
|
||||
if (match?.[1]) {
|
||||
task.filename = decodeURIComponent(match[1].replace(/"/g, ""));
|
||||
}
|
||||
}
|
||||
|
||||
// Size
|
||||
const len = response.headers["content-length"];
|
||||
if (len) {
|
||||
task.totalBytes = Number(Array.isArray(len) ? len[0] : len);
|
||||
}
|
||||
|
||||
const filePath = join(sessionPath, `${task.id}_${task.filename}`);
|
||||
const fileStream = createWriteStream(filePath);
|
||||
|
||||
let lastUpdate = Date.now();
|
||||
let bytesAtLastUpdate = 0;
|
||||
|
||||
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;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
fileStream.end();
|
||||
task.status = "completed";
|
||||
task.progress = 100;
|
||||
task.speed = 0;
|
||||
sessionManager.touch(task.sessionId); // keep alive after finish
|
||||
|
||||
} catch (err) {
|
||||
task.status = "error";
|
||||
task.error = err instanceof Error ? err.message : "Unknown error";
|
||||
console.error(`[DownloadManager] Download failed: ${task.url}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { existsSync, mkdirSync, rmSync, readdirSync, statSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
const STORAGE_ROOT = resolve(process.cwd(), "server/storage");
|
||||
const SESSION_TIMEOUT_MS = 60 * 60 * 1000; // 1 Hour
|
||||
|
||||
type SessionData = {
|
||||
id: string;
|
||||
lastActive: number;
|
||||
};
|
||||
|
||||
export class SessionManager {
|
||||
private sessions: Map<string, SessionData> = new Map();
|
||||
|
||||
constructor() {
|
||||
// Ensure storage root exists
|
||||
if (!existsSync(STORAGE_ROOT)) {
|
||||
mkdirSync(STORAGE_ROOT, { recursive: true });
|
||||
}
|
||||
|
||||
// Start Garbage Collector
|
||||
setInterval(() => this.cleanup(), 60 * 1000); // Check every minute
|
||||
console.log("[SessionManager] Garbage Collector started.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates a session. Updates lastActive timestamp.
|
||||
*/
|
||||
public getSession(id?: string): SessionData {
|
||||
const now = Date.now();
|
||||
|
||||
if (id && this.sessions.has(id)) {
|
||||
const session = this.sessions.get(id)!;
|
||||
session.lastActive = now;
|
||||
return session;
|
||||
}
|
||||
|
||||
// If ID provided but not in memory, check if folder exists (recovery)
|
||||
if (id && existsSync(join(STORAGE_ROOT, id))) {
|
||||
const session = { id, lastActive: now };
|
||||
this.sessions.set(id, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
// Create new session
|
||||
const newId = randomUUID();
|
||||
const session = { id: newId, lastActive: now };
|
||||
this.sessions.set(newId, session);
|
||||
|
||||
// Create folder
|
||||
const sessionPath = this.getSessionPath(newId);
|
||||
if (!existsSync(sessionPath)) {
|
||||
mkdirSync(sessionPath, { recursive: true });
|
||||
}
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
public getSessionPath(sessionId: string): string {
|
||||
return join(STORAGE_ROOT, sessionId);
|
||||
}
|
||||
|
||||
public getSessionTimeRemaining(sessionId: string): number {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return 0;
|
||||
const expiresAt = session.lastActive + SESSION_TIMEOUT_MS;
|
||||
return Math.max(0, expiresAt - Date.now());
|
||||
}
|
||||
|
||||
public getExpiresAt(sessionId: string): string {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return new Date().toISOString();
|
||||
return new Date(session.lastActive + SESSION_TIMEOUT_MS).toISOString();
|
||||
}
|
||||
|
||||
public touch(sessionId: string) {
|
||||
if (this.sessions.has(sessionId)) {
|
||||
this.sessions.get(sessionId)!.lastActive = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes expired sessions and deletes their files.
|
||||
*/
|
||||
private cleanup() {
|
||||
const now = Date.now();
|
||||
|
||||
// Check in-memory sessions
|
||||
for (const [id, session] of this.sessions.entries()) {
|
||||
if (now - session.lastActive > SESSION_TIMEOUT_MS) {
|
||||
console.log(`[SessionManager] Session ${id} expired. Cleaning up...`);
|
||||
this.destroySession(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Double check orphaned folders (in case server restarted)
|
||||
// accessible folders in storage that are not in memory OR are too old
|
||||
try {
|
||||
const dirs = readdirSync(STORAGE_ROOT);
|
||||
for (const dir of dirs) {
|
||||
if (dir === ".gitignore") continue;
|
||||
|
||||
const dirPath = join(STORAGE_ROOT, dir);
|
||||
const stats = statSync(dirPath);
|
||||
|
||||
// If folder is older than timeout and not in active memory (or in memory but expired)
|
||||
// Note: mtime might update when files are written, so this is a heuristic fallback
|
||||
const isInMemory = this.sessions.has(dir);
|
||||
if (!isInMemory && (now - stats.mtimeMs > SESSION_TIMEOUT_MS)) {
|
||||
console.log(`[SessionManager] Removing orphaned session folder: ${dir}`);
|
||||
rmSync(dirPath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[SessionManager] Error during fallback cleanup", err);
|
||||
}
|
||||
}
|
||||
|
||||
private destroySession(id: string) {
|
||||
this.sessions.delete(id);
|
||||
const path = this.getSessionPath(id);
|
||||
if (existsSync(path)) {
|
||||
try {
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
console.log(`[SessionManager] Deleted storage for ${id}`);
|
||||
} catch (e) {
|
||||
console.error(`[SessionManager] Failed to delete ${path}`, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const sessionManager = new SessionManager();
|
||||
+3
-1
@@ -14,7 +14,9 @@
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"uuid": "^13.0.0",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
|
||||
+70
-209
@@ -1,230 +1,91 @@
|
||||
import { useState } from "react";
|
||||
import { Layout } from "./components/ui/Layout";
|
||||
import "./App.css";
|
||||
import { DownloadForm } from "./components/feature/DownloadForm";
|
||||
import { DownloadItem, type DownloadItemData } from "./components/feature/DownloadItem";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "./components/ui/Card";
|
||||
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";
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? "http://localhost:3000";
|
||||
function DownloadList() {
|
||||
const { tasks, expiresAt } = useSession();
|
||||
|
||||
function App() {
|
||||
const [downloads, setDownloads] = useState<DownloadItemData[]>([]);
|
||||
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} />
|
||||
</div>
|
||||
|
||||
const startDownload = async (itemId: number, url: string, resume = false) => {
|
||||
const existing = downloads.find((item) => item.id === itemId);
|
||||
const alreadyReceived = resume && existing?.receivedBytes
|
||||
? existing.receivedBytes
|
||||
: 0;
|
||||
{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>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{tasks.map((task) => (
|
||||
<DownloadItem key={task.id} item={task} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
setDownloads((current) =>
|
||||
current.map((item) =>
|
||||
item.id === itemId
|
||||
? {
|
||||
...item,
|
||||
status: "downloading",
|
||||
progress: item.progress ?? 0,
|
||||
error: undefined,
|
||||
speedHistory: [], // Reset history on start/resume
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
function Main() {
|
||||
const { queueDownload } = useSession();
|
||||
|
||||
const handleDownload = async (url: string) => {
|
||||
try {
|
||||
const query = new URLSearchParams({
|
||||
url,
|
||||
});
|
||||
if (resume && alreadyReceived > 0) {
|
||||
query.set("offset", String(alreadyReceived));
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${API_URL}/stream?${query.toString()}`,
|
||||
);
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
const message = "Failed to start download.";
|
||||
setDownloads((current) =>
|
||||
current.map((item) =>
|
||||
item.id === itemId
|
||||
? { ...item, status: "error", error: message, progress: null }
|
||||
: item,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const contentLengthHeader =
|
||||
response.headers.get("x-origin-content-length") ??
|
||||
response.headers.get("content-length");
|
||||
|
||||
const totalBytes = contentLengthHeader
|
||||
? Number.parseInt(contentLengthHeader, 10)
|
||||
: 0;
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: BlobPart[] = [];
|
||||
let received = alreadyReceived;
|
||||
const startedAt = performance.now();
|
||||
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
chunks.push(value.buffer as ArrayBuffer);
|
||||
received += value.length;
|
||||
const elapsedSeconds = (performance.now() - startedAt) / 1000;
|
||||
const bytesPerSecond =
|
||||
elapsedSeconds > 0 ? received / elapsedSeconds : 0;
|
||||
const percentage =
|
||||
totalBytes > 0 ? Math.round((received / totalBytes) * 100) : null;
|
||||
|
||||
setDownloads((current) =>
|
||||
current.map((item) => {
|
||||
if (item.id !== itemId) return item;
|
||||
|
||||
const newHistory = [...(item.speedHistory || []), bytesPerSecond];
|
||||
// Keep last 50 data points for the graph
|
||||
if (newHistory.length > 50) newHistory.shift();
|
||||
|
||||
return {
|
||||
...item,
|
||||
progress: percentage,
|
||||
receivedBytes: received,
|
||||
totalBytes: totalBytes || item.totalBytes,
|
||||
speedBytesPerSecond: bytesPerSecond,
|
||||
speedHistory: newHistory,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const contentType =
|
||||
response.headers.get("content-type") ?? "application/octet-stream";
|
||||
const blob = new Blob(chunks, { type: contentType });
|
||||
|
||||
const disposition = response.headers.get("content-disposition");
|
||||
const fallbackName = (() => {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const nameFromPath = parsed.pathname.split("/").filter(Boolean).pop();
|
||||
return nameFromPath ?? "download.bin";
|
||||
} catch {
|
||||
return "download.bin";
|
||||
}
|
||||
})();
|
||||
|
||||
const filename = (() => {
|
||||
if (disposition) {
|
||||
const match =
|
||||
/filename\*?=(?:UTF-8''|")?([^";]+)/i.exec(disposition);
|
||||
if (match?.[1]) {
|
||||
return decodeURIComponent(match[1].replace(/"/g, ""));
|
||||
}
|
||||
}
|
||||
return fallbackName;
|
||||
})();
|
||||
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
|
||||
setDownloads((current) =>
|
||||
current.map((item) =>
|
||||
item.id === itemId
|
||||
? { ...item, status: "completed", progress: 100 }
|
||||
: item,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Unexpected error during download.";
|
||||
setDownloads((current) =>
|
||||
current.map((item) =>
|
||||
item.id === itemId
|
||||
? { ...item, status: "error", error: message, progress: null }
|
||||
: item,
|
||||
),
|
||||
);
|
||||
await queueDownload(url);
|
||||
} catch (error) {
|
||||
console.error("Failed to queue", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNewDownloads = (urls: string[]) => {
|
||||
const baseId = Date.now();
|
||||
const newItems: DownloadItemData[] = urls.map((value, index) => ({
|
||||
id: baseId + index,
|
||||
url: value,
|
||||
status: "pending",
|
||||
progress: 0,
|
||||
speedHistory: [],
|
||||
}));
|
||||
|
||||
setDownloads((current) => [...newItems, ...current]);
|
||||
|
||||
newItems.forEach((item) => {
|
||||
void startDownload(item.id, item.url);
|
||||
});
|
||||
};
|
||||
|
||||
const handleRetry = (id: number, url: string) => {
|
||||
void startDownload(id, url, true);
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="grid gap-8 lg:grid-cols-[400px_1fr]">
|
||||
<div className="space-y-6">
|
||||
<DownloadForm onSubmit={handleNewDownloads} />
|
||||
|
||||
<Card className="border-border/50 bg-card/50 backdrop-blur-sm hidden lg:block">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Tips</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-muted-foreground space-y-2">
|
||||
<p>• Use direct links ending in .iso, .zip, .mp4, etc.</p>
|
||||
<p>• Downloads are streamed directly to your browser memory, then saved.</p>
|
||||
<p>• If the tab closes, the download is lost.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<section className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-2xl font-bold tracking-tight">Active Downloads</h2>
|
||||
<span className="text-sm text-muted-foreground">{downloads.length} items</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{downloads.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12 text-center animate-in fade-in-50">
|
||||
<div className="mb-4 rounded-full bg-secondary/50 p-4">
|
||||
<div className="i-lucide-download size-8 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold">No downloads yet</h3>
|
||||
<p className="mt-2 text-sm text-muted-foreground max-w-sm">
|
||||
Paste your links on the left sidebar to get started. The VPS proxy will handle the connection.
|
||||
<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>
|
||||
) : (
|
||||
downloads.map((item) => (
|
||||
<DownloadItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
onRetry={handleRetry}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
<DownloadForm onDownload={handleDownload} />
|
||||
</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>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Downloads List */}
|
||||
<div className="lg:col-span-8">
|
||||
<DownloadList />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<SessionProvider>
|
||||
<Main />
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -1,75 +1,54 @@
|
||||
import { useState } from "react";
|
||||
import type { FormEvent } from "react";
|
||||
import { Download } from "lucide-react";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Textarea } from "../ui/Textarea";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/Card";
|
||||
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 {
|
||||
onSubmit: (urls: string[]) => void;
|
||||
onDownload: (url: string) => void;
|
||||
}
|
||||
|
||||
export function DownloadForm({ onSubmit }: DownloadFormProps) {
|
||||
const [text, setText] = useState("");
|
||||
export function DownloadForm({ onDownload }: DownloadFormProps) {
|
||||
const [url, setUrl] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = (e: FormEvent) => {
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
const urls = text
|
||||
.split(/\r?\n/)
|
||||
.map((u) => u.trim())
|
||||
.filter(Boolean);
|
||||
const result = formSchema.safeParse({ url });
|
||||
|
||||
if (urls.length === 0) {
|
||||
setError("Please enter at least one URL.");
|
||||
if (!result.success) {
|
||||
setError(result.error.errors[0].message);
|
||||
return;
|
||||
}
|
||||
|
||||
const invalidUrl = urls.find((u) => {
|
||||
try {
|
||||
new URL(u);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (invalidUrl) {
|
||||
setError(`Invalid URL detected: ${invalidUrl}`);
|
||||
return;
|
||||
}
|
||||
|
||||
onSubmit(urls);
|
||||
setText("");
|
||||
onDownload(url);
|
||||
setUrl("");
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border-border/50 bg-card/50 backdrop-blur-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>New Download</CardTitle>
|
||||
<CardDescription>
|
||||
Enter direct links (HTTP/HTTPS) to stream via VPS. One URL per line.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<Textarea
|
||||
placeholder="https://example.com/file.iso"
|
||||
className="min-h-[120px] font-mono text-sm"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
<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-sm text-destructive">{error}</p>}
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" className="w-full sm:w-auto">
|
||||
<Download className="mr-2 size-4" />
|
||||
Start Download
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
</div>
|
||||
<Button type="submit">
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,153 +1,137 @@
|
||||
import {
|
||||
Download,
|
||||
FileCheck,
|
||||
FileWarning,
|
||||
Loader2,
|
||||
Play,
|
||||
Server,
|
||||
HardDrive
|
||||
} from "lucide-react";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Card, CardContent } from "../ui/Card";
|
||||
import { Progress } from "../ui/ProgressBar";
|
||||
import { formatBytes, formatSpeed } from "../../lib/utils";
|
||||
|
||||
export type DownloadStatus = "pending" | "downloading" | "completed" | "error";
|
||||
const API_URL = import.meta.env.VITE_API_URL || "http://localhost:3000";
|
||||
|
||||
export type DownloadStatus = "queued" | "downloading" | "completed" | "error";
|
||||
|
||||
export type DownloadItemData = {
|
||||
id: number;
|
||||
id: string;
|
||||
sessionId: string;
|
||||
url: string;
|
||||
filename: string;
|
||||
status: DownloadStatus;
|
||||
progress: number | null;
|
||||
receivedBytes?: number;
|
||||
totalBytes?: number;
|
||||
speedBytesPerSecond?: number;
|
||||
speedHistory: number[];
|
||||
progress: number;
|
||||
totalBytes: number;
|
||||
receivedBytes: number;
|
||||
speed: number;
|
||||
error?: string;
|
||||
createdAt: number;
|
||||
};
|
||||
|
||||
interface DownloadItemProps {
|
||||
item: DownloadItemData;
|
||||
onRetry: (id: number, url: string) => void;
|
||||
}
|
||||
|
||||
export function DownloadItem({ item, onRetry }: DownloadItemProps) {
|
||||
export function DownloadItem({ item }: DownloadItemProps) {
|
||||
const isCompleted = item.status === "completed";
|
||||
const isError = item.status === "error";
|
||||
const isDownloading = item.status === "downloading";
|
||||
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 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");
|
||||
}
|
||||
};
|
||||
|
||||
download();
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden transition-all hover:bg-muted/50">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 flex-1 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`flex size-8 shrink-0 items-center justify-center rounded-full bg-secondary text-muted-foreground ${isCompleted ? "bg-green-500/10 text-green-500" : ""
|
||||
} ${isError ? "bg-red-500/10 text-red-500" : ""} ${isDownloading ? "bg-primary/10 text-primary" : ""
|
||||
}`}
|
||||
>
|
||||
{isCompleted ? (
|
||||
<FileCheck className="size-4" />
|
||||
) : isError ? (
|
||||
<FileWarning className="size-4" />
|
||||
) : isDownloading ? (
|
||||
<Download className="size-4 animate-bounce" />
|
||||
) : (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
)}
|
||||
<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" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium leading-none">
|
||||
{item.url.split("/").pop() || item.url}
|
||||
</p>
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">
|
||||
{item.url}
|
||||
</p>
|
||||
) : 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>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{item.progress ?? 0}%</span>
|
||||
<span>
|
||||
<span>
|
||||
{item.status === "downloading" &&
|
||||
formatSpeed(item.speedBytesPerSecond)}
|
||||
</span>
|
||||
</span>
|
||||
) : 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>
|
||||
<Progress
|
||||
value={item.progress}
|
||||
className={`h-2 ${isError ? "bg-red-900/20" : ""} ${isCompleted ? "bg-green-900/20" : ""
|
||||
}`}
|
||||
indicatorClassName={`${isError ? "bg-red-500" : ""} ${isCompleted ? "bg-green-500" : ""
|
||||
}`}
|
||||
/>
|
||||
|
||||
{/* Sparkline for speed history */}
|
||||
{item.status === "downloading" && item.speedHistory.length > 1 && (
|
||||
<div className="h-8 w-full overflow-hidden opacity-50">
|
||||
<svg
|
||||
className="h-full w-full"
|
||||
viewBox={`0 0 ${item.speedHistory.length - 1} 100`}
|
||||
preserveAspectRatio="none"
|
||||
>
|
||||
<path
|
||||
d={`M 0,100 ${item.speedHistory
|
||||
.map((s, i) => {
|
||||
const max = Math.max(...item.speedHistory);
|
||||
const y = max > 0 ? 100 - (s / max) * 100 : 100;
|
||||
return `L ${i},${y}`;
|
||||
})
|
||||
.join(" ")} L ${item.speedHistory.length - 1},100 Z`}
|
||||
fill="currentColor"
|
||||
className="text-primary/20"
|
||||
/>
|
||||
<path
|
||||
d={`M 0,${100 - (item.speedHistory[0] / Math.max(...item.speedHistory)) * 100} ${item.speedHistory
|
||||
.map((s, i) => {
|
||||
const max = Math.max(...item.speedHistory);
|
||||
const y = max > 0 ? 100 - (s / max) * 100 : 100;
|
||||
return `L ${i},${y}`;
|
||||
})
|
||||
.join(" ")}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
className="text-primary"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>
|
||||
{formatBytes(item.receivedBytes)} /{" "}
|
||||
{formatBytes(item.totalBytes)}
|
||||
</span>
|
||||
<span className="capitalize">{item.status}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isError && (
|
||||
<div className="rounded-md bg-destructive/10 p-2 text-xs text-destructive">
|
||||
{item.error}
|
||||
) : (
|
||||
<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 flex-col gap-2">
|
||||
<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 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onRetry(item.id, item.url)}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<Play className="size-4" />
|
||||
</Button>
|
||||
<div className="text-sm text-destructive pt-1">
|
||||
{item.error || "Unknown error occurred"}
|
||||
</div>
|
||||
)}
|
||||
{/* Placeholder for pause/cancel in future */}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Clock } from "lucide-react";
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
interface SessionTimerProps {
|
||||
expiresAt: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SessionTimer({ expiresAt, className }: SessionTimerProps) {
|
||||
const [timeLeft, setTimeLeft] = useState<string>("--:--");
|
||||
const [isCritical, setIsCritical] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!expiresAt) return;
|
||||
|
||||
const tick = () => {
|
||||
const now = Date.now();
|
||||
const end = new Date(expiresAt).getTime();
|
||||
const diff = Math.max(0, end - now);
|
||||
|
||||
if (diff <= 0) {
|
||||
setTimeLeft("Expired");
|
||||
setIsCritical(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
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
|
||||
};
|
||||
|
||||
tick(); // Initial call
|
||||
const interval = setInterval(tick, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [expiresAt]);
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const Alert = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & { variant?: "default" | "destructive" }
|
||||
>(({ className, variant = "default", ...props }, ref) => (
|
||||
<div
|
||||
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",
|
||||
variant === "destructive" &&
|
||||
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Alert.displayName = "Alert"
|
||||
|
||||
const AlertTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h5
|
||||
ref={ref}
|
||||
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertTitle.displayName = "AlertTitle"
|
||||
|
||||
const AlertDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("text-sm [&_p]:leading-relaxed", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDescription.displayName = "AlertDescription"
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription }
|
||||
@@ -0,0 +1,133 @@
|
||||
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 || "";
|
||||
|
||||
export function SessionProvider({ children }: { children: React.ReactNode }) {
|
||||
const [sessionId, setSessionId] = useState<string>(() => {
|
||||
return localStorage.getItem("downloader_session_id") || "";
|
||||
});
|
||||
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;
|
||||
|
||||
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 (err) {
|
||||
console.error("Failed to init session", err);
|
||||
}
|
||||
};
|
||||
|
||||
initSession();
|
||||
}, [sessionId]);
|
||||
|
||||
// Poll Tasks
|
||||
const refreshTasks = async () => {
|
||||
if (!sessionId) return;
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/tasks`, {
|
||||
headers: { "x-session-id": sessionId },
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setTasks(data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch tasks", err);
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/queue`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-session-id": sessionId,
|
||||
},
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error("Failed to queue download");
|
||||
|
||||
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 (err) {
|
||||
console.error(err);
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={{ sessionId, tasks, expiresAt, queueDownload, refreshTasks }}>
|
||||
{children}
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSession() {
|
||||
const context = useContext(SessionContext);
|
||||
if (!context) throw new Error("useSession must be used within SessionProvider");
|
||||
return context;
|
||||
}
|
||||
Reference in new issue
Block a user