Skip to content

armgit / VERT

Public Imported from GitHub
0

The next-generation file converter. Open source, fully local* and free forever.

24.7 KB
Raw Blame
import VertdErrorComponent from "#lib/components/functional/popups/VertdError.svelte";
import { m } from "#lib/paraglide/messages";
import { Settings } from "#lib/sections/settings/index.svelte";
import {
	VertdInstance,
	getVertdCustomHeaders,
} from "#lib/sections/settings/vertdSettings.svelte";
import { VertFile } from "#lib/types";
import type {
	ConversionSettings,
	SettingCategories,
	SettingDefinition,
} from "#lib/types/conversion-settings";
import { formatError } from "#lib/util/error";
import { ToastManager } from "#lib/util/toast.svelte";
import { PUB_DISABLE_FAILURE_BLOCKS } from "$app/env/public";
import { SvelteMap, SvelteSet } from "svelte/reactivity";
import { type CodecInfo, codecOptions, toCodecInfo } from "../codec-labels";
import { Converter, FormatInfo, formatDuration } from "../converter.svelte";
import { applyPriorities } from "../priority";

interface UploadResponse {
	id: string;
	auth: string;
	from: string;
	to: null;
	completed: false;
	totalFrames: number;
	// for .zip uploads
	sequence?: {
		kind: "frameSequence" | "dash";
		extension: string;
		entry: string;
	};
}

interface RouteRequestMap {
	"/api/keep": {
		id: string;
		token: string;
	};
}

interface CodecsResponse {
	videoCodecs: CodecInfo[];
	audioCodecs: CodecInfo[];
}

type CodecsRouteResponse = {
	format?: string;
	videoCodecs?: (CodecInfo | string)[];
	audioCodecs?: (CodecInfo | string)[];
	codec?: string;
	formats?: string[];
};

interface RouteResponseMap {
	"/api/upload": UploadResponse;
	"/api/version": string;
	"/api/size_limit": number | null;
	"/api/keep": void;
	// get list of all codecs supported by vertd server
	"/api/codecs": {
		video: CodecInfo[];
		audio: CodecInfo[];
		all: CodecInfo[];
	};
	// list of codecs for this format
	[key: `/api/codecs/${string}`]: CodecsRouteResponse;
	// list of formats supporting this codec
	[key: `/api/codecs/support/${string}`]: {
		codec: string;
		formats: string[];
	};
	[key: `/api/confirm/${string}/${string}`]: void; // confirm download - job id, token
}

export const vertdFetch: {
	<U extends keyof RouteRequestMap>(
		path: U,
		options: RequestInit,
		body: RouteRequestMap[U],
		baseUrl?: string,
	): Promise<RouteResponseMap[U]>;
	<U extends Exclude<keyof RouteResponseMap, keyof RouteRequestMap>>(
		path: U,
		options: RequestInit,
		body?: undefined,
		baseUrl?: string,
	): Promise<RouteResponseMap[U]>;
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
} = async (url: any, options: RequestInit, body?: any, baseUrl?: string) => {
	const domain = baseUrl ?? (await VertdInstance.instance.url());

	const headers = new Headers(options.headers);
	for (const [key, value] of Object.entries(getVertdCustomHeaders()))
		headers.set(key, value);

	// if there is a body, insert a Content-Type: application/json header
	if (body) {
		headers.set("Content-Type", "application/json");
		options.body = JSON.stringify(body);
	}

	options.headers = headers;

	const res = await fetch(domain + url, options);

	const text = await res.text();
	const normalizedText = text.replace(/^\uFEFF/, "").trim();

	if (!normalizedText.length) {
		if (!res.ok) throw new Error(`vertd request failed (${res.status})`);
		return undefined as RouteResponseMap[typeof url];
	}

	let json: unknown = null;
	try {
		json = JSON.parse(normalizedText);
	} catch {
		throw new Error(normalizedText);
	}

	if (json && typeof json === "object" && "type" in json && "data" in json) {
		const envelope = json as { type: string; data: unknown };

		if (envelope.type === "error") {
			if (typeof envelope.data === "string")
				throw new Error(envelope.data);
			throw new Error(JSON.stringify(envelope.data));
		}

		if (envelope.type === "success")
			return envelope.data as RouteResponseMap[typeof url];
	}

	if (!res.ok) throw new Error(normalizedText);

	return json as RouteResponseMap[typeof url];
};

