import { json, error } from '@sveltejs/kit'; import { getJob, updateJob, setJobStatus } from '$lib/server/db.js'; import { deduplicateSegments } from '$lib/server/postprocess.js'; import { writeOutputs } from '$lib/server/formatter.js'; import { sendNotification } from '$lib/server/push.js'; import { cleanupJobTmp } from '$lib/server/downloader.js'; import { emitProgress } from '$lib/server/pipeline.js'; import type { Segment, WhisperJob } from '$lib/types.js'; export async function POST({ params, request }) { const jobId = params.jobId; const job = getJob(jobId); if (!job) throw error(404, 'Job not found'); // Discard the result if the job was cancelled locally while whisper was running if (job.status === 'cancelled') { return json({ ok: true }); } const whisperJob = (await request.json()) as WhisperJob; if (whisperJob.status === 'failed' || whisperJob.status === 'cancelled') { const msg = whisperJob.error ?? `Whisper job ${whisperJob.status}`; updateJob({ id: jobId, status: 'failed', error: msg }); emitProgress(jobId, { type: 'error', message: msg }); return json({ ok: true }); } try { setJobStatus(jobId, 'processing', 90); emitProgress(jobId, { type: 'status', status: 'processing', progress: 90 }); const rawSegments = whisperJob.segments as Segment[]; const segments = deduplicateSegments(rawSegments); const paths = await writeOutputs(segments, job.title, jobId); const outputDir = paths.srt.replace(/\/[^/]+$/, ''); updateJob({ id: jobId, status: 'done', progress: 100, segmentsJson: JSON.stringify(segments), outputDir }); emitProgress(jobId, { type: 'done', status: 'done' }); await sendNotification(jobId, '✅ Transcript ready', job.title); await cleanupJobTmp(jobId); return json({ ok: true }); } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); updateJob({ id: jobId, status: 'failed', error: message }); emitProgress(jobId, { type: 'error', message }); return json({ ok: false, error: message }, { status: 500 }); } }