Tele-v / src /api.ts
oga3oga's picture
Upload 24 files
da1ea85 verified
Raw History Blame Contribute Delete
22 kB
// ─── Centralized API Client ──────────────────────────────────────────────────
import type { FileEntry, Job, VideoInfo, DownloadJob, RemoteEntry, TeleboxEntry, BackblazeEntry } from "./types";
const AUTH_USER = "admin";
const AUTH_PASS = "1234";
const BASIC_AUTH = typeof btoa === "function"
? btoa(`${AUTH_USER}:${AUTH_PASS}`)
: Buffer.from(`${AUTH_USER}:${AUTH_PASS}`).toString("base64");
const originalFetch = globalThis.fetch.bind(globalThis);
const authFetch: typeof fetch = (input, init) => {
const headers = new Headers(init?.headers ?? {});
if (!headers.has("Authorization")) {
headers.set("Authorization", `Basic ${BASIC_AUTH}`);
}
return originalFetch(input, { ...init, headers });
};
globalThis.fetch = authFetch;
export const api = {
async getFiles(): Promise<{ downloaded: FileEntry[]; encoded: FileEntry[]; folders: string[] }> {
const r = await fetch("/api/files");
return r.json();
},
async deleteFile(id: string): Promise<void> {
await fetch(`/api/files/${encodeURIComponent(id)}`, { method: "DELETE" });
},
async batchDelete(ids: string[]): Promise<void> {
await fetch("/api/batch/delete", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids }),
});
},
async batchPixeldrain(ids: string[]): Promise<{ jobIds: string[] }> {
const r = await fetch("/api/batch/pixeldrain", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids }),
});
return r.json();
},
async renameFile(id: string, newName: string): Promise<{ id: string; name: string }> {
const r = await fetch(`/api/files/${encodeURIComponent(id)}/rename`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ newName }),
});
return r.json();
},
async moveFile(id: string, targetFolder: string): Promise<{ ok: boolean; error?: string }> {
const r = await fetch(`/api/files/${encodeURIComponent(id)}/move`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ targetFolder }),
});
return r.json();
},
async batchMove(ids: string[], targetFolder: string): Promise<{ ok: boolean; error?: string; results?: unknown }> {
const r = await fetch(`/api/batch/move`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids, targetFolder }),
});
return r.json();
},
async createFolder(folderName: string): Promise<{ ok: boolean; folder?: string; error?: string }> {
const r = await fetch("/api/folders/create", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ folderName }),
});
return r.json();
},
async renameFolder(oldPath: string, newName: string): Promise<{ ok: boolean; error?: string }> {
const r = await fetch("/api/folders/rename", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ oldPath, newName }),
});
return r.json();
},
async deleteFolder(folderPath: string): Promise<{ ok: boolean; error?: string }> {
const r = await fetch("/api/folders", {
method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ folderPath }),
});
return r.json();
},
async startDownloadUrl(url: string, username?: string, password?: string, useAria2?: boolean): Promise<{ jobId: string }> {
const r = await fetch("/api/download-url", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url, username, password, useAria2: !!useAria2 }),
});
return r.json();
},
async getDownloadJob(id: string): Promise<{ job: DownloadJob }> {
const r = await fetch(`/api/download-jobs/${id}`);
return r.json();
},
async stopDownloadJob(id: string): Promise<void> {
await fetch(`/api/download-jobs/${id}/stop`, { method: "POST" });
},
async startEncode(settings: Record<string, unknown>): Promise<Job> {
const r = await fetch("/api/encode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings),
});
const data = await r.json();
if (!r.ok || data.error) {
throw new Error(data.error || "Failed to start encode");
}
return data.job;
},
async stopJob(id: string): Promise<void> {
await fetch(`/api/jobs/${id}/stop`, { method: "POST" });
},
async getFileInfo(id: string): Promise<{ ok: boolean; info: VideoInfo }> {
const r = await fetch(`/api/files/${encodeURIComponent(id)}/info`);
return r.json();
},
async trimFile(fileId: string, startTime: number, endTime: number, outputFilename: string): Promise<Job> {
const r = await fetch("/api/trim", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileId, startTime, endTime, outputFilename }),
});
const data = await r.json();
return data.job;
},
async trimSegments(fileId: string, segments: { startTime: number; endTime: number }[], outputFilename: string): Promise<Job> {
const r = await fetch("/api/trim", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileId, segments, outputFilename }),
});
const data = await r.json();
return data.job;
},
async getJobs(): Promise<Job[]> {
const r = await fetch("/api/jobs");
const data = await r.json();
return data.jobs;
},
async clearFinishedJobs(): Promise<void> {
await fetch("/api/jobs/finished", { method: "DELETE" });
},
async getJob(id: string): Promise<Job> {
const r = await fetch(`/api/jobs/${id}`);
const data = await r.json();
return data.job;
},
async uploadToPixeldrain(id: string): Promise<{ jobId: string }> {
const r = await fetch(`/api/files/${encodeURIComponent(id)}/pixeldrain`, { method: "POST" });
return r.json();
},
async uploadFileToRemote(id: string, serverUrl: string, hfCreds?: { accessKeyId?: string; secretAccessKey?: string }): Promise<{ ok: boolean; error?: string }> {
const r = await fetch(`/api/files/${encodeURIComponent(id)}/remote-upload`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ serverUrl, hfAccessKeyId: hfCreds?.accessKeyId, hfSecretAccessKey: hfCreds?.secretAccessKey }),
});
return r.json();
},
async unzipFile(id: string): Promise<{ ok: boolean; outputFolder?: string; fileCount?: number; error?: string }> {
const r = await fetch(`/api/files/${encodeURIComponent(id)}/unzip`, { method: "POST" });
return r.json();
},
async batchZip(ids: string[]): Promise<{ ok: boolean; filename?: string; fileCount?: number; error?: string }> {
const r = await fetch("/api/batch/zip", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileIds: ids }),
});
return r.json();
},
async remoteList(url: string, hfToken?: string): Promise<{ ok: boolean; entries: RemoteEntry[]; error?: string }> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 8000);
try {
const params = new URLSearchParams({ url });
if (hfToken) params.append("hfToken", hfToken);
const r = await fetch(`/api/remote/list?${params.toString()}`, {
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!r.ok) {
const text = await r.text().catch(() => "");
return { ok: false, entries: [], error: `Server returned ${r.status}: ${text.slice(0, 200)}` };
}
return r.json();
} catch (err) {
clearTimeout(timeoutId);
if (err instanceof Error && err.name === "AbortError") {
return { ok: false, entries: [], error: "Connection timed out (8s). Check that the remote server is running and accessible." };
}
return { ok: false, entries: [], error: err instanceof Error ? err.message : "Failed to fetch" };
}
},
async remoteDownload(
serverUrl: string,
remoteName: string,
targetFolder?: string,
directUrl?: string,
hfMeta?: { hfPath?: string; hfOrg?: string; hfBucket?: string },
hfToken?: string
): Promise<{ ok: boolean; jobId?: string; error?: string }> {
const r = await fetch("/api/remote/download", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({
serverUrl,
remoteName,
filename: remoteName,
targetFolder,
url: directUrl,
hfPath: hfMeta?.hfPath,
hfOrg: hfMeta?.hfOrg,
hfBucket: hfMeta?.hfBucket,
hfToken,
}),
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async remoteDownloadFolder(
serverUrl: string,
folderName: string,
targetFolder?: string,
hfToken?: string
): Promise<{ ok: boolean; jobIds?: string[]; count?: number; error?: string }> {
const r = await fetch("/api/remote/download-folder", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ serverUrl, folderName, targetFolder, hfToken }),
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async teleboxList(token: string, pid: number): Promise<{ ok: boolean; entries?: TeleboxEntry[]; pid?: number; error?: string }> {
const q = new URLSearchParams({ token, pid: String(pid) });
const r = await fetch(`/api/telebox/list?${q.toString()}`);
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async teleboxCreateFolder(token: string, pid: number, name: string): Promise<{ ok: boolean; dirId?: number; error?: string }> {
const r = await fetch("/api/telebox/folder-create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, pid, name }),
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async teleboxDownload(webToken: string, itemId: string, filename: string, targetFolder?: string): Promise<{ ok: boolean; jobId?: string; error?: string }> {
const r = await fetch("/api/telebox/download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ webToken, itemId, filename, targetFolder }),
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async teleboxUpload(token: string, pid: number, files: FileList | File[]): Promise<{ ok: boolean; results?: unknown[]; error?: string }> {
const form = new FormData();
form.append("token", token);
form.append("pid", String(pid));
Array.from(files).forEach((file) => form.append("files", file));
const r = await fetch("/api/telebox/upload", {
method: "POST",
body: form,
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async remoteRename(serverUrl: string, oldName: string, newName: string, hfCreds?: { accessKeyId?: string; secretAccessKey?: string; hfToken?: string }): Promise<{ ok: boolean; error?: string }> {
const body: Record<string, string> = { serverUrl, oldName, newName };
if (hfCreds?.accessKeyId) body.hfAccessKeyId = hfCreds.accessKeyId;
if (hfCreds?.secretAccessKey) body.hfSecretAccessKey = hfCreds.secretAccessKey;
if (hfCreds?.hfToken) body.hfToken = hfCreds.hfToken;
const r = await fetch("/api/remote/rename", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return r.json();
},
async remoteDelete(serverUrl: string, name: string, hfCreds?: { accessKeyId?: string; secretAccessKey?: string }): Promise<{ ok: boolean; error?: string }> {
const body: Record<string, string> = { serverUrl, name };
if (hfCreds?.accessKeyId) body.hfAccessKeyId = hfCreds.accessKeyId;
if (hfCreds?.secretAccessKey) body.hfSecretAccessKey = hfCreds.secretAccessKey;
const r = await fetch("/api/remote/delete", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return r.json();
},
async remoteMove(serverUrl: string, name: string, targetFolder: string, hfCreds?: { accessKeyId?: string; secretAccessKey?: string; hfToken?: string }): Promise<{ ok: boolean; error?: string }> {
const body: Record<string, string> = { serverUrl, name, targetFolder };
if (hfCreds?.accessKeyId) body.hfAccessKeyId = hfCreds.accessKeyId;
if (hfCreds?.secretAccessKey) body.hfSecretAccessKey = hfCreds.secretAccessKey;
if (hfCreds?.hfToken) body.hfToken = hfCreds.hfToken;
const r = await fetch("/api/remote/move", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return r.json();
},
async remoteUpload(serverUrl: string, file: File, hfCreds?: { accessKeyId?: string; secretAccessKey?: string }): Promise<{ ok: boolean; error?: string }> {
const fd = new FormData();
fd.append("file", file);
fd.append("serverUrl", serverUrl);
if (hfCreds?.accessKeyId) fd.append("hfAccessKeyId", hfCreds.accessKeyId);
if (hfCreds?.secretAccessKey) fd.append("hfSecretAccessKey", hfCreds.secretAccessKey);
const r = await fetch("/api/remote/upload", { method: "POST", body: fd });
return r.json();
},
async getRemoteDownloadJob(id: string): Promise<{ job: DownloadJob }> {
const r = await fetch(`/api/remote/download-jobs/${id}`);
return r.json();
},
async stopRemoteDownloadJob(id: string): Promise<void> {
await fetch(`/api/remote/download-jobs/${id}/stop`, { method: "POST" });
},
async uploadFiles(files: File[], targetFolder?: string): Promise<{ ok: boolean; uploaded?: Array<{ name: string; relPath: string; folder: string }>; error?: string }> {
const formData = new FormData();
for (const file of files) formData.append("files", file);
if (targetFolder) formData.append("folderPath", targetFolder);
const r = await fetch("/api/files/upload", {
method: "POST",
body: formData,
});
return r.json();
},
// ── Backblaze B2 (S3-compatible) ──────────────────────────────────────────────
async backblazeList(
bucketId: string,
endpointUrl: string,
keyId: string,
appKey: string,
prefix?: string
): Promise<{ ok: boolean; entries: BackblazeEntry[]; error?: string }> {
const q = new URLSearchParams({ bucketId, endpointUrl, keyId, appKey });
if (prefix) q.set("prefix", prefix);
const r = await fetch(`/api/backblaze/list?${q.toString()}`);
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, entries: [], error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async backblazeDownload(
bucketId: string,
endpointUrl: string,
keyId: string,
appKey: string,
objectKey: string,
targetFolder?: string
): Promise<{ ok: boolean; jobId?: string; error?: string }> {
const r = await fetch("/api/backblaze/download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ bucketId, endpointUrl, keyId, appKey, objectKey, targetFolder }),
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
// ── Generic S3-compatible storage (Qencode media storage, Backblaze B2, or any
// other S3-compatible bucket). `host` is the PATH-STYLE S3 management API host
// for the provider (e.g. "us-west.s3.qencode.com" or "s3.us-east-005.backblazeb2.com")
// β€” NOT a virtual-hosted CDN/playback host (Qencode's is a different host entirely,
// used only by s3SignedUrl below for playback links). ──────────────────────────
async s3List(
bucketName: string,
accessKeyId: string,
secretAccessKey: string,
region: string,
host: string,
prefix?: string
): Promise<{ ok: boolean; entries: BackblazeEntry[]; error?: string }> {
const q = new URLSearchParams({ bucketName, accessKeyId, secretAccessKey, region, host });
if (prefix) q.set("prefix", prefix);
const r = await fetch(`/api/s3/list?${q.toString()}`);
const data = await r.json().catch(() => ({}));
if (!r.ok) return { ok: false, entries: [], error: data.error || `Server returned ${r.status}` };
return data;
},
async s3Upload(
bucketName: string,
accessKeyId: string,
secretAccessKey: string,
region: string,
host: string,
file: File,
prefix?: string
): Promise<{ ok: boolean; error?: string }> {
const fd = new FormData();
fd.append("file", file);
fd.append("bucketName", bucketName);
fd.append("accessKeyId", accessKeyId);
fd.append("secretAccessKey", secretAccessKey);
fd.append("region", region);
fd.append("host", host);
if (prefix) fd.append("prefix", prefix);
const r = await fetch("/api/s3/upload", { method: "POST", body: fd });
return r.json();
},
async s3Presign(
bucketName: string,
accessKeyId: string,
secretAccessKey: string,
region: string,
host: string,
objectKey: string,
expiresInSeconds?: number
): Promise<{ ok: boolean; url?: string; error?: string }> {
const r = await fetch("/api/s3/presign", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ bucketName, accessKeyId, secretAccessKey, region, host, objectKey, expiresInSeconds }),
});
return r.json();
},
async s3Download(
bucketName: string,
accessKeyId: string,
secretAccessKey: string,
region: string,
host: string,
objectKey: string,
targetFolder?: string,
cfProxyUrl?: string
): Promise<{ ok: boolean; jobId?: string; error?: string }> {
const r = await fetch("/api/s3/download", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ bucketName, accessKeyId, secretAccessKey, region, host, objectKey, targetFolder, cfProxyUrl }),
});
return r.json();
},
async s3Delete(
bucketName: string,
accessKeyId: string,
secretAccessKey: string,
region: string,
host: string,
objectKey: string
): Promise<{ ok: boolean; error?: string }> {
const r = await fetch("/api/s3/delete", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ bucketName, accessKeyId, secretAccessKey, region, host, objectKey }),
});
return r.json();
},
async s3SignedUrl(
endpointUrl: string,
objectKey: string,
expiresInSeconds?: number
): Promise<{ ok: boolean; url?: string; error?: string }> {
const r = await fetch("/api/s3/signed-url", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ endpointUrl, objectKey, expiresInSeconds }),
});
return r.json();
},
/** Upload a local server-side file (by encode job ID or file ID) directly to S3. */
async getSettings(): Promise<Record<string, unknown>> {
const r = await fetch("/api/settings");
return r.json();
},
async saveSettings(data: Record<string, unknown>): Promise<void> {
await fetch("/api/settings", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
},
async s3UploadLocal(
jobId: string | null,
fileId: string | null,
bucketName: string,
accessKeyId: string,
secretAccessKey: string,
region: string,
host: string,
prefix?: string
): Promise<{ ok: boolean; filename?: string; error?: string }> {
const r = await fetch("/api/s3/upload-local", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jobId, fileId, bucketName, accessKeyId, secretAccessKey, region, host, prefix }),
});
return r.json();
},
// ── HuggingFace Folder Sync ────────────────────────────────────────────────
async syncFolderToRemote(localPath: string, bucketUrl: string, hfToken?: string): Promise<{ ok: boolean; jobId?: string; error?: string }> {
const r = await fetch("/api/remote/sync-folder", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ localPath, bucketUrl, hfToken }),
});
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
async getSyncStatus(jobId: string): Promise<{ ok: boolean; job?: any; error?: string }> {
const r = await fetch(`/api/remote/sync-status/${encodeURIComponent(jobId)}`);
if (!r.ok) {
const data = await r.json().catch(() => ({}));
return { ok: false, error: data.error || `Server returned ${r.status}` };
}
return r.json();
},
};