// ws types

export type ConversionSpeed =
	"verySlow" | "slower" | "slow" | "medium" | "fast" | "ultraFast";

const vertdSpeedValues: ConversionSpeed[] = [
	"verySlow",
	"slower",
	"slow",
	"medium",
	"fast",
	"ultraFast",
];

interface StartJobMessage {
	type: "startJob";
	data: {
		token: string;
		jobId: string;
		to: string;
		settings: ConversionSettings;
	};
}

interface ErrorMessage {
	type: "error";
	data: {
		message: unknown;
	};
}

interface ProgressMessage {
	type: "progressUpdate";
	data: ProgressData;
}

interface CompletedMessage {
	type: "jobFinished";
	data: {
		jobId: string;
	};
}

interface CancelJobMessage {
	type: "cancelJob";
	data: {
		jobId: string;
		token: string;
	};
}

interface JobCancelledMessage {
	type: "jobCancelled";
	data: {
		jobId: string;
	};
}

interface JobRetriedMessage {
	type: "jobRetried";
	data: {
		jobId: string;
	};
}

interface FpsProgress {
	type: "fps";
	data: number;
}

interface FrameProgress {
	type: "frame";
	data: number;
}

type ProgressData = FpsProgress | FrameProgress;

type VertdMessage =
	| StartJobMessage
	| ErrorMessage
	| ProgressMessage
	| CancelJobMessage
	| JobCancelledMessage
	| JobRetriedMessage
	| CompletedMessage;

const progressEstimates = {
	upload: 25,
	convert: 50,
	download: 25,
};

const progressEstimate = (
	progress: number,
	type: keyof typeof progressEstimates,
) => {
	const previousValues = Object.values(progressEstimates)
		.filter((_, i) => i < Object.keys(progressEstimates).indexOf(type))
		.reduce((a, b) => a + b, 0);
	return progress * progressEstimates[type] + previousValues;
};

interface UploadTask {
	promise: Promise<UploadResponse>;
	abort: () => void;
}

const createUploadTask = async (
	file: VertFile,
	apiUrl: string,
	sequenceKind?: "frameSequence" | "dash",
): Promise<UploadTask> => {
	const formData = new FormData();
	if (sequenceKind) formData.append("sequenceKind", sequenceKind);
	formData.append("file", file.file, file.name);
	const xhr = new XMLHttpRequest();
	xhr.open("POST", `${apiUrl}/api/upload`, true);
	const customHeaders = getVertdCustomHeaders();

	const promise = new Promise<UploadResponse>((resolve, reject) => {
		xhr.upload.addEventListener("progress", (e) => {
			console.log(e);
			if (e.lengthComputable) {
				file.progress = progressEstimate(e.loaded / e.total, "upload");
			}
		});

		console.log("meow");

		xhr.onload = () => {
			try {
				console.log("xhr.responseText");
				const res = JSON.parse(xhr.responseText);
				if (res.type === "error") {
					reject(new Error(formatError(res.data)));
					return;
				}
				resolve(res.data);
			} catch {
				console.log(xhr.responseText);
				reject(xhr.statusText);
			}
		};

		xhr.onerror = () => {
			console.log(xhr.statusText);
			reject(xhr.statusText);
		};

		xhr.onabort = () => {
			reject(new Error("Conversion cancelled"));
		};

		for (const [key, value] of Object.entries(customHeaders))
			xhr.setRequestHeader(key, value);

		xhr.send(formData);
		console.log("sent!");
	});

	return {
		promise,
		abort: () => xhr.abort(),
	};
};

interface DownloadTask {
	promise: Promise<Blob>;
	abort: () => void;
}

const downloadTask = (url: string, file: VertFile): DownloadTask => {
	const xhr = new XMLHttpRequest();
	xhr.open("GET", url, true);
	xhr.responseType = "blob";
	const customHeaders = getVertdCustomHeaders();

	const promise = new Promise<Blob>((resolve, reject) => {
		xhr.addEventListener("progress", (e) => {
			if (e.lengthComputable) {
				file.progress = progressEstimate(
					e.loaded / e.total,
					"download",
				);
			}
		});

		xhr.onload = () => {
			if (xhr.status === 200) {
				resolve(xhr.response);
			} else {
				reject(xhr.statusText);
			}
		};

		xhr.onerror = () => {
			reject(xhr.statusText);
		};

		xhr.onabort = () => {
			reject(new Error("Conversion cancelled"));
		};

		for (const [key, value] of Object.entries(customHeaders))
			xhr.setRequestHeader(key, value);

		xhr.send();
	});

	return {
		promise,
		abort: () => xhr.abort(),
	};
};

// prettier-ignore
export const videoFormats: string[] = ["mp4", "mkv", "webm", "avi", "wmv", "mov", "gif", "apng", "webp", "mts", "ts", "m2ts", "mpg", "mpeg", "flv", "f4v", "vob", "m4v", "3gp", "3g2", "mxf", "ogx", "ogv", "gxf", "rm", "rmvb", "h264", "divx", "swf", "amv", "asf", "nut", "ivf", "y4m"];
const cantEncode: string[] = ["rm", "rmvb"];
const cantDecode: string[] = [];

export class VertdConverter extends Converter {
	public name = "vertd";
	public ready = $state(false);
	public reportsProgress = true;

	private activeConversions = new SvelteMap<
		string,
		{
			ws: WebSocket;
			jobId: string;
			token: string;
		}
	>();

	private activeUploads = new SvelteMap<string, UploadTask>();

	private activeDownloads = new SvelteMap<string, DownloadTask>();

	private cancelledConversions = new SvelteSet<string>();

	public supportedFormats = applyPriorities("vertd", [
		new FormatInfo("zip", true, false, false, 0),
		...videoFormats
			.map((f: string) => new FormatInfo(f, true, true, true))
			.filter((format) => !cantEncode.includes(format.name.slice(1)))
			.filter((format) => !cantDecode.includes(format.name.slice(1))),
		...cantEncode.map((f) => new FormatInfo(f, true, false, true)),
		...cantDecode.map((f) => new FormatInfo(f, false, true, true)),
	]);

	private codecs: CodecsResponse = { videoCodecs: [], audioCodecs: [] };

	constructor() {
		super();
		this.log("created converter");
		this.log("not rly sure how to implement this :P");
		this.status = "ready";
	}

	private blocked(hash: string): boolean {
		let blockedHashes = Settings.instance.settings.vertdBlockedHashes;

		// ensure it's a map
		// this might fix the "e.get" isn't a function error, but i can't reproduce it
		if (!(blockedHashes instanceof Map) || blockedHashes === null) {
			// eslint-disable-next-line svelte/prefer-svelte-reactivity
			blockedHashes = new Map(Object.entries(blockedHashes || {}));
			Settings.instance.settings.vertdBlockedHashes = blockedHashes;
			Settings.instance.save();
		}

		// eslint-disable-next-line svelte/prefer-svelte-reactivity
		const now = new Date();
		const dates = blockedHashes.get(hash) || [];
		const filteredDates = dates.filter(
			(date) => now.getTime() - date.getTime() < 60 * 60 * 1000,
		);

		if (filteredDates.length === 0) {
			blockedHashes.delete(hash);
			return false;
		}

		blockedHashes.set(hash, filteredDates);

		Settings.instance.save();

		return filteredDates.length >= 3;
	}

	private failure(hash: string): void {
		let blockedHashes = Settings.instance.settings.vertdBlockedHashes;

		// same as above (blocked())
		if (!(blockedHashes instanceof Map) || blockedHashes === null) {
			// eslint-disable-next-line svelte/prefer-svelte-reactivity
			blockedHashes = new Map(Object.entries(blockedHashes || {}));
			Settings.instance.settings.vertdBlockedHashes = blockedHashes;
			Settings.instance.save();
		}

		// eslint-disable-next-line svelte/prefer-svelte-reactivity
		const now = new Date();
		const dates = blockedHashes.get(hash) || [];
		dates.push(now);
		blockedHashes.set(hash, dates);
		Settings.instance.save();
	}

	public async getAvailableSettings(
		input: VertFile,
		baseUrl?: string,
	): Promise<SettingCategories> {
		// video - bitrate, fps, resolution, trim, crop, rotate, flip/flop, audio settings?

		const qualityOptions = [
			{
				value: 0, // very slow
				label: m["convert.settings.video.speed.very_slow"](),
			},
			{
				value: 1, // slower
				label: m["convert.settings.video.speed.slower"](),
			},
			{
				value: 2, // slow
				label: m["convert.settings.video.speed.slow"](),
			},
			{
				value: 3, // medium
				label: m["convert.settings.video.speed.medium"](),
			},
			{
				value: 4, // faster
				label: m["convert.settings.video.speed.fast"](),
			},
			{
				value: 5, // fastest
				label: m["convert.settings.video.speed.ultra_fast"](),
			},
		];

		// get codecs for this format from vertd
		try {
			const targetFormat = input.to.replace(/^\./, "");
			const codecsJson = await vertdFetch(
				`/api/codecs/${targetFormat}`,
				{
					method: "GET",
				},
				undefined,
				baseUrl,
			);

			const nextCodecs: CodecsResponse = {
				videoCodecs: (codecsJson.videoCodecs || []).map(toCodecInfo),
				audioCodecs: (codecsJson.audioCodecs || []).map(toCodecInfo),
			};
			const previousCodecs = JSON.stringify(this.codecs);
			const newCodecs = JSON.stringify(nextCodecs);

			if (previousCodecs !== newCodecs) {
				this.codecs = nextCodecs;
				this.log(`updated codecs from vertd: ${newCodecs}`);
			}
		} catch (e) {
			this.error(`failed to fetch codecs from vertd: ${e}`);
			throw e;
		}

		// get default vertd speed
		const defaultSpeed = Settings.instance.settings.vertdSpeed;
		const defaultSpeedIndex = vertdSpeedValues.indexOf(defaultSpeed);
		const qualitySpeedRange: SettingDefinition = {
			key: "vertdSpeed",
			label: m["convert.settings.video.speed.title"](),
			description: m["convert.settings.video.speed.description"](),
			type: "range",
			min: 0,
			max: qualityOptions.length - 1,
			step: 1,
			default: defaultSpeedIndex !== -1 ? defaultSpeedIndex : 3,
			options: qualityOptions.map((option, index) => ({
				value: index,
				label: option.label,
			})),
			forceFullWidth: true,
		};

		const fps: SettingDefinition = {
			key: "fps",
			label: m["convert.settings.video.fps.label"](),
			type: "text",
			default: "",
			placeholder: m["convert.settings.video.fps.placeholder"](),
		};

		const resolution: SettingDefinition = {
			key: "resolution",
			label: m["convert.settings.video.resolution.label"](),
			type: "text",
			default: "",
			placeholder: m["convert.settings.video.resolution.placeholder"](),
		};

		const videoCodec: SettingDefinition = {
			key: "videoCodec",
			label: m["convert.settings.video.codec.video"](),
			type: "select",
			default: "auto",
			options: [
				{ value: "auto", label: m["convert.settings.common.auto"]() },
				...codecOptions(this.codecs.videoCodecs),
			],
		};

		// TODO: allow CRF for consistent quality?
		const videoBitrate: SettingDefinition = {
			key: "videoBitrate",
			label: m["convert.settings.video.bitrate.video"](),
			type: "text",
			default: "",
			placeholder:
				m["convert.settings.video.bitrate.video_placeholder"](),
		};

		/*
		 *	audio settings
		 */
		const audioCodec: SettingDefinition = {
			key: "audioCodec",
			label: m["convert.settings.video.codec.audio"](),
			type: "select",
			default: "auto",
			options: [
				{ value: "auto", label: m["convert.settings.common.auto"]() },
				...codecOptions(this.codecs.audioCodecs),
			],
		};

		const audioBitrate: SettingDefinition = {
			key: "audioBitrate",
			label: m["convert.settings.video.bitrate.audio"](),
			type: "text",
			default: "",
			placeholder:
				m["convert.settings.video.bitrate.audio_placeholder"](),
		};

		const sampleRate: SettingDefinition = {
			key: "sampleRate",
			label: m["convert.settings.audio.sample_rate.label"](),
			type: "text",
			default: "",
			placeholder: m["convert.settings.audio.sample_rate.placeholder"](),
		};

		const audioChannels: SettingDefinition = {
			key: "audioChannels",
			label: m["convert.settings.video.audioChannels.label"](),
			type: "text",
			default: "",
			placeholder:
				m["convert.settings.video.audioChannels.placeholder"](),
		};

		/*
		 *	common
		 */
		const metadata: SettingDefinition = {
			key: "metadata",
			label: m["convert.settings.common.metadata"](),
			type: "boolean",
			default: Settings.instance.settings.metadata,
		};

		// trim/crop/rotate - also have another ui for this prob

		const animatedImages = [".gif", ".webp", ".apng"];
		if (animatedImages.includes(input.to)) {
			return {
				Video: [fps, resolution],
				General: [metadata],
			};
		}

		return {
			Video: [
				qualitySpeedRange,
				videoCodec,
				videoBitrate,
				fps,
				resolution,
			],
			Audio: [audioCodec, audioBitrate, audioChannels, sampleRate],
			General: [metadata],
		};
	}

	public async getDefaultSettings(
		input: VertFile,
		baseUrl?: string,
	): Promise<ConversionSettings> {
		const defaults: ConversionSettings = {};
		const categories = await this.getAvailableSettings(input, baseUrl);
		Object.values(categories)
			.flat()
			.forEach((setting) => {
				defaults[setting.key] = setting.default;
			});

		return defaults;
	}

	public async convert(
		input: VertFile,
		to: string,
		settings: ConversionSettings,
	): Promise<VertFile> {
		this.trackConversion(input);
		if (to.startsWith(".")) to = to.slice(1);
		this.log(`converting ${input.name} (${input.id}) to .${to}`);
		const startedAt = performance.now();

		const fileUpload = input;
		const apiUrl = await VertdInstance.instance.url();
		const conversionSettings = // vertd expects object not string json
			Object.keys(settings).length > 4
				? { ...settings } // user-provided settings
				: { ...(await this.getDefaultSettings(input)), ...settings }; // use defaults if not provided

		let hash: string;
		if (PUB_DISABLE_FAILURE_BLOCKS === "false") {
			hash = await fileUpload.hash();
			if (this.blocked(hash)) {
				this.log(
					`conversion blocked for file ${input.name} (${input.id})`,
				);
				throw new Error(
					m["convert.errors.vertd.ratelimit"]({
						filename: input.name,
					}),
				);
			}
		}

		const uploadTask = await createUploadTask(
			fileUpload,
			apiUrl,
			fileUpload.sequenceKind,
		);
		this.activeUploads.set(input.id, uploadTask);

		// cover a cancel that arrived during url resolution / upload setup
		if (this.isCancelled(input)) {
			this.clearCancel(input);
			throw new Error("Conversion cancelled");
		}

		let uploadRes: UploadResponse;
		try {
			uploadRes = await uploadTask.promise;
		} finally {
			this.activeUploads.delete(input.id);
		}

		if (uploadRes.sequence)
			this.log(
				`received sequence upload for ${input.name} (${input.id}) (kind: ${uploadRes.sequence.kind}, extension: ${uploadRes.sequence.extension}, entry: ${uploadRes.sequence.entry})`,
			);

		if (this.cancelledConversions.has(input.id)) {
			this.clearCancel(input);
			throw new Error("Conversion cancelled");
		}

		return new Promise((resolve, reject) => {
			let settled = false;
			const protocol = apiUrl.startsWith("https") ? "wss:" : "ws:";
			const ws = new WebSocket(
				`${protocol}//${apiUrl.replace("http://", "").replace("https://", "")}/api/ws`,
			);

			const connectTimeout = setTimeout(() => {
				if (settled) return;
				settled = true;
				this.activeConversions.delete(input.id);
				ws.close();
				reject(new Error("vertd websocket connection timeout"));
			}, 30000);

			const rejectConversion = (reason: unknown) => {
				if (settled) return;
				settled = true;
				clearTimeout(connectTimeout);
				this.cancelledConversions.delete(input.id);
				this.clearCancel(input);
				this.activeUploads.delete(input.id);
				this.activeDownloads.get(input.id)?.abort();
				this.activeDownloads.delete(input.id);
				this.activeConversions.delete(input.id);
				if (
					ws.readyState === WebSocket.CONNECTING ||
					ws.readyState === WebSocket.OPEN
				) {
					ws.close();
				}
				reject(reason);
			};

			const resolveConversion = (value: VertFile) => {
				if (settled) return;
				settled = true;
				clearTimeout(connectTimeout);
				this.cancelledConversions.delete(input.id);
				this.clearCancel(input);
				this.activeUploads.delete(input.id);
				this.activeDownloads.delete(input.id);
				this.activeConversions.delete(input.id);
				resolve(value);
			};

			this.activeConversions.set(input.id, {
				ws,
				jobId: uploadRes.id,
				token: uploadRes.auth,
			});

			ws.onopen = () => {
				if (this.cancelledConversions.has(input.id)) {
					rejectConversion(new Error("Conversion cancelled"));
					return;
				}

				clearTimeout(connectTimeout);
				this.log(
					`opened ws connection to vertd for file ${input.name} (${input.id})`,
				);
				const msg: StartJobMessage = {
					type: "startJob",
					data: {
						jobId: uploadRes.id,
						token: uploadRes.auth,
						to,
						settings: conversionSettings,
					},
				};
				ws.send(JSON.stringify(msg));
				this.log(JSON.stringify(msg, null, 2));
				this.log(
					`sent startJob message for file ${input.name} (${input.id})`,
				);
			};

			ws.onerror = () => {
				this.error(`ws error for file ${input.name} (${input.id})`);
				rejectConversion(new Error("vertd websocket error"));
			};

			ws.onclose = (e) => {
				if (settled) return;
				if (this.cancelledConversions.has(input.id)) {
					rejectConversion(new Error("Conversion cancelled"));
					return;
				}

				this.error(
					`ws closed unexpectedly for file ${input.name} (${input.id}) (code: ${e.code})`,
				);
				rejectConversion(
					new Error("vertd websocket closed unexpectedly"),
				);
			};

			ws.onmessage = async (e) => {
				let msg: VertdMessage;
				try {
					if (typeof e.data !== "string") {
						rejectConversion(
							new Error("invalid websocket payload type"),
						);
						return;
					}
					msg = JSON.parse(e.data);
				} catch {
					rejectConversion(new Error("invalid websocket payload"));
					return;
				}

				this.log(
					`received message ${msg.type} for file ${input.name} (${input.id})`,
				);
				switch (msg.type) {
					case "progressUpdate": {
						const data = msg.data;
						if (data.type !== "frame") break;
						const frame = data.data;
						input.progress = progressEstimate(
							frame / uploadRes.totalFrames,
							"convert",
						);
						break;
					}

					case "jobRetried": {
						this.log(
							`job retrying for file ${input.name} (${input.id})`,
						);
						ToastManager.add({
							type: "error",
							message: m["convert.errors.vertd.retry"]({
								filename: input.name,
							}),
						});
						break;
					}

					case "jobFinished": {
						this.log(
							`job finished for file ${input.name} (${input.id})`,
						);
						try {
							if (settled) break;
							const url = `${apiUrl}/api/download/${msg.data.jobId}/${uploadRes.auth}`;
							this.log(`downloading from ${url}`);
							const download = downloadTask(url, input);
							this.activeDownloads.set(input.id, download);
							const res = await download.promise;
							this.activeDownloads.delete(input.id);

							if (settled) return; // cancelled during download

							// confirm download to clean up on server
							try {
								await vertdFetch(
									`/api/confirm/${msg.data.jobId}/${uploadRes.auth}`,
									{
										method: "GET",
									},
									undefined,
									apiUrl,
								);
								this.log(
									`confirmed download for file ${input.name} (${input.id})`,
								);
							} catch (e) {
								this.error(`failed to confirm download: ${e}`);
							}

							this.log(
								`converted ${input.name} (${input.id}) to .${to} in ${formatDuration(performance.now() - startedAt)}`,
							);
							resolveConversion(
								new VertFile(
									new File([res], input.name),
									`.${to}`,
								),
							);
						} catch (e) {
							// don't count cancellations as failures
							if (
								hash &&
								!this.cancelledConversions.has(input.id)
							)
								this.failure(hash);
							rejectConversion(e);
						} finally {
							ws.close();
						}
						break;
					}

					case "jobCancelled": {
						this.log("job cancelled");
						ws.close();
						rejectConversion("Conversion cancelled");
						break;
					}

					case "error": {
						const errorText = formatError(msg.data.message);
						this.error(`error: ${errorText}`);
						if (hash) this.failure(hash);

						rejectConversion({
							component: VertdErrorComponent,
							additional: {
								jobId: uploadRes.id,
								auth: uploadRes.auth,
								from: input.from,
								to: to,
								errorMessage: errorText,
							},
						});
						break;
					}

					default: {
						break;
					}
				}
			};
		});
	}

	public async cancel(input: VertFile): Promise<void> {
		await super.cancel(input);

		this.cancelledConversions.add(input.id);

		const activeUpload = this.activeUploads.get(input.id);
		if (activeUpload) {
			this.log(`cancelling upload for file ${input.name} (${input.id})`);
			activeUpload.abort();
			this.activeUploads.delete(input.id);
		}

		const activeDownload = this.activeDownloads.get(input.id);
		if (activeDownload) {
			this.log(
				`cancelling download for file ${input.name} (${input.id})`,
			);
			activeDownload.abort();
			this.activeDownloads.delete(input.id);
		}

		const activeConversion = this.activeConversions.get(input.id);
		if (!activeConversion) {
			if (!activeUpload && !activeDownload)
				this.error(
					`no active conversion found for file ${input.name} (${input.id})`,
				);
			return;
		}

		const { ws, jobId, token } = activeConversion;

		if (ws.readyState === WebSocket.OPEN) {
			const cancelMsg: CancelJobMessage = {
				type: "cancelJob",
				data: {
					jobId,
					token,
				},
			};
			ws.send(JSON.stringify(cancelMsg));
			this.log(
				`sent cancelJob message for file ${input.name} (${input.id})`,
			);
		}

		ws.close();
		this.activeConversions.delete(input.id);
	}

	public async valid(): Promise<boolean> {
		try {
			const apiUrl = await VertdInstance.instance.url();
			await vertdFetch(
				"/api/version",
				{
					method: "GET",
				},
				undefined,
				apiUrl,
			);
			return true;
		} catch (e) {
			this.log(e as unknown as string);
			return false;
		}
	}
}