775 lines
28 KiB
TypeScript
775 lines
28 KiB
TypeScript
// ── Types ────────────────────────────────────────────
|
|
|
|
interface Job {
|
|
id: string;
|
|
video_path: string;
|
|
video_filename: string;
|
|
status: 'pending' | 'queued' | 'processing' | 'paused' | 'completed' | 'failed' | 'cancelled';
|
|
config: string;
|
|
progress: number;
|
|
current_index: number;
|
|
total_units: number;
|
|
segments: string;
|
|
last_context: string;
|
|
current_time_position: number;
|
|
error: string | null;
|
|
created_at: string;
|
|
updated_at: string;
|
|
completed_at: string | null;
|
|
output_audio: string | null;
|
|
output_subtitles_srt: string | null;
|
|
output_subtitles_vtt: string | null;
|
|
output_muxed: string | null;
|
|
output_options: string;
|
|
}
|
|
|
|
interface AudioSegment {
|
|
audioFile: string;
|
|
startTime: number;
|
|
duration: number;
|
|
description: string;
|
|
}
|
|
|
|
interface ProgressData {
|
|
id: string;
|
|
status: string;
|
|
progress: number;
|
|
currentIndex: number;
|
|
totalUnits: number;
|
|
segments: AudioSegment[];
|
|
error: string | null;
|
|
output_audio: string | null;
|
|
output_subtitles_srt: string | null;
|
|
output_subtitles_vtt: string | null;
|
|
output_muxed: string | null;
|
|
}
|
|
|
|
interface FileInfo {
|
|
filename: string;
|
|
filePath: string;
|
|
size: number;
|
|
}
|
|
|
|
// ── State ────────────────────────────────────────────
|
|
|
|
let authToken: string | null = sessionStorage.getItem('authToken');
|
|
let selectedFilePath: string | null = null;
|
|
const sseMap = new Map<string, EventSource>();
|
|
let pollTimer: number | null = null;
|
|
|
|
// ── DOM helpers ───────────────────────────────────────
|
|
|
|
const $$ = (sel: string): NodeListOf<HTMLElement> => document.querySelectorAll(sel);
|
|
const el = (id: string): HTMLElement => {
|
|
const e = document.getElementById(id);
|
|
if (!e) throw new Error(`Missing element #${id}`);
|
|
return e;
|
|
};
|
|
|
|
// ── API ───────────────────────────────────────────────
|
|
|
|
function apiHeaders(): Record<string, string> {
|
|
const h: Record<string, string> = { 'Content-Type': 'application/json' };
|
|
if (authToken) h['Authorization'] = `Basic ${authToken}`;
|
|
return h;
|
|
}
|
|
|
|
async function api(method: string, url: string, body?: unknown): Promise<Response> {
|
|
const res = await fetch(url, {
|
|
method,
|
|
headers: apiHeaders(),
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
if (res.status === 401) {
|
|
sessionStorage.removeItem('authToken');
|
|
authToken = null;
|
|
showLoginScreen();
|
|
throw new Error('Unauthorized');
|
|
}
|
|
return res;
|
|
}
|
|
|
|
async function apiJson<T>(method: string, url: string, body?: unknown): Promise<T> {
|
|
const res = await api(method, url, body);
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.error || 'Request failed');
|
|
return data as T;
|
|
}
|
|
|
|
// ── Screen switching ──────────────────────────────────
|
|
|
|
function showLoginScreen(): void {
|
|
el('login-screen').hidden = false;
|
|
el('main-screen').hidden = true;
|
|
}
|
|
|
|
function showMainScreen(): void {
|
|
el('login-screen').hidden = true;
|
|
el('main-screen').hidden = false;
|
|
}
|
|
|
|
// ── Tablist (WAI-ARIA) ────────────────────────────────
|
|
|
|
function activateTab(tablistId: string, tabId: string): void {
|
|
const tablist = el(tablistId);
|
|
const tabs = Array.from(tablist.querySelectorAll<HTMLElement>('[role="tab"]'));
|
|
tabs.forEach(t => {
|
|
const selected = t.id === tabId;
|
|
t.setAttribute('aria-selected', selected ? 'true' : 'false');
|
|
t.setAttribute('tabindex', selected ? '0' : '-1');
|
|
t.classList.toggle('active', selected);
|
|
|
|
const panelId = t.getAttribute('aria-controls');
|
|
if (!panelId) return;
|
|
const panel = document.getElementById(panelId);
|
|
if (panel) panel.hidden = !selected;
|
|
});
|
|
|
|
const tab = tabs.find(t => t.id === tabId);
|
|
const tabName = tab?.getAttribute('aria-controls') || '';
|
|
onTabActivated(tablistId, tabName);
|
|
}
|
|
|
|
function onTabActivated(tablistId: string, panelId: string): void {
|
|
if (tablistId !== 'main-tablist') return;
|
|
if (panelId === 'dashboard') loadJobs();
|
|
if (panelId === 'files') loadFilesList();
|
|
}
|
|
|
|
function wireTablist(tablistId: string): void {
|
|
const tablist = el(tablistId);
|
|
const tabs = Array.from(tablist.querySelectorAll<HTMLElement>('[role="tab"]'));
|
|
|
|
tabs.forEach(tab => {
|
|
tab.addEventListener('click', () => activateTab(tablistId, tab.id));
|
|
});
|
|
|
|
tablist.addEventListener('keydown', (e) => {
|
|
const ke = e as KeyboardEvent;
|
|
const current = document.activeElement as HTMLElement | null;
|
|
if (!current || !tabs.includes(current)) return;
|
|
let next: HTMLElement | undefined;
|
|
const idx = tabs.indexOf(current);
|
|
if (ke.key === 'ArrowRight') next = tabs[(idx + 1) % tabs.length];
|
|
else if (ke.key === 'ArrowLeft') next = tabs[(idx - 1 + tabs.length) % tabs.length];
|
|
else if (ke.key === 'Home') next = tabs[0];
|
|
else if (ke.key === 'End') next = tabs[tabs.length - 1];
|
|
if (next) {
|
|
ke.preventDefault();
|
|
activateTab(tablistId, next.id);
|
|
next.focus();
|
|
}
|
|
});
|
|
}
|
|
|
|
// ── Login ─────────────────────────────────────────────
|
|
|
|
(el('login-form') as HTMLFormElement).addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const username = (el('login-username') as HTMLInputElement).value;
|
|
const password = (el('login-password') as HTMLInputElement).value;
|
|
const errorEl = el('login-error');
|
|
try {
|
|
const res = await fetch('/api/auth/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password }),
|
|
});
|
|
const data = await res.json();
|
|
if (data.authenticated) {
|
|
authToken = data.token;
|
|
if (authToken) sessionStorage.setItem('authToken', authToken);
|
|
errorEl.hidden = true;
|
|
showMainScreen();
|
|
initApp();
|
|
} else {
|
|
errorEl.textContent = data.error || 'Login failed';
|
|
errorEl.hidden = false;
|
|
}
|
|
} catch {
|
|
errorEl.textContent = 'Connection failed';
|
|
errorEl.hidden = false;
|
|
}
|
|
});
|
|
|
|
el('logout-btn').addEventListener('click', () => {
|
|
sessionStorage.removeItem('authToken');
|
|
authToken = null;
|
|
sseMap.forEach(s => s.close());
|
|
sseMap.clear();
|
|
if (pollTimer) clearInterval(pollTimer);
|
|
showLoginScreen();
|
|
});
|
|
|
|
// ── Utils ─────────────────────────────────────────────
|
|
|
|
function escapeHtml(str: string | null | undefined): string {
|
|
if (!str) return '';
|
|
return String(str)
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"');
|
|
}
|
|
|
|
function formatSize(bytes: number): string {
|
|
if (!bytes) return '0 B';
|
|
const units = ['B', 'KB', 'MB', 'GB'];
|
|
let i = 0;
|
|
let size = bytes;
|
|
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
|
|
return `${size.toFixed(1)} ${units[i]}`;
|
|
}
|
|
|
|
// ── Browse files (for New Job) ────────────────────────
|
|
|
|
async function loadBrowseFiles(): Promise<void> {
|
|
try {
|
|
const data = await apiJson<{ files: FileInfo[] }>('GET', '/api/files');
|
|
const sel = el('video-select') as HTMLSelectElement;
|
|
sel.innerHTML = '<option value="">-- Select file --</option>';
|
|
data.files.forEach(f => {
|
|
const opt = document.createElement('option');
|
|
opt.value = f.filePath;
|
|
opt.textContent = `${f.filename} (${formatSize(f.size)})`;
|
|
sel.appendChild(opt);
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
el('refresh-files').addEventListener('click', loadBrowseFiles);
|
|
|
|
(el('video-select') as HTMLSelectElement).addEventListener('change', function () {
|
|
if (this.value) selectedFilePath = this.value;
|
|
});
|
|
|
|
// ── File upload ───────────────────────────────────────
|
|
|
|
const videoUpload = el('video-upload') as HTMLInputElement;
|
|
const uploadName = el('upload-name');
|
|
|
|
videoUpload.addEventListener('change', function () {
|
|
if (this.files?.length) {
|
|
selectedFilePath = null;
|
|
uploadName.textContent = `Selected: ${this.files[0].name} (${formatSize(this.files[0].size)})`;
|
|
} else {
|
|
uploadName.textContent = '';
|
|
}
|
|
});
|
|
|
|
// ── YouTube download (SSE) ────────────────────────────
|
|
|
|
let youtubeStream: EventSource | null = null;
|
|
|
|
el('download-url').addEventListener('click', () => {
|
|
const url = (el('youtube-url') as HTMLInputElement).value.trim();
|
|
if (!url) return;
|
|
if (!authToken) return;
|
|
|
|
const status = el('download-status');
|
|
const progressWrap = document.querySelector<HTMLElement>('.download-progress');
|
|
const progressbar = el('download-progressbar');
|
|
const fill = el('download-fill');
|
|
|
|
status.textContent = 'Starting download...';
|
|
status.className = 'status';
|
|
if (progressWrap) progressWrap.hidden = false;
|
|
progressbar.setAttribute('aria-valuenow', '0');
|
|
fill.style.width = '0%';
|
|
|
|
if (youtubeStream) youtubeStream.close();
|
|
|
|
const streamUrl = `/api/files/youtube/stream?url=${encodeURIComponent(url)}&token=${encodeURIComponent(authToken)}`;
|
|
const es = new EventSource(streamUrl);
|
|
youtubeStream = es;
|
|
|
|
es.onmessage = (event) => {
|
|
let data: { type: string; percent?: number; filePath?: string; filename?: string; title?: string; message?: string };
|
|
try { data = JSON.parse(event.data); } catch { return; }
|
|
|
|
if (data.type === 'progress' && typeof data.percent === 'number') {
|
|
const pct = Math.max(0, Math.min(100, data.percent));
|
|
progressbar.setAttribute('aria-valuenow', String(Math.round(pct)));
|
|
fill.style.width = `${pct}%`;
|
|
status.textContent = `Downloading ${pct.toFixed(1)}%`;
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'done' && data.filePath && data.filename) {
|
|
progressbar.setAttribute('aria-valuenow', '100');
|
|
fill.style.width = '100%';
|
|
status.textContent = `Downloaded: ${data.filename}`;
|
|
status.className = 'status success';
|
|
selectedFilePath = data.filePath;
|
|
|
|
const sel = el('video-select') as HTMLSelectElement;
|
|
const opt = document.createElement('option');
|
|
opt.value = data.filePath;
|
|
opt.textContent = data.filename;
|
|
opt.selected = true;
|
|
sel.appendChild(opt);
|
|
|
|
es.close();
|
|
youtubeStream = null;
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'error') {
|
|
status.textContent = `Error: ${data.message || 'Download failed'}`;
|
|
status.className = 'status error';
|
|
if (progressWrap) progressWrap.hidden = true;
|
|
es.close();
|
|
youtubeStream = null;
|
|
}
|
|
};
|
|
|
|
es.onerror = () => {
|
|
if (es.readyState === EventSource.CLOSED) return;
|
|
status.textContent = 'Connection lost';
|
|
status.className = 'status error';
|
|
es.close();
|
|
youtubeStream = null;
|
|
};
|
|
});
|
|
|
|
// ── New Job form ──────────────────────────────────────
|
|
|
|
(el('new-job-form') as HTMLFormElement).addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
if (!selectedFilePath) {
|
|
if (videoUpload.files?.length) {
|
|
const formData = new FormData();
|
|
formData.append('video', videoUpload.files[0]);
|
|
try {
|
|
const headers: Record<string, string> = {};
|
|
if (authToken) headers['Authorization'] = `Basic ${authToken}`;
|
|
const res = await fetch('/api/files/upload', { method: 'POST', headers, body: formData });
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.error || 'Upload failed');
|
|
selectedFilePath = data.filePath;
|
|
} catch (err: any) {
|
|
alert('Upload error: ' + err.message);
|
|
return;
|
|
}
|
|
} else {
|
|
alert('Please select a video file or source');
|
|
return;
|
|
}
|
|
}
|
|
|
|
const fd = new FormData(e.target as HTMLFormElement);
|
|
const config: Record<string, unknown> = {};
|
|
for (const [key, val] of fd.entries()) {
|
|
if (key === '') continue;
|
|
if (val === 'on') config[key] = true;
|
|
else if (val === 'off') config[key] = false;
|
|
else if (!isNaN(val as any) && val !== '') config[key] = parseFloat(val as string);
|
|
else config[key] = val;
|
|
}
|
|
// Empty strings would clobber server-side defaults during the spread-merge in
|
|
// JobManager.createJob — drop them. (The server also filters defensively.)
|
|
for (const k of Object.keys(config)) {
|
|
const v = config[k];
|
|
if (v === '' || v === undefined || v === null) delete config[k];
|
|
}
|
|
|
|
const outputOptions = {
|
|
audio: fd.get('output-audio') === 'on',
|
|
subtitles: fd.get('output-subtitles') === 'on',
|
|
muxed: fd.get('output-muxed') === 'on',
|
|
};
|
|
|
|
if (config.visionProvider) {
|
|
const vp: Record<string, unknown> = {};
|
|
vp[config.visionProvider as string] = {
|
|
model: config.visionModel || 'gpt-4o',
|
|
maxTokens: config.visionMaxTokens ? parseInt(config.visionMaxTokens as string) : 300,
|
|
};
|
|
config.visionProviders = vp;
|
|
}
|
|
if (config.ttsProvider) {
|
|
const tp: Record<string, unknown> = {};
|
|
tp[config.ttsProvider as string] = {
|
|
model: config.ttsModel || 'tts-1',
|
|
voice: config.ttsVoice || 'alloy',
|
|
};
|
|
config.ttsProviders = tp;
|
|
}
|
|
|
|
delete config.visionModel;
|
|
delete config.visionMaxTokens;
|
|
delete config.ttsModel;
|
|
delete config['output-audio'];
|
|
delete config['output-subtitles'];
|
|
delete config['output-muxed'];
|
|
|
|
try {
|
|
const data = await apiJson<{ job: Job }>('POST', '/api/jobs', {
|
|
videoPath: selectedFilePath,
|
|
config,
|
|
outputOptions,
|
|
});
|
|
await apiJson('POST', `/api/jobs/${data.job.id}/start`);
|
|
selectedFilePath = null;
|
|
videoUpload.value = '';
|
|
uploadName.textContent = '';
|
|
(el('new-job-form') as HTMLFormElement).reset();
|
|
activateTab('main-tablist', 'tab-dashboard');
|
|
} catch (err: any) {
|
|
alert('Error creating job: ' + err.message);
|
|
}
|
|
});
|
|
|
|
// ── Job list & rendering ──────────────────────────────
|
|
|
|
async function loadJobs(): Promise<void> {
|
|
const container = el('jobs-list');
|
|
container.setAttribute('aria-busy', 'true');
|
|
try {
|
|
const data = await apiJson<{ jobs: Job[] }>('GET', '/api/jobs');
|
|
renderJobs(data.jobs);
|
|
data.jobs.forEach(j => {
|
|
if (j.status === 'processing' || j.status === 'queued') {
|
|
connectSSE(j.id);
|
|
}
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
} finally {
|
|
container.setAttribute('aria-busy', 'false');
|
|
}
|
|
}
|
|
|
|
function renderJobs(jobs: Job[]): void {
|
|
const container = el('jobs-list');
|
|
if (!jobs.length) {
|
|
container.innerHTML = '<p class="empty">No jobs yet. Create one from the “New Job” tab.</p>';
|
|
return;
|
|
}
|
|
|
|
container.innerHTML = jobs.map(j => {
|
|
const segs: AudioSegment[] = JSON.parse(j.segments || '[]');
|
|
const progressClass = j.status === 'completed' ? 'completed' : j.status === 'failed' ? 'failed' : '';
|
|
const downloads: string[] = [];
|
|
|
|
if (j.status === 'completed') {
|
|
// Plain <a download> navigations don't send our Authorization header.
|
|
// Pass the token via query string — middleware/auth.ts accepts ?token=.
|
|
const tok = authToken ? `token=${encodeURIComponent(authToken)}` : '';
|
|
const sep = (qs: string) => qs.includes('?') ? '&' : '?';
|
|
const url = (path: string) => tok ? `${path}${sep(path)}${tok}` : path;
|
|
if (j.output_audio) downloads.push(`<a href="${url(`/api/jobs/${j.id}/download/audio`)}" download>Audio</a>`);
|
|
if (j.output_subtitles_srt) downloads.push(`<a href="${url(`/api/jobs/${j.id}/download/subtitles?format=srt`)}" download>SRT</a>`);
|
|
if (j.output_subtitles_vtt) downloads.push(`<a href="${url(`/api/jobs/${j.id}/download/subtitles?format=vtt`)}" download>VTT</a>`);
|
|
if (j.output_muxed) downloads.push(`<a href="${url(`/api/jobs/${j.id}/download/muxed`)}" download>Muxed</a>`);
|
|
}
|
|
|
|
let actions = '';
|
|
if (j.status === 'pending' || j.status === 'queued') {
|
|
actions += `<button type="button" class="act-start" data-id="${j.id}">Start</button>`;
|
|
}
|
|
if (j.status === 'processing') {
|
|
actions += `<button type="button" class="act-pause" data-id="${j.id}">Pause</button>`;
|
|
}
|
|
if (j.status === 'failed' || j.status === 'paused' || j.status === 'cancelled') {
|
|
actions += `<button type="button" class="act-restart" data-id="${j.id}">Restart</button>`;
|
|
}
|
|
if (j.status !== 'processing') {
|
|
actions += `<button type="button" class="act-delete danger" data-id="${j.id}">Delete</button>`;
|
|
}
|
|
|
|
const pct = Math.round(j.progress);
|
|
return `
|
|
<article class="job-card" data-id="${j.id}" aria-labelledby="job-${j.id}-title">
|
|
<div class="job-card-header">
|
|
<h3 id="job-${j.id}-title">${escapeHtml(j.video_filename)}</h3>
|
|
<div class="job-actions">${actions}</div>
|
|
</div>
|
|
<span class="status-badge status-${j.status}">${j.status}</span>
|
|
<div role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${pct}" aria-label="Job progress" class="progress-bar">
|
|
<div class="progress-fill ${progressClass}" style="width:${pct}%"></div>
|
|
</div>
|
|
<div class="job-meta">
|
|
<span>${pct}%</span>
|
|
<span>Idx: ${j.current_index}/${j.total_units}</span>
|
|
<span>${new Date(j.created_at).toLocaleString()}</span>
|
|
</div>
|
|
${j.error ? `<div class="error-msg" role="alert">${escapeHtml(j.error)}</div>` : ''}
|
|
${downloads.length ? `<div class="download-links">${downloads.join('')}</div>` : ''}
|
|
<button type="button" class="toggle-detail" data-id="${j.id}" aria-expanded="false" aria-controls="job-${j.id}-detail">${segs.length} segments</button>
|
|
<div class="job-detail" id="job-${j.id}-detail" data-id="${j.id}" hidden>
|
|
<div class="segment-log">${segs.map(s => `<div class="segment-entry"><span class="segment-time">[${s.startTime.toFixed(1)}s]</span> ${escapeHtml(s.description)}</div>`).join('')}</div>
|
|
</div>
|
|
</article>`;
|
|
}).join('');
|
|
|
|
container.querySelectorAll<HTMLElement>('.act-start').forEach(b =>
|
|
b.addEventListener('click', () => handleJobAction(b.dataset.id || '', 'start')));
|
|
container.querySelectorAll<HTMLElement>('.act-pause').forEach(b =>
|
|
b.addEventListener('click', () => handleJobAction(b.dataset.id || '', 'pause')));
|
|
container.querySelectorAll<HTMLElement>('.act-restart').forEach(b =>
|
|
b.addEventListener('click', () => handleJobAction(b.dataset.id || '', 'restart')));
|
|
container.querySelectorAll<HTMLElement>('.act-delete').forEach(b =>
|
|
b.addEventListener('click', () => handleJobAction(b.dataset.id || '', 'delete')));
|
|
container.querySelectorAll<HTMLElement>('.toggle-detail').forEach(b => {
|
|
b.addEventListener('click', () => {
|
|
const jobId = b.dataset.id || '';
|
|
const detail = container.querySelector<HTMLElement>(`.job-detail[data-id="${jobId}"]`);
|
|
if (!detail) return;
|
|
const willOpen = detail.hidden;
|
|
detail.hidden = !willOpen;
|
|
b.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
|
|
const job = jobs.find(j => j.id === jobId);
|
|
const segs: AudioSegment[] = job ? JSON.parse(job.segments || '[]') : [];
|
|
b.textContent = willOpen ? 'Hide segments' : `${segs.length} segments`;
|
|
});
|
|
});
|
|
}
|
|
|
|
async function handleJobAction(id: string, action: string): Promise<void> {
|
|
const method = action === 'delete' ? 'DELETE' : 'POST';
|
|
const url = `/api/jobs/${id}${action === 'delete' ? '' : '/' + action}`;
|
|
try {
|
|
await api(method, url);
|
|
loadJobs();
|
|
} catch (err: any) {
|
|
alert(`Error: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
el('refresh-jobs').addEventListener('click', loadJobs);
|
|
|
|
// ── Polling ───────────────────────────────────────────
|
|
|
|
function startPolling(): void {
|
|
if (pollTimer) return;
|
|
pollTimer = window.setInterval(loadJobs, 5000);
|
|
}
|
|
|
|
// ── SSE live progress ─────────────────────────────────
|
|
|
|
function connectSSE(jobId: string): void {
|
|
if (sseMap.has(jobId)) return;
|
|
if (!authToken) return;
|
|
const es = new EventSource(`/api/jobs/${jobId}/progress?token=${encodeURIComponent(authToken)}`);
|
|
es.onmessage = (event: MessageEvent) => {
|
|
const data: ProgressData = JSON.parse(event.data);
|
|
updateJobCard(jobId, data);
|
|
if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {
|
|
es.close();
|
|
sseMap.delete(jobId);
|
|
}
|
|
};
|
|
es.onerror = () => {
|
|
es.close();
|
|
sseMap.delete(jobId);
|
|
};
|
|
sseMap.set(jobId, es);
|
|
}
|
|
|
|
function updateJobCard(jobId: string, data: ProgressData): void {
|
|
const card = document.querySelector<HTMLElement>(`.job-card[data-id="${jobId}"]`);
|
|
if (!card) return;
|
|
|
|
const badge = card.querySelector('.status-badge');
|
|
if (badge) {
|
|
badge.className = `status-badge status-${data.status}`;
|
|
badge.textContent = data.status;
|
|
}
|
|
|
|
const pct = Math.round(data.progress);
|
|
const bar = card.querySelector<HTMLElement>('[role="progressbar"]');
|
|
if (bar) bar.setAttribute('aria-valuenow', String(pct));
|
|
|
|
const fill = card.querySelector<HTMLElement>('.progress-fill');
|
|
if (fill) {
|
|
fill.style.width = pct + '%';
|
|
fill.className = 'progress-fill';
|
|
if (data.status === 'completed') fill.classList.add('completed');
|
|
else if (data.status === 'failed') fill.classList.add('failed');
|
|
}
|
|
|
|
const metaSpans = card.querySelectorAll<HTMLElement>('.job-meta span');
|
|
if (metaSpans[0]) metaSpans[0].textContent = pct + '%';
|
|
if (metaSpans[1]) metaSpans[1].textContent = `Idx: ${data.currentIndex}/${data.totalUnits}`;
|
|
|
|
const log = card.querySelector<HTMLElement>('.segment-log');
|
|
if (log && data.segments) {
|
|
log.innerHTML = data.segments.map(s =>
|
|
`<div class="segment-entry"><span class="segment-time">[${s.startTime.toFixed(1)}s]</span> ${escapeHtml(s.description)}</div>`
|
|
).join('');
|
|
}
|
|
|
|
const toggleBtn = card.querySelector<HTMLElement>('.toggle-detail');
|
|
if (toggleBtn && data.segments) {
|
|
const expanded = toggleBtn.getAttribute('aria-expanded') === 'true';
|
|
if (!expanded) toggleBtn.textContent = `${data.segments.length} segments`;
|
|
}
|
|
}
|
|
|
|
// ── Settings ──────────────────────────────────────────
|
|
|
|
async function loadSettings(): Promise<void> {
|
|
try {
|
|
const data = await apiJson<{ config: Record<string, string> }>('GET', '/api/config');
|
|
const container = el('settings-fields');
|
|
const entries = Object.entries(data.config || {});
|
|
if (!entries.length) {
|
|
container.innerHTML = '<p class="empty">No custom settings yet. Settings from .env are used as defaults.</p>';
|
|
return;
|
|
}
|
|
container.innerHTML = entries.map(([key, value]) => {
|
|
const safeKey = escapeHtml(key);
|
|
return `<div class="field"><label for="setting-${safeKey}">${safeKey}</label><input type="text" id="setting-${safeKey}" name="${safeKey}" value="${escapeHtml(String(value))}"></div>`;
|
|
}).join('');
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
(el('settings-form') as HTMLFormElement).addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const fd = new FormData(e.target as HTMLFormElement);
|
|
const config: Record<string, string> = {};
|
|
for (const [key, val] of fd.entries()) {
|
|
config[key] = val as string;
|
|
}
|
|
try {
|
|
await apiJson('PUT', '/api/config', config);
|
|
alert('Settings saved');
|
|
} catch (err: any) {
|
|
alert('Error: ' + err.message);
|
|
}
|
|
});
|
|
|
|
// ── Files list ────────────────────────────────────────
|
|
|
|
let selectedFiles = new Set<string>();
|
|
|
|
async function loadFilesList(): Promise<void> {
|
|
try {
|
|
const data = await apiJson<{ files: FileInfo[] }>('GET', '/api/files');
|
|
const tbody = document.querySelector('#files-table tbody')!;
|
|
tbody.innerHTML = data.files.map(f => `
|
|
<tr>
|
|
<td><input type="checkbox" class="file-checkbox" data-filename="${escapeHtml(f.filename)}" aria-label="Select ${escapeHtml(f.filename)}"></td>
|
|
<td>${escapeHtml(f.filename)}</td>
|
|
<td>${formatSize(f.size)}</td>
|
|
</tr>
|
|
`).join('');
|
|
|
|
tbody.querySelectorAll<HTMLInputElement>('.file-checkbox').forEach(cb => {
|
|
cb.addEventListener('change', updateFileSelection);
|
|
});
|
|
(el('select-all-files') as HTMLInputElement).checked = false;
|
|
selectedFiles.clear();
|
|
updateFileSelection();
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
function updateFileSelection(): void {
|
|
selectedFiles.clear();
|
|
document.querySelectorAll<HTMLInputElement>('.file-checkbox:checked').forEach(cb => {
|
|
if (cb.dataset.filename) selectedFiles.add(cb.dataset.filename);
|
|
});
|
|
(el('delete-selected-files') as HTMLButtonElement).disabled = selectedFiles.size === 0;
|
|
}
|
|
|
|
(el('select-all-files') as HTMLInputElement).addEventListener('change', function () {
|
|
document.querySelectorAll<HTMLInputElement>('.file-checkbox').forEach(cb => {
|
|
cb.checked = this.checked;
|
|
});
|
|
updateFileSelection();
|
|
});
|
|
|
|
el('delete-selected-files').addEventListener('click', async () => {
|
|
if (!selectedFiles.size) return;
|
|
if (!confirm(`Delete ${selectedFiles.size} file(s)?`)) return;
|
|
|
|
const failures: string[] = [];
|
|
for (const filename of selectedFiles) {
|
|
try {
|
|
await api('DELETE', `/api/files/${encodeURIComponent(filename)}`);
|
|
} catch (err: any) {
|
|
failures.push(`${filename}: ${err.message}`);
|
|
}
|
|
}
|
|
if (failures.length) {
|
|
alert(`Some deletions failed:\n${failures.join('\n')}`);
|
|
}
|
|
await loadFilesList();
|
|
await loadBrowseFiles();
|
|
});
|
|
|
|
el('refresh-files-list').addEventListener('click', loadFilesList);
|
|
|
|
// ── Config defaults for New Job form ─────────────────
|
|
|
|
async function loadConfigDefaults(): Promise<void> {
|
|
try {
|
|
const data = await apiJson<{ config: Record<string, string> }>('GET', '/api/config');
|
|
const c = data.config || {};
|
|
|
|
if (c.visionProvider) {
|
|
const sel = document.querySelector<HTMLSelectElement>('[name="visionProvider"]');
|
|
if (sel) {
|
|
sel.innerHTML = '<option value="openai">OpenAI</option><option value="gemini">Gemini</option><option value="ollama">Ollama</option><option value="openrouter">OpenRouter</option>';
|
|
sel.value = c.visionProvider;
|
|
}
|
|
}
|
|
if (c.ttsProvider) {
|
|
const sel = document.querySelector<HTMLSelectElement>('[name="ttsProvider"]');
|
|
if (sel) {
|
|
sel.innerHTML = '<option value="openai">OpenAI</option><option value="elevenlabs">ElevenLabs</option><option value="google">Google Cloud</option>';
|
|
sel.value = c.ttsProvider;
|
|
}
|
|
}
|
|
const fields: string[] = [
|
|
'visionModel', 'ttsModel', 'ttsVoice', 'ttsSpeedFactor', 'ttsInstructions',
|
|
'batchWindowDuration', 'framesInBatch', 'captureIntervalSeconds', 'contextWindowSize',
|
|
'defaultPrompt', 'changePrompt', 'batchPrompt',
|
|
];
|
|
for (const name of fields) {
|
|
const field = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(`[name="${name}"]`);
|
|
if (field && c[name] !== undefined) field.value = c[name];
|
|
}
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
// ── Init ──────────────────────────────────────────────
|
|
|
|
function initApp(): void {
|
|
wireTablist('main-tablist');
|
|
wireTablist('source-tablist');
|
|
loadJobs();
|
|
loadBrowseFiles();
|
|
loadConfigDefaults();
|
|
loadSettings();
|
|
startPolling();
|
|
}
|
|
|
|
// ── Startup ───────────────────────────────────────────
|
|
|
|
(async () => {
|
|
if (authToken) {
|
|
try {
|
|
const res = await fetch('/api/auth/check', {
|
|
headers: { Authorization: `Basic ${authToken}` },
|
|
});
|
|
const data = await res.json();
|
|
if (data.authenticated) {
|
|
showMainScreen();
|
|
initApp();
|
|
return;
|
|
}
|
|
} catch { /* fall through to login */ }
|
|
}
|
|
showLoginScreen();
|
|
})();
|