Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Say "the file is empty" for 0-byte sources instead of an engine error (#157)

KnifeLemonc8fbd7d1b311
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 81b656b6..83370f7c 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -68,6 +68,7 @@
"toast.cancel": "Cancel",
"error.unsupported_source": "This file type isn't supported",
+ "error.empty_file": "The file is empty (0 bytes). A file made with “New” in the right-click menu stays empty until you open it in its app and save it",
"format_request.request": "Request this format",
"format_request.notice_title": "Filee can't convert {0} files yet",
"format_request.notice_text": "Tell us which format you need.\nRequests decide what Filee supports next.\nEncrypted or copy-protected (DRM) files can't be converted, whatever the format.",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index c72674de..f55421c8 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -62,6 +62,7 @@
"toast.open_folder": "Mostrar",
"toast.cancel": "Cancelar",
"error.unsupported_source": "Este tipo de archivo no es compatible",
+ "error.empty_file": "El archivo está vacío (0 bytes). Un archivo creado con «Nuevo» en el menú contextual sigue vacío hasta que lo abres en su aplicación y lo guardas",
"format_request.request": "Solicitar este formato",
"format_request.notice_title": "Filee aún no puede convertir archivos {0}",
"format_request.notice_text": "Cuéntanos qué formato necesitas.\nLas solicitudes determinan qué formatos admitirá Filee a continuación.\nLos archivos cifrados o con protección de copia (DRM) no se pueden convertir, sea cual sea su formato.",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 9325caa2..f00356df 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -68,6 +68,7 @@
"toast.cancel": "취소",
"error.unsupported_source": "지원하지 않는 파일 형식이에요",
+ "error.empty_file": "빈 파일이에요(0바이트). 우클릭 메뉴의 “새로 만들기”로 만든 파일은 앱에서 열어 저장해야 내용이 생겨요",
"format_request.request": "이 형식 요청하기",
"format_request.notice_title": "아직 {0} 파일은 변환할 수 없어요",
"format_request.notice_text": "필요한 형식을 알려주세요.\n요청을 보고 다음에 지원할 형식을 정해요.\n암호화되거나 DRM이 걸린 파일은 변환할 수 없어요.",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 83c4309e..caa4bcee 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -68,6 +68,7 @@
"toast.cancel": "Anuluj",
"error.unsupported_source": "Ten typ pliku nie jest obsługiwany",
+ "error.empty_file": "Plik jest pusty (0 bajtów). Plik utworzony przez „Nowy” w menu kontekstowym pozostaje pusty, dopóki nie otworzysz go w jego aplikacji i nie zapiszesz",
"format_request.request": "Poproś o ten format",
"format_request.notice_title": "Filee nie potrafi jeszcze konwertować plików {0}",
"format_request.notice_text": "Napisz, jakiego formatu potrzebujesz.\nNa podstawie próśb wybieramy kolejne obsługiwane formaty.\nPlików zaszyfrowanych lub chronionych przed kopiowaniem (DRM) nie da się konwertować, niezależnie od formatu.",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index d800805c..582ee7b2 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -68,6 +68,7 @@
"toast.cancel": "取消",
"error.unsupported_source": "不支持此文件类型",
+ "error.empty_file": "文件是空的(0 字节)。用右键菜单“新建”创建的文件,要在对应的应用中打开并保存后才有内容",
"format_request.request": "请求支持此格式",
"format_request.notice_title": "Filee 暂时无法转换 {0} 文件",
"format_request.notice_text": "告诉我们你需要的格式。\n我们会根据请求决定接下来支持哪些格式。\n加密或有复制保护 (DRM) 的文件,无论什么格式都无法转换。",
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 5edecdae..8c333999 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -139,7 +139,8 @@ public sealed class JobQueue : IAsyncDisposable
async (i, _) =>
{
var file = job.Files[i];
- if (FormatRegistry.Detect(file.SourcePath)?.Id == "pdf")
+ // An empty PDF goes the long way, where it fails as empty instead of breaking the whole merge.
+ if (FormatRegistry.Detect(file.SourcePath)?.Id == "pdf" && !IsEmptyFile(file.SourcePath))
{
// Already a PDF, merged as it is: its pages can't be turned (only images going into it can).
if (job.Preset.Image.TurnsOrMirrors)
@@ -189,6 +190,7 @@ public sealed class JobQueue : IAsyncDisposable
var file = job.Files[i];
// A TIFF joins as it is, unless it is to be turned: then it goes through the engine like the rest.
parts[i] = FormatRegistry.Detect(file.SourcePath)?.Id == "tiff" && !job.Preset.Image.TurnsOrMirrors
+ && !IsEmptyFile(file.SourcePath)
? [file.SourcePath]
: await RunFileAsync(job, file, i + 1, planner, workDir, finalOutput: false, intermediate: "tiff");
});
@@ -303,6 +305,20 @@ public sealed class JobQueue : IAsyncDisposable
}
}
+ /// <summary>A file (not a folder) with nothing in it. Combining still packs such a file as it is.</summary>
+ private static bool IsEmptyFile(string path)
+ {
+ try
+ {
+ var info = new FileInfo(path);
+ return info.Exists && info.Length == 0;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
+ {
+ return false;
+ }
+ }
+
/// <summary>Gives the outputs the creation and modification dates of the source (<see cref="OutputRule.KeepDates"/>).</summary>
private void CopyDates(string source, IEnumerable<string> outputs)
{
@@ -344,6 +360,10 @@ public sealed class JobQueue : IAsyncDisposable
var source = FormatRegistry.Detect(file.SourcePath);
if (source is null)
return Fail(file, "error.unsupported_source", "." + FormatRegistry.ExtensionOf(file.SourcePath));
+ // A file just made with "New" in the file manager stays 0 bytes until its app saves it: no engine can read it,
+ // and their errors ("Central Directory corrupt") don't say why.
+ if (IsEmptyFile(file.SourcePath))
+ return Fail(file, "error.empty_file", null);
var target = !finalOutput ? intermediate
: job.Preset.TargetFormat == BuiltInData.SameAsSource ? source.Id
diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs
index 7d2c6af6..926153f7 100644
--- a/tests/Filee.Cli.Tests/CliTests.cs
+++ b/tests/Filee.Cli.Tests/CliTests.cs
@@ -124,6 +124,18 @@ public sealed class CliTests : IDisposable
Assert.Contains("fail", output);
}
+ [Fact]
+ public async Task An_empty_file_says_it_is_empty()
+ {
+ var empty = Path.Combine(_folder, "new.docx");
+ File.WriteAllBytes(empty, []);
+
+ var (code, output, _) = await Run("convert", empty, "--to", "pdf");
+
+ Assert.Equal(Cli.SomeFailed, code);
+ Assert.Contains("new.docx: The file is empty (0 bytes).", output);
+ }
+
[Theory]
[InlineData(new[] { "convert", "a.png" }, "--to")]
[InlineData(new[] { "convert", "a.png", "--to", "jpg", "--preset", "x" }, "--to")]
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index f4e20cb2..db0bbc43 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -222,6 +222,57 @@ public class JobQueueTests
Assert.Equal("error.unsupported_source", job.Files[1].ErrorKey);
}
+ [Fact]
+ public async Task An_empty_file_fails_as_empty_before_any_engine_sees_it()
+ {
+ // A DOCX made with "New" in Explorer is 0 bytes until Word saves it (#157).
+ using var dir = new TempDir();
+ var empty = dir.File("new.docx", "");
+ var ok = dir.File("a.jpg");
+ var converter = new FakeConverter("docx-writer", new ConversionEdge("docx", "pdf"), new ConversionEdge("jpg", "pdf"));
+ await using var queue = new JobQueue(new ConverterCatalog([converter]));
+
+ var job = await Run(queue, [empty, ok], new Preset { TargetFormat = "pdf" });
+
+ Assert.Equal(JobState.CompletedWithErrors, job.State);
+ Assert.Equal(FileState.Failed, job.Files[0].State);
+ Assert.Equal("error.empty_file", job.Files[0].ErrorKey);
+ Assert.Null(job.Files[0].ErrorDetail);
+ Assert.False(File.Exists(Path.Combine(dir.Path, "new.pdf")));
+ Assert.Equal(FileState.Done, job.Files[1].State);
+ }
+
+ [Fact]
+ public async Task An_empty_pdf_fails_as_empty_instead_of_breaking_the_merge()
+ {
+ using var dir = new TempDir();
+ var photo = dir.File("1.jpg");
+ var empty = dir.File("2.pdf", "");
+ var merger = new FakeMerger();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("pdfsharp", new ConversionEdge("jpg", "pdf"))]), merger);
+
+ var job = await Run(queue, [photo, empty], new Preset { TargetFormat = "pdf", Pdf = { MergeIntoSingle = true } });
+
+ Assert.Equal("error.empty_file", job.Files[1].ErrorKey);
+ Assert.Equal(["1.pdf"], merger.Inputs.Select(Path.GetFileName));
+ }
+
+ [Fact]
+ public async Task Combine_still_packs_empty_files_and_folders()
+ {
+ // Packing changes nothing: an empty file goes into the archive as it is.
+ using var dir = new TempDir();
+ var empty = dir.File("empty.txt", "");
+ var folder = Directory.CreateDirectory(Path.Combine(dir.Path, "folder")).FullName;
+ var combiner = new FakeCombiner();
+ await using var queue = new JobQueue(new ConverterCatalog([]), combiner: combiner);
+
+ var job = await Run(queue, [empty, folder], new Preset { TargetFormat = "zip", Archive = { CombineIntoOne = true } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal([empty, folder], combiner.Inputs);
+ }
+
[Fact]
public async Task No_route_is_reported()
{