The next-generation file converter. Open source, fully local* and free forever.
fix: handle errors and zip errors better
JovannMCbe7637f31f66
diff --git a/messages/en.json b/messages/en.jsonindex d6217ec..4c26ee5 100644--- a/messages/en.json+++ b/messages/en.json@@ -50,14 +50,15 @@"convert": {"archive_file": {"extract": "Extract archive",- "extracting": "Detected archive: {filename}",- "extracted": "Extracted {extract_count} files from {filename}. {ignore_count} items were ignored.",- "detected": "Detected {type} files in {filename}.",+ "extracting": "Detected '{filename}' as an archive.",+ "extracted": "Extracted {extract_count} files from '{filename}'. {ignore_count} items were ignored.",+ "detected": "Detected {type} files in '{filename}'.","audio": "audio","video": "video","doc": "document","image": "image",- "extract_error": "Error extracting {filename}: {error}"+ "extract_error": "Error extracting '{filename}': {error}",+ "conversion_failed": "Failed to convert {count} files in '{filename}'. See '{reportName}' in the archive for more information."},"image_sequence": {"image_sequence": "Image Sequence",@@ -212,10 +213,10 @@"cant_convert": "We can't convert this file.","converter_fallback": {"title": "Change converter?",- "body": "Conversion failed for {filename}. Would you like to try the next compatible converter {converter}?",+ "body": "Conversion failed for '{filename}'. Would you like to try the next compatible converter, '{converter}'?","yes": "Next converter","no": "Cancel conversion",- "all_failed": "All compatible converters failed for {filename}. Conversion has been cancelled."+ "all_failed": "All compatible converters failed for '{filename}'. Conversion has been cancelled."},"unsupported_format": "Only image, video, audio, and document files are supported","format_output_only": "This format can currently only be used as output (converted to), not as input.",@@ -451,7 +452,7 @@},"warnings": {"settings_change": "Changed setting '{setting}' from '{oldValue}' to '{newValue}' for {file} ({to}) to prevent conversion failure.",- "file_type_mismatch": "File {filename} is named {expected}, but was detected as {actual}. This may cause conversion issues."+ "file_type_mismatch": "File '{filename}' is named {expected}, but was detected as {actual}. This may cause conversion issues."}},"privacy": {diff --git a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts b/src/lib/converters/ffmpeg/ffmpeg.svelte.tsindex 19b8b72..23fc658 100644--- a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts+++ b/src/lib/converters/ffmpeg/ffmpeg.svelte.ts@@ -291,7 +291,7 @@ export class FFmpegConverter extends Converter {input,to,conversionSettings,- conversionError,+ () => conversionError,);if (specialHandled) {return specialHandled;@@ -561,7 +561,7 @@ const handleSpecialOutput = async (input: VertFile,to: string,conversionSettings: ConversionSettings,- conversionError: string | null,+ getConversionError: () => string | null,): Promise<VertFile | null> => {if (to === ".qoa") {const sampleRate =@@ -590,13 +590,20 @@ const handleSpecialOutput = async ("pcm_f32le","output.raw",];- await ffmpeg.exec(pcmArgs);+ const exitCode = await ffmpeg.exec(pcmArgs);+ const conversionError = getConversionError();if (conversionError) throw new Error(conversionError);+ if (exitCode !== 0)+ throw new Error(+ `FFmpeg QOA PCM conversion failed with exit code ${exitCode}`,+ );const pcmRaw = (await ffmpeg.readFile("output.raw",)) as unknown as Uint8Array;+ if (!pcmRaw || pcmRaw.length === 0)+ throw new Error("FFmpeg QOA conversion returned empty PCM audio");const { encodeQoa } = await import("$lib/util/parse/qoa");const qoaBytes = encodeQoa(new Uint8Array(pcmRaw),diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex b2f681c..daad8e0 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -411,10 +411,20 @@ class Files {}public async convertAll() {+ const filenames = this.files.map((file) => file.name);const promiseFns = this.files.map((f) => () => f.convert());const coreCount = navigator.hardwareConcurrency || 4;const queue = new PQueue({ concurrency: coreCount });- await Promise.all(promiseFns.map((fn) => queue.add(fn)));+ const results = await Promise.allSettled(+ promiseFns.map((fn) => queue.add(fn)),+ );+ for (const [i, result] of results.entries()) {+ if (result.status === "rejected")+ error(+ ["files", "convert"],+ `batch conversion failed for file ${i + 1} (${filenames[i]}): ${result.reason}`,+ );+ }}public async downloadAll() {diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex 70e1f17..f7dc397 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -356,104 +356,105 @@ export class VertFile {// eslint-disable-next-line @typescript-eslint/no-explicit-anypublic async convert(...args: any[]) {- await this.runPostDownload();-if (!this.retryingFallback) this.attemptedConverters.clear();+ this.cancelled = false;+ let res: VertFile | undefined;+ try {+ await this.runPostDownload();- log(- `Starting conversion for ${this.file.name} from ${this.from} to ${this.to}`,- );- if (!this.converters.length) throw new Error("No converters found");-- let converter: Converter | undefined;- const isImageSequence =- this.conversionSettings.imageSequence && this.isZip();-- // force ffmpeg for image sequences- // TODO: should allow vertd as well probably(?) but maybe in the future- if (isImageSequence) {- converter = converters.find((c) => c.name === "ffmpeg");- if (!converter) {- throw new Error(- "FFmpeg converter not found for image sequence conversion",- );- }- } else {- const customConverter = this.converters.find(- (c) => c.name === this.conversionSettings.converter,+ log(+ ["file", "convert"],+ `Starting conversion for ${this.file.name} from ${this.from} to ${this.to}`,);- converter = customConverter;-- if (!converter) {- const compatibleConverters = this.findConverters([- this.from,- this.to,- ]);- if (compatibleConverters.length) {- converter = compatibleConverters[0];- log(- ["file", "convert"],- `found compatible converter: ${converter.name}`,+ if (!this.converters.length) throw new Error("No converters found");++ let converter: Converter | undefined;+ const isImageSequence =+ this.conversionSettings.imageSequence && this.isZip();++ // force ffmpeg for image sequences+ // TODO: should allow vertd as well probably(?) but maybe in the future+ if (isImageSequence) {+ converter = converters.find((c) => c.name === "ffmpeg");+ if (!converter) {+ throw new Error(+ "FFmpeg converter not found for image sequence conversion",);+ }+ } else {+ const customConverter = this.converters.find(+ (c) => c.name === this.conversionSettings.converter,+ );+ converter = customConverter;++ if (!converter) {+ const compatibleConverters = this.findConverters([+ this.from,+ this.to,+ ]);+ if (compatibleConverters.length) {+ converter = compatibleConverters[0];+ log(+ ["file", "convert"],+ `found compatible converter: ${converter.name}`,+ );+ } else {+ log(+ ["file", "convert"],+ `no compatible converter found for ${this.from} to ${this.to}`,+ );+ }} else {log(["file", "convert"],- `no compatible converter found for ${this.from} to ${this.to}`,+ `using custom converter from settings: ${converter.name}`,);}- } else {- log(- ["file", "convert"],- `using custom converter from settings: ${converter.name}`,- );}- }-- if (!converter) throw new Error("No converter found");- const canProceed = await this.confirmServerWarning(converter);- if (!canProceed) {- this.cancelled = true;- return;- }+ if (!converter) throw new Error("No converter found");- const normalizedSettings: NormalizedSettings =- await converter.normalizeSettings(this, this.to, {- ...(await converter.getDefaultSettings(this)),- ...Object.fromEntries(- Object.entries(this.conversionSettings).filter(- ([, value]) => value !== undefined,+ const canProceed = await this.confirmServerWarning(converter);+ if (!canProceed) {+ this.cancelled = true;+ return;+ }+ this.attemptedConverters.add(converter.name);+ this.activeConverterName = converter.name;++ const normalizedSettings: NormalizedSettings =+ await converter.normalizeSettings(this, this.to, {+ ...(await converter.getDefaultSettings(this)),+ ...Object.fromEntries(+ Object.entries(this.conversionSettings).filter(+ ([, value]) => value !== undefined,+ ),),- ),- });+ });- for (const change of normalizedSettings.changes) {- log(- ["file", "settings"],- `changed setting "${change.setting}" from "${change.oldValue}" to "${change.newValue}" for file ${change.file}`,- );- ToastManager.add({- type: "warning",- message: m["workers.warnings.settings_change"]({- setting: change.setting,- oldValue: change.oldValue,- newValue: change.newValue,- file: change.file,- to: this.to,- }),- });- }+ for (const change of normalizedSettings.changes) {+ log(+ ["file", "settings"],+ `changed setting "${change.setting}" from "${change.oldValue}" to "${change.newValue}" for file ${change.file}`,+ );+ ToastManager.add({+ type: "warning",+ message: m["workers.warnings.settings_change"]({+ setting: change.setting,+ oldValue: change.oldValue,+ newValue: change.newValue,+ file: change.file,+ to: this.to,+ }),+ });+ }- this.attemptedConverters.add(converter.name);- this.activeConverterName = converter.name;- log(["file", "convert"], `using converter: ${converter.name}`);+ log(["file", "convert"], `using converter: ${converter.name}`);- this.result = null;- this.progress = 0;- this.processing = true;- this.cancelled = false;- let res;- try {+ this.result = null;+ this.progress = 0;+ this.processing = true;+ this.cancelled = false;// for zips: extract > convert each > re-zip// else convert normallyres =@@ -540,9 +541,10 @@ export class VertFile {}this.result = null;+ } finally {+ this.processing = false;+ this.activeConverterName = null;}- this.processing = false;- this.activeConverterName = null;return res;}@@ -568,6 +570,7 @@ export class VertFile {const totalFiles = entries.length;const fileProgress: number[] = new Array(totalFiles).fill(0);const convertedFiles: File[] = [];+ const failedFiles: string[] = [];const progressFiles = new Map<number, VertFile>();const progressInterval = setInterval(() => {for (const [index, file] of progressFiles)@@ -581,68 +584,120 @@ export class VertFile {const updateProgress = () => {const totalProgress = fileProgress.reduce((sum, p) => sum + p, 0);- this.progress = Math.round(totalProgress / totalFiles);+ this.progress = totalFiles+ ? Math.round(totalProgress / totalFiles)+ : 100;};try {// convert all files in the zip- await queue.addAll(- entries.map(({ filename, data }, index) => async () => {- if (this.cancelled) {- throw new Error("Conversion cancelled");- }-- const tempVFile = new VertFile(- new File([new Uint8Array(data)], filename, {- type: "application/octet-stream",- }),- this.to,- );- tempVFile.from =- this.archiveFormats?.[index] ?? tempVFile.from;- tempVFile.converters = [converter];-- if (converter.reportsProgress) {- progressFiles.set(index, tempVFile);+ await Promise.allSettled(+ entries.map(({ filename, data }, index) =>+ queue.add(async () => {try {- const converted = await converter.convert(- tempVFile,+ if (this.cancelled) {+ throw new Error("Conversion cancelled");+ }++ const tempVFile = new VertFile(+ new File([new Uint8Array(data)], filename, {+ type: "application/octet-stream",+ }),this.to,- settings,);-- convertedFiles[index] = converted.file;- fileProgress[index] = 100;- updateProgress();+ tempVFile.from =+ this.archiveFormats?.[index] ?? tempVFile.from;+ tempVFile.converters = [converter];++ if (converter.reportsProgress) {+ progressFiles.set(index, tempVFile);+ try {+ const converted = await converter.convert(+ tempVFile,+ this.to,+ settings,+ );++ convertedFiles[index] = converted.file;+ fileProgress[index] = 100;+ updateProgress();+ } finally {+ progressFiles.delete(index);+ }+ } else {+ // else track progress via completions only+ const converted = await converter.convert(+ tempVFile,+ this.to,+ settings,+ );++ convertedFiles[index] = converted.file;++ fileProgress[index] = 100;+ updateProgress();+ }+ } catch (err) {+ if (!this.cancelled) {+ const message =+ err instanceof Error+ ? err.message+ : String(err);+ failedFiles[index] = `${filename}: ${message}`;+ error(+ ["file", "zip"],+ `failed to convert archive member ${filename}: ${message}`,+ );+ }} finally {progressFiles.delete(index);+ fileProgress[index] = 100;+ updateProgress();}- } else {- // else track progress via completions only- const converted = await converter.convert(- tempVFile,- this.to,- settings,- );-- convertedFiles[index] = converted.file;-- fileProgress[index] = 100;- updateProgress();- }- }),+ }),+ ),);} finally {clearInterval(progressInterval);}// return zip of converted files- const resultArray = await createZip(convertedFiles);+ if (this.cancelled) throw new Error("Conversion cancelled");+ const outputFiles = convertedFiles.filter(Boolean);+ const failures = failedFiles.filter(Boolean);+ let reportName = "failed-files.txt";+ if (failures.length) {+ for (+ let suffix = 1;+ outputFiles.some((file) => file.name === reportName);+ suffix+++ )+ reportName = `failed-files-${suffix}.txt`;+ outputFiles.push(+ new File(+ [+ `Failed conversions (${failures.length}):\n\n${failures.join("\n")}\n`,+ ],+ reportName,+ { type: "text/plain" },+ ),+ );+ }+ const resultArray = await createZip(outputFiles);const outputFilename = this.file.name.replace(/\.[^/.]+$/, ".zip");const resultFile = new File([new Uint8Array(resultArray)],outputFilename,);+ if (failures.length)+ ToastManager.add({+ type: "warning",+ message: m["convert.archive_file.conversion_failed"]({+ filename: outputFilename,+ count: failures.length,+ reportName,+ }),+ });return new VertFile(resultFile, ".zip");}diff --git a/src/lib/util/file.ts b/src/lib/util/file.tsindex 067ac21..803013a 100644--- a/src/lib/util/file.ts+++ b/src/lib/util/file.ts@@ -44,10 +44,11 @@ export async function createZip(files: File[]): Promise<Uint8Array> {}export function ignoreEntry(filename: string): boolean {+ const parts = filename.replace(/\\/g, "/").split("/");return (- filename.startsWith(".") ||- filename.includes("/__MACOSX/") ||- filename.endsWith("/")+ parts.some(+ (part) => part.startsWith(".") || part.toUpperCase() === "__MACOSX",+ ) || filename.endsWith("/"));}