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.

Jobs can save files from a browser before converting them

KnifeLemon78a602bfde35
diff --git a/src/Filee.Core/Conversion/ConversionJob.cs b/src/Filee.Core/Conversion/ConversionJob.cs
index fcd1f06c..0d9d1ea2 100644
--- a/src/Filee.Core/Conversion/ConversionJob.cs
+++ b/src/Filee.Core/Conversion/ConversionJob.cs
@@ -27,7 +27,11 @@ public enum FileState
/// <summary>Result for one source file of a job.</summary>
public sealed class FileResult
{
- public required string SourcePath { get; init; }
+ /// <summary>
+ /// The file converted. For a source the job fetches first (<see cref="ConversionJob.Fetcher"/>) a placeholder
+ /// until it has been saved, then where it was saved.
+ /// </summary>
+ public required string SourcePath { get; set; }
public FileState State { get; set; } = FileState.Pending;
public double Progress { get; set; }
public List<string> Outputs { get; } = [];
@@ -50,17 +54,23 @@ public sealed class ConversionJob
{
private readonly CancellationTokenSource _cts = new();
- public ConversionJob(IReadOnlyList<string> sources, Preset preset, string presetDisplayName)
+ /// <param name="fetcher">Saves sources that aren't files yet before they are converted (files from a browser).</param>
+ public ConversionJob(IReadOnlyList<string> sources, Preset preset, string presetDisplayName, ISourceFetcher? fetcher = null)
{
- Sources = sources;
Preset = preset.Clone(); // later edits of the preset must not affect a running job
PresetDisplayName = presetDisplayName;
+ Fetcher = fetcher;
Files = sources.Select(s => new FileResult { SourcePath = s }).ToList();
}
public string Id { get; } = Guid.NewGuid().ToString("N")[..10];
public DateTime CreatedAt { get; } = DateTime.Now;
- public IReadOnlyList<string> Sources { get; }
+
+ /// <summary>The source files, as <see cref="FileResult.SourcePath"/> currently names them.</summary>
+ public IReadOnlyList<string> Sources => Files.Select(f => f.SourcePath).ToList();
+
+ /// <summary>Saves the sources that aren't files yet when the job runs; null when all of them are files.</summary>
+ public ISourceFetcher? Fetcher { get; }
public Preset Preset { get; }
public string PresetDisplayName { get; }
public IReadOnlyList<FileResult> Files { get; }
@@ -77,3 +87,23 @@ public sealed class ConversionJob
/// <summary>Requests cancellation. Running engines stop as soon as they can.</summary>
public void Cancel() => _cts.Cancel();
}
+
+/// <summary>
+/// Brings sources that aren't files yet onto disk when their job runs: files dragged out of a web browser are saved
+/// (or downloaded) then, so the download shows its progress and errors like the conversion.
+/// </summary>
+public interface ISourceFetcher
+{
+ /// <summary>True for a source this fetcher saves (the others are files already).</summary>
+ bool Fetches(string source);
+
+ /// <summary>Saves the file <paramref name="source"/> stands for and returns its path.</summary>
+ /// <exception cref="ConversionRefusedException">A reason the user can act on (a web page instead of a file, …).</exception>
+ Task<string> FetchAsync(string source, IProgress<double> progress, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// The job is over (finished, failed or cancelled before it ran): delete what only the conversion needed. Called
+ /// once, before <see cref="JobQueue.JobFinished"/>.
+ /// </summary>
+ void Release(ConversionJob job);
+}
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 03aa3dc0..55c3e20e 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -50,9 +50,10 @@ public sealed class JobQueue : IAsyncDisposable
public bool IsBusy => Volatile.Read(ref _busy) > 0;
/// <summary>Adds a job to the queue and returns it immediately.</summary>
- public ConversionJob Enqueue(IReadOnlyList<string> sources, Preset preset, string presetDisplayName)
+ /// <param name="fetcher">Saves sources that aren't files yet (files from a browser) when the job runs.</param>
+ public ConversionJob Enqueue(IReadOnlyList<string> sources, Preset preset, string presetDisplayName, ISourceFetcher? fetcher = null)
{
- var job = new ConversionJob(sources, preset, presetDisplayName);
+ var job = new ConversionJob(sources, preset, presetDisplayName, fetcher);
Interlocked.Increment(ref _busy); // until the worker is done with it
_channel.Writer.TryWrite(job);
JobUpdated?.Invoke(this, job);
@@ -82,6 +83,9 @@ public sealed class JobQueue : IAsyncDisposable
Directory.CreateDirectory(workDir);
try
{
+ if (job.Fetcher is { } fetcher)
+ await FetchSourcesAsync(job, fetcher);
+
var planner = _catalog.CreatePlanner();
var merge = job.Preset.Pdf.MergeIntoSingle
&& job.Preset.TargetFormat == "pdf"
@@ -124,12 +128,83 @@ public sealed class JobQueue : IAsyncDisposable
foreach (var output in job.Outputs)
_reservedOutputs.Remove(output);
TryDelete(workDir);
+ Release(job);
}
Notify(job);
JobFinished?.Invoke(this, job);
}
+ /// <summary>Share of a fetched file's progress that saving it takes; converting it fills the rest.</summary>
+ private const double FetchShare = 0.5;
+
+ /// <summary>
+ /// Saves the sources the job's fetcher brings (files dragged from a browser) before anything is converted. A file
+ /// that can't be saved fails with its reason; the others still convert.
+ /// </summary>
+ private async Task FetchSourcesAsync(ConversionJob job, ISourceFetcher fetcher)
+ {
+ var files = job.Files.Where(f => fetcher.Fetches(f.SourcePath)).ToList();
+ await Parallel.ForEachAsync(files, new ParallelOptions { MaxDegreeOfParallelism = 4 }, async (file, _) =>
+ {
+ file.State = FileState.Running;
+ Notify(job);
+ var progress = new Progress<double>(p =>
+ {
+ var value = Math.Clamp(p, 0, 1) * FetchShare;
+ if (value <= file.Progress || file.State != FileState.Running)
+ return;
+ file.Progress = value;
+ Notify(job);
+ });
+ try
+ {
+ file.SourcePath = await fetcher.FetchAsync(file.SourcePath, progress, job.CancellationToken);
+ file.State = FileState.Pending;
+ file.Progress = FetchShare;
+ }
+ catch (OperationCanceledException)
+ {
+ file.State = FileState.Cancelled;
+ }
+ catch (ConversionRefusedException ex)
+ {
+ _log.LogInformation("Saving {File} was refused: {Reason}", file.SourcePath, ex.Message);
+ FailFetch(file, ex.ErrorKey, ex.Detail);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Saving {File} failed", file.SourcePath);
+ FailFetch(file, "error.web_download_failed", ex.Message);
+ }
+ Notify(job);
+ });
+
+ static void FailFetch(FileResult file, string key, string? detail)
+ {
+ file.State = FileState.Failed;
+ file.ErrorKey = key;
+ file.ErrorDetail = detail;
+ file.Progress = 1;
+ }
+ }
+
+ /// <summary>A file that didn't get as far as being converted (saving it failed or was cancelled).</summary>
+ private static bool Stopped(FileResult file) => file.State is FileState.Failed or FileState.Cancelled;
+
+ /// <summary>Lets the job's fetcher clean up (originals that aren't kept).</summary>
+ private void Release(ConversionJob job)
+ {
+ try
+ {
+ job.Fetcher?.Release(job);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Cleaning up after job {Job} failed", job.Id);
+ }
+ }
+
/// <summary>Converts every file to PDF in the work directory, then merges them into one output.</summary>
private async Task RunMergedAsync(ConversionJob job, RoutePlanner planner, string workDir)
{
@@ -139,6 +214,8 @@ public sealed class JobQueue : IAsyncDisposable
async (i, _) =>
{
var file = job.Files[i];
+ if (Stopped(file))
+ return;
// 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))
{
@@ -188,6 +265,8 @@ public sealed class JobQueue : IAsyncDisposable
async (i, _) =>
{
var file = job.Files[i];
+ if (Stopped(file))
+ return;
// 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)
@@ -232,7 +311,7 @@ public sealed class JobQueue : IAsyncDisposable
{
var format = FormatRegistry.Get(job.Preset.TargetFormat);
var inputs = new List<FileResult>();
- foreach (var file in job.Files)
+ foreach (var file in job.Files.Where(f => !Stopped(f)))
{
// Folders (from the command line; drops deliver files) are packed with their content.
if (File.Exists(file.SourcePath) || Directory.Exists(file.SourcePath))
@@ -357,6 +436,8 @@ public sealed class JobQueue : IAsyncDisposable
string intermediate = "pdf")
{
var ct = job.CancellationToken;
+ if (Stopped(file))
+ return [];
var source = FormatRegistry.Detect(file.SourcePath);
if (source is null)
return Fail(file, "error.unsupported_source", "." + FormatRegistry.ExtensionOf(file.SourcePath));
@@ -397,6 +478,8 @@ public sealed class JobQueue : IAsyncDisposable
file.State = FileState.Running;
Notify(job);
+ // A file saved from a browser first has part of its progress already.
+ var floor = file.Progress;
try
{
@@ -417,7 +500,7 @@ public sealed class JobQueue : IAsyncDisposable
var progress = new Progress<double>(p =>
{
// Reports arrive on the thread pool, possibly out of order: progress only moves forward.
- var value = (stepIndex + Math.Clamp(p, 0, 1)) / route.Steps.Count;
+ var value = floor + (1 - floor) * (stepIndex + Math.Clamp(p, 0, 1)) / route.Steps.Count;
if (value <= file.Progress)
return;
file.Progress = value;
@@ -546,6 +629,7 @@ public sealed class JobQueue : IAsyncDisposable
if (job.CancellationToken.IsCancellationRequested)
{
job.State = JobState.Cancelled;
+ Release(job);
Notify(job);
JobFinished?.Invoke(this, job);
continue;
diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.cs
index 06fc428c..da8bb737 100644
--- a/src/Filee.Core/Platform/IPlatformServices.cs
+++ b/src/Filee.Core/Platform/IPlatformServices.cs
@@ -72,6 +72,12 @@ public interface IPlatformServices
/// </summary>
string DescribeForegroundWindow() => "";
+ /// <summary>
+ /// The user's Downloads folder, where files dragged from a browser are saved unless Settings says otherwise.
+ /// Windows asks the shell (the folder can be moved); elsewhere ~/Downloads.
+ /// </summary>
+ string DownloadsFolder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
+
/// <summary>System drag threshold in the same units as screen coordinates.</summary>
int SystemDragThreshold { get; }
diff --git a/src/Filee.Core/Presets/OutputPathResolver.cs b/src/Filee.Core/Presets/OutputPathResolver.cs
index bdf3c108..3c9c47e8 100644
--- a/src/Filee.Core/Presets/OutputPathResolver.cs
+++ b/src/Filee.Core/Presets/OutputPathResolver.cs
@@ -24,7 +24,9 @@ public static class OutputPathResolver
public static string? Resolve(OutputRule rule, Tokens tokens, string targetExtension,
Func<string, bool> exists, string? suffix = null)
{
- var sourceDir = Path.GetDirectoryName(Path.GetFullPath(tokens.SourcePath)) ?? "";
+ var sourceDir = string.IsNullOrWhiteSpace(rule.SourceFolder)
+ ? Path.GetDirectoryName(Path.GetFullPath(tokens.SourcePath)) ?? ""
+ : Path.GetFullPath(rule.SourceFolder);
var dir = rule.Location switch
{
OutputLocation.Subfolder => Path.Combine(sourceDir, Sanitize(ExpandPattern(rule.SubfolderName, tokens), "converted")),
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
index 38a7897f..fdb2ee94 100644
--- a/src/Filee.Core/Presets/OutputRule.cs
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -64,6 +64,14 @@ public sealed class OutputRule
/// </summary>
public bool KeepDates { get; set; }
+ /// <summary>
+ /// The folder "next to the source" means for this job, instead of the source's own: files dragged from a browser
+ /// are saved there (or, when only the converted file is kept, into a work folder that is deleted afterwards).
+ /// Set per job, never saved with a preset.
+ /// </summary>
+ [System.Text.Json.Serialization.JsonIgnore]
+ public string? SourceFolder { get; set; }
+
public OutputRule Clone()
{
var clone = (OutputRule)MemberwiseClone();
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 79863577..bd612069 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -135,6 +135,9 @@ public sealed class AppSettings
/// <summary>Where presets set to "Default" save (Settings → General).</summary>
public DefaultOutputSettings DefaultOutput { get; set; } = new();
+ /// <summary>Where files dragged from a web browser are saved (Settings → General).</summary>
+ public BrowserDropSettings BrowserDrops { get; set; } = new();
+
/// <summary>
/// Optional engines the user already has: package id ("ffmpeg", "calibre", …) → the program they picked. Used
/// instead of Filee's download (Settings → Engines).
@@ -218,3 +221,13 @@ public sealed class DefaultOutputSettings
public string CustomFolder { get; set; } = "";
}
+
+/// <summary>Files dragged out of a web browser (Settings → General).</summary>
+public sealed class BrowserDropSettings
+{
+ /// <summary>Where they are saved; empty means the user's Downloads folder (looked up each time, as it can move).</summary>
+ public string Folder { get; set; } = "";
+
+ /// <summary>Keep only the converted file: the original goes into a work folder and is deleted after the conversion.</summary>
+ public bool SaveOnlyConverted { get; set; }
+}
diff --git a/src/Filee.Core/Web/BrowserDrag.cs b/src/Filee.Core/Web/BrowserDrag.cs
new file mode 100644
index 00000000..256c7795
--- /dev/null
+++ b/src/Filee.Core/Web/BrowserDrag.cs
@@ -0,0 +1,152 @@
+// Decides what in a drag from a web browser is a file to convert. The rules, in order:
+//
+// 1. Files the browser hands over itself (the picture's own bytes as a Windows virtual file, Firefox's temporary
+// copy): taken as they are. Internet shortcuts (".url", what any dragged link also comes with) and programs are
+// not taken.
+// 2. A picture (the dragged HTML fragment is one <img> and no text; a Firefox file promise): its address.
+// 3. A download a page offers (DownloadURL): its address, named as the page says.
+// 4. Links: only when the address ends in an extension Filee converts (".pdf", ".docx", ".png"), never a web page
+// (".html", ".php", no extension). The server's answer is checked again when downloading.
+// 5. Nothing else, but the drag carries the picture's pixels (a blob: address Filee can't fetch): those, as PNG.
+//
+// Plain text is never read: a selected address is text, not a file.
+
+using Filee.Core.Formats;
+
+namespace Filee.Core.Web;
+
+/// <summary>The parts of a drag Filee reads for files from a browser.</summary>
+public sealed class BrowserDragContent
+{
+ /// <summary>Files the drag hands over with their bytes (virtual files, a browser's temporary copy).</summary>
+ public IReadOnlyList<WebDropItem> Files { get; init; } = [];
+
+ /// <summary>Text of the address formats, by format name (<see cref="BrowserDragFormats"/>).</summary>
+ public IReadOnlyDictionary<string, string> Texts { get; init; } = new Dictionary<string, string>();
+
+ /// <summary>The picture's pixels from the drag itself, made into a file on request; null when there are none.</summary>
+ public Func<WebDropItem?>? Picture { get; init; }
+
+ /// <summary>True when the drag names a web address in a link format: it comes from a browser.</summary>
+ public bool HasAddress => AddressFormatNames.Any(f => Texts.TryGetValue(f, out var text) && !string.IsNullOrWhiteSpace(text));
+
+ /// <summary>The formats that carry a web address (by native name).</summary>
+ public static IReadOnlyList<string> AddressFormatNames { get; } =
+ [
+ BrowserDragFormats.DownloadUrlFormat, BrowserDragFormats.MozFilePromiseUrl, BrowserDragFormats.MozUrl,
+ BrowserDragFormats.UniformResourceLocatorW, BrowserDragFormats.UniformResourceLocator, BrowserDragFormats.NetscapeUrl,
+ BrowserDragFormats.MacUrl, BrowserDragFormats.UriList,
+ ];
+
+ public string? Text(string format) =>
+ Texts.TryGetValue(format, out var text) && !string.IsNullOrWhiteSpace(text) ? text : null;
+}
+
+public static class BrowserDrag
+{
+ /// <summary>
+ /// The files in <paramref name="content"/>, in the order they were dragged; empty when it holds none (a page link,
+ /// a text selection). Files of <see cref="BrowserDragContent.Files"/> not returned are disposed.
+ /// </summary>
+ public static IReadOnlyList<WebDropItem> Files(BrowserDragContent content)
+ {
+ var handed = new List<WebDropItem>();
+ foreach (var file in content.Files)
+ {
+ if (WebFileNames.IsBlocked(file.Name))
+ file.Dispose();
+ else
+ handed.Add(file);
+ }
+ if (handed.Count > 0)
+ return handed;
+
+ var picture = content.Picture is not null;
+ var html = content.Text(BrowserDragFormats.Html) ?? content.Text(BrowserDragFormats.WindowsHtml) ?? content.Text(BrowserDragFormats.MacHtml);
+ if (BrowserDragFormats.ImageOnly(html) is { } src && Address(src, image: true, Base(content)) is { } image)
+ return [image];
+
+ if (content.Text(BrowserDragFormats.MozFilePromiseUrl) is { } promised
+ && Address(promised.Trim(), image: true, null, content.Text(BrowserDragFormats.MozFilePromiseName)?.Trim()) is { } promise)
+ return [promise];
+
+ if (BrowserDragFormats.ParseDownloadUrl(content.Text(BrowserDragFormats.DownloadUrlFormat)) is { } download
+ && Address(download.Url.OriginalString, image: false, null, download.Name, download.Mime) is { } offered)
+ return [offered];
+
+ var items = new List<WebDropItem>();
+ var seen = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var url in Links(content))
+ {
+ if (seen.Add(url) && Address(url, picture, null) is { } item)
+ items.Add(item);
+ }
+ if (items.Count > 0)
+ return items;
+
+ return picture && content.HasAddress && content.Picture!() is { } pixels ? [pixels] : [];
+ }
+
+ /// <summary>The addresses of the link formats, the most precise first.</summary>
+ private static IEnumerable<string> Links(BrowserDragContent content)
+ {
+ foreach (var url in BrowserDragFormats.ParseMozUrl(content.Text(BrowserDragFormats.MozUrl)))
+ yield return url;
+ foreach (var format in new[] { BrowserDragFormats.UniformResourceLocatorW, BrowserDragFormats.UniformResourceLocator, BrowserDragFormats.MacUrl })
+ {
+ if (content.Text(format) is { } text)
+ yield return text.Trim();
+ }
+ foreach (var url in BrowserDragFormats.ParseMozUrl(content.Text(BrowserDragFormats.NetscapeUrl)))
+ yield return url;
+ foreach (var url in BrowserDragFormats.ParseUriList(content.Text(BrowserDragFormats.UriList)))
+ yield return url;
+ }
+
+ /// <summary>The page address, for a picture whose src is relative.</summary>
+ private static Uri? Base(BrowserDragContent content) =>
+ Links(content).Select(u => Uri.TryCreate(u, UriKind.Absolute, out var uri) ? uri : null).FirstOrDefault(u => u is not null);
+
+ /// <summary>
+ /// The file at <paramref name="address"/>, or null when it isn't one Filee takes: not http(s) or data:, a web
+ /// page, a program, or a link whose type can't be told before downloading.
+ /// </summary>
+ /// <param name="image">The address is a picture's: taken even without an extension (".jpg" stands in until the bytes say).</param>
+ internal static WebDropItem? Address(string address, bool image, Uri? pageAddress, string? name = null, string? mime = null)
+ {
+ if (address.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
+ {
+ if (BrowserDragFormats.DecodeDataUrl(address) is not { } data
+ || WebFormats.ExtensionForMime(data.Mime) is not { } dataExtension
+ || FormatRegistry.FindByExtension(dataExtension) is null)
+ return null;
+ return WebDropItem.FromBytes(WebFileNames.WithExtension(name ?? "image", dataExtension), data.Bytes, data.Mime);
+ }
+
+ // "/img/a.png" and "//cdn/a.png" are relative to the page (on Unix .NET would take the first for a file path).
+ Uri? url = null;
+ if (address.Contains("://", StringComparison.Ordinal))
+ Uri.TryCreate(address, UriKind.Absolute, out url);
+ else if (pageAddress is not null)
+ Uri.TryCreate(pageAddress, address, out url);
+ if (url is null || !WebDownloader.IsWebAddress(url))
+ return null;
+
+ var fileName = WebFileNames.Sanitize(name ?? WebFileNames.FromUrl(url), image ? "image" : "download");
+ if (WebFileNames.IsBlocked(fileName))
+ return null;
+ if (WebFileNames.IsPage(fileName))
+ {
+ if (!image)
+ return null;
+ fileName = FormatRegistry.NameWithoutExtension(fileName);
+ }
+ if (FormatRegistry.Detect(fileName) is not null)
+ return WebDropItem.FromAddress(fileName, url);
+ if (image || WebFormats.IsImage(mime))
+ return WebDropItem.FromAddress(WebFileNames.WithExtension(fileName, WebFormats.ExtensionForMime(mime) ?? "jpg"), url);
+ if (WebFormats.ExtensionForMime(mime) is { } extension && FormatRegistry.FindByExtension(extension) is not null)
+ return WebDropItem.FromAddress(WebFileNames.WithExtension(fileName, extension), url);
+ return null;
+ }
+}
diff --git a/src/Filee.Core/Web/BrowserDragFormats.cs b/src/Filee.Core/Web/BrowserDragFormats.cs
new file mode 100644
index 00000000..c8a8a34c
--- /dev/null
+++ b/src/Filee.Core/Web/BrowserDragFormats.cs
@@ -0,0 +1,265 @@
+// The forms web browsers put a dragged picture, link or download into: pure parsing, so it can be tested anywhere.
+// The App reads the raw formats from the drag (Avalonia) and DraggedWebItems decides what in them is a file.
+//
+// FileGroupDescriptorW Windows: names (and sizes) of files that exist only inside the source app, whose
+// bytes come with FileContents (Chrome and Edge: a dragged picture; any link: a ".url").
+// UniformResourceLocatorW Windows: the link or picture address, UTF-16.
+// text/x-moz-url Firefox (and Chrome, for Firefox's sake): "address\ntitle" pairs, UTF-16.
+// _NETSCAPE_URL Linux: "address\ntitle", UTF-8.
+// text/uri-list RFC 2483: one address per line, "#" lines are comments.
+// DownloadURL Chrome, when a page sets it (Gmail attachments): "type:name:address".
+// application/x-moz-file-promise-url (+ -dest-filename) Firefox: the picture a drag promises, and its name.
+// public.url / public.url-name macOS: the address and its title.
+// text/html, HTML Format the dragged fragment; a picture drag is one <img> (maybe inside a link), no text.
+
+using System.Buffers.Binary;
+using System.Net;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Filee.Core.Web;
+
+/// <summary>One entry of a FileGroupDescriptorW.</summary>
+/// <param name="Name">The file's name (may contain a relative folder, "photos\a.jpg").</param>
+/// <param name="Size">Its size when the source says it.</param>
+/// <param name="IsFolder">A folder entry (no contents of its own).</param>
+public sealed record FileDescriptor(string Name, long? Size, bool IsFolder);
+
+/// <summary>A DownloadURL value: the file's media type, its name and where it is.</summary>
+public sealed record DownloadUrl(string Mime, string Name, Uri Url);
+
+public static partial class BrowserDragFormats
+{
+ public const string FileGroupDescriptorW = "FileGroupDescriptorW";
+ public const string UniformResourceLocatorW = "UniformResourceLocatorW";
+ public const string UniformResourceLocator = "UniformResourceLocator";
+ public const string MozUrl = "text/x-moz-url";
+ public const string NetscapeUrl = "_NETSCAPE_URL";
+ public const string UriList = "text/uri-list";
+ public const string DownloadUrlFormat = "DownloadURL";
+ public const string MozFilePromiseUrl = "application/x-moz-file-promise-url";
+ public const string MozFilePromiseName = "application/x-moz-file-promise-dest-filename";
+ public const string MacUrl = "public.url";
+ public const string MacUrlName = "public.url-name";
+ public const string Html = "text/html";
+ public const string WindowsHtml = "HTML Format";
+ public const string MacHtml = "public.html";
+
+ // FILEDESCRIPTORW: dwFlags, clsid, sizel, pointl, dwFileAttributes, three FILETIMEs, nFileSizeHigh/Low,
+ // cFileName[MAX_PATH] (UTF-16) = 592 bytes, after a 4-byte count.
+ private const int DescriptorSize = 592;
+ private const int SizeHighOffset = 64;
+ private const int AttributesOffset = 36;
+ private const int NameOffset = 72;
+ private const int NameChars = 260;
+ private const uint FdAttributes = 0x4;
+ private const uint FdFileSize = 0x40;
+ private const uint FileAttributeDirectory = 0x10;
+
+ /// <summary>The entries of a FileGroupDescriptorW; empty when the data is cut short or makes no sense.</summary>
+ public static IReadOnlyList<FileDescriptor> ParseFileGroupDescriptor(ReadOnlySpan<byte> data)
+ {
+ if (data.Length < 4)
+ return [];
+ var count = BinaryPrimitives.ReadUInt32LittleEndian(data);
+ if (count == 0 || count > 10_000 || data.Length < 4 + (long)count * DescriptorSize)
+ return [];
+ var entries = new List<FileDescriptor>((int)count);
+ for (var i = 0; i < (int)count; i++)
+ {
+ var entry = data.Slice(4 + i * DescriptorSize, DescriptorSize);
+ var flags = BinaryPrimitives.ReadUInt32LittleEndian(entry);
+ var nameBytes = entry.Slice(NameOffset, NameChars * 2);
+ var name = Encoding.Unicode.GetString(nameBytes);
+ var end = name.IndexOf('\0');
+ if (end >= 0)
+ name = name[..end];
+ long? size = (flags & FdFileSize) != 0
+ ? (long)(((ulong)BinaryPrimitives.ReadUInt32LittleEndian(entry[SizeHighOffset..]) << 32)
+ | BinaryPrimitives.ReadUInt32LittleEndian(entry[(SizeHighOffset + 4)..]))
+ : null;
+ var folder = (flags & FdAttributes) != 0
+ && (BinaryPrimitives.ReadUInt32LittleEndian(entry[AttributesOffset..]) & FileAttributeDirectory) != 0;
+ if (name.Length > 0)
+ entries.Add(new FileDescriptor(name, size, folder));
+ }
+ return entries;
+ }
+
+ /// <summary>Builds a FileGroupDescriptorW (for tests and fakes).</summary>
+ public static byte[] BuildFileGroupDescriptor(IReadOnlyList<FileDescriptor> entries)
+ {
+ var data = new byte[4 + entries.Count * DescriptorSize];
+ BinaryPrimitives.WriteUInt32LittleEndian(data, (uint)entries.Count);
+ for (var i = 0; i < entries.Count; i++)
+ {
+ var entry = data.AsSpan(4 + i * DescriptorSize, DescriptorSize);
+ var flags = FdAttributes | (entries[i].Size is null ? 0 : FdFileSize);
+ BinaryPrimitives.WriteUInt32LittleEndian(entry, flags);
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[AttributesOffset..], entries[i].IsFolder ? FileAttributeDirectory : 0x80);
+ if (entries[i].Size is { } size)
+ {
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[SizeHighOffset..], (uint)(size >> 32));
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[(SizeHighOffset + 4)..], (uint)size);
+ }
+ var name = entries[i].Name.Length >= NameChars ? entries[i].Name[..(NameChars - 1)] : entries[i].Name;
+ Encoding.Unicode.GetBytes(name).CopyTo(entry[NameOffset..]);
+ }
+ return data;
+ }
+
+ /// <summary>
+ /// Text from a drag format's bytes: UTF-16 (little endian, as Windows and Firefox write it; with or without a BOM)
+ /// or UTF-8, up to the first NUL (Windows pads its memory blocks).
+ /// </summary>
+ public static string DecodeText(byte[]? data)
+ {
+ if (data is null || data.Length == 0)
+ return "";
+ string text;
+ if (data.Length >= 2 && data[0] == 0xFF && data[1] == 0xFE)
+ text = Encoding.Unicode.GetString(data, 2, (data.Length - 2) & ~1);
+ else if (data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF)
+ text = Encoding.UTF8.GetString(data, 3, data.Length - 3);
+ else if (LooksLikeUtf16(data))
+ text = Encoding.Unicode.GetString(data, 0, data.Length & ~1);
+ else
+ text = Encoding.UTF8.GetString(data);
+ var end = text.IndexOf('\0');
+ return end >= 0 ? text[..end] : text;
+ }
+
+ /// <summary>
+ /// ASCII text in UTF-16 has a zero in every odd byte; UTF-8 text has none. The zeros Windows pads a memory block
+ /// with don't count.
+ /// </summary>
+ private static bool LooksLikeUtf16(byte[] data)
+ {
+ var length = data.Length;
+ while (length > 0 && data[length - 1] == 0)
+ length--;
+ var pairs = Math.Min((length + 1) / 2, 64);
+ if (pairs == 0)
+ return false;
+ var zeros = 0;
+ for (var i = 0; i < pairs; i++)
+ {
+ if (i * 2 + 1 >= length || data[i * 2 + 1] == 0)
+ zeros++;
+ }
+ return zeros * 2 >= pairs;
+ }
+
+ /// <summary>The addresses in a text/x-moz-url or _NETSCAPE_URL value: lines alternate address and title.</summary>
+ public static IReadOnlyList<string> ParseMozUrl(string? text)
+ {
+ var lines = Lines(text);
+ var urls = new List<string>();
+ for (var i = 0; i < lines.Count; i += 2)
+ urls.Add(lines[i]);
+ return urls;
+ }
+
+ /// <summary>The addresses in a text/uri-list value (comments and blank lines skipped).</summary>
+ public static IReadOnlyList<string> ParseUriList(string? text) =>
+ Lines(text).Where(line => !line.StartsWith('#')).ToList();
+
+ /// <summary>A DownloadURL value ("image/png:photo.png:https://…"), or null.</summary>
+ public static DownloadUrl? ParseDownloadUrl(string? text)
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ return null;
+ text = text.Trim();
+ var first = text.IndexOf(':');
+ var second = first < 0 ? -1 : text.IndexOf(':', first + 1);
+ if (first <= 0 || second < 0)
+ return null;
+ var mime = text[..first];
+ var name = text[(first + 1)..second];
+ var url = text[(second + 1)..];
+ if (!mime.Contains('/') || name.Length == 0 || !Uri.TryCreate(url, UriKind.Absolute, out var uri))
+ return null;
+ return new DownloadUrl(mime, name, uri);
+ }
+
+ /// <summary>The URL= line of an Internet shortcut (".url" file contents), or null.</summary>
+ public static string? ParseInternetShortcut(string? text) =>
+ Lines(text).FirstOrDefault(line => line.StartsWith("URL=", StringComparison.OrdinalIgnoreCase))?[4..].Trim();
+
+ /// <summary>
+ /// The picture a dragged HTML fragment is: the src of its only &lt;img&gt;, when the fragment shows no text (a
+ /// selection of text with pictures in it is not a picture). Windows' "HTML Format" header is skipped.
+ /// </summary>
+ public static string? ImageOnly(string? html)
+ {
+ if (string.IsNullOrWhiteSpace(html))
+ return null;
+ var start = html.IndexOf("<!--StartFragment-->", StringComparison.OrdinalIgnoreCase);
+ var end = html.IndexOf("<!--EndFragment-->", StringComparison.OrdinalIgnoreCase);
+ if (start >= 0 && end > start)
+ html = html[(start + "<!--StartFragment-->".Length)..end];
+ var images = ImageTag().Matches(html);
+ if (images.Count != 1)
+ return null;
+ var withoutMarkup = Comment().Replace(html, "");
+ withoutMarkup = Tag().Replace(withoutMarkup, "");
+ if (WebUtility.HtmlDecode(withoutMarkup).Any(c => !char.IsWhiteSpace(c)))
+ return null;
+ var src = WebUtility.HtmlDecode(images[0].Groups["src"].Value).Trim();
+ return src.Length == 0 ? null : src;
+ }
+
+ private static List<string> Lines(string? text) =>
+ string.IsNullOrEmpty(text)
+ ? []
+ : text.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
+
+ [GeneratedRegex("""<img\b[^>]*?\bsrc\s*=\s*(?:"(?<src>[^"]*)"|'(?<src>[^']*)'|(?<src>[^\s>]+))""", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
+ private static partial Regex ImageTag();
+
+ [GeneratedRegex("<[^>]*>", RegexOptions.CultureInvariant)]
+ private static partial Regex Tag();
+
+ [GeneratedRegex("<!--.*?-->", RegexOptions.Singleline | RegexOptions.CultureInvariant)]
+ private static partial Regex Comment();
+
+ /// <summary>
+ /// The bytes and media type of a data: URL (base64 or percent-encoded), or null when it isn't one or holds more
+ /// than <paramref name="maxBytes"/>.
+ /// </summary>
+ public static (string Mime, byte[] Bytes)? DecodeDataUrl(string? url, int maxBytes = 256 * 1024 * 1024)
+ {
+ if (url is null || !url.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
+ return null;
+ var comma = url.IndexOf(',');
+ if (comma < 0)
+ return null;
+ var header = url[5..comma];
+ var payload = url[(comma + 1)..];
+ var parts = header.Split(';');
+ var mime = parts[0].Trim().Length == 0 ? "text/plain" : parts[0].Trim();
+ var base64 = parts.Skip(1).Any(p => p.Trim().Equals("base64", StringComparison.OrdinalIgnoreCase));
+ try
+ {
+ byte[] bytes;
+ if (base64)
+ {
+ payload = Uri.UnescapeDataString(payload).Replace(" ", "").Replace("\r", "").Replace("\n", "");
+ if ((long)payload.Length * 3 / 4 > maxBytes)
+ return null;
+ bytes = Convert.FromBase64String(payload);
+ }
+ else
+ {
+ bytes = Encoding.UTF8.GetBytes(Uri.UnescapeDataString(payload));
+ if (bytes.Length > maxBytes)
+ return null;
+ }
+ return (mime, bytes);
+ }
+ catch (FormatException)
+ {
+ return null;
+ }
+ }
+}
diff --git a/src/Filee.Core/Web/WebDownloader.cs b/src/Filee.Core/Web/WebDownloader.cs
new file mode 100644
index 00000000..f92bbfff
--- /dev/null
+++ b/src/Filee.Core/Web/WebDownloader.cs
@@ -0,0 +1,227 @@
+// Saves files from the web: the bytes a browser handed over with a drag, or, when a drag brought only an address, the
+// file downloaded from it. Downloads are plain GET requests without the browser's cookies or sign-in (Filee has
+// neither): only http and https, a few redirects, a size cap and timeouts. Whatever arrives is named by what it
+// really is, never replaces an existing file, and programs or web pages are refused instead of saved.
+
+using System.Net;
+using System.Net.Http.Headers;
+using Filee.Core.Conversion;
+
+namespace Filee.Core.Web;
+
+public sealed class WebDownloader : IDisposable
+{
+ /// <summary>Largest file Filee saves from the web.</summary>
+ public const long DefaultMaxBytes = 2L * 1024 * 1024 * 1024;
+
+ private readonly HttpClient _http;
+
+ /// <param name="handler">For tests; by default a handler without cookies, credentials or automatic redirects.</param>
+ /// <param name="userAgent">"Filee/1.13.0"; some servers refuse requests without one.</param>
+ public WebDownloader(HttpMessageHandler? handler = null, string? userAgent = null)
+ {
+ handler ??= new SocketsHttpHandler
+ {
+ AllowAutoRedirect = false,
+ UseCookies = false,
+ UseProxy = true,
+ Credentials = null,
+ PreAuthenticate = false,
+ AutomaticDecompression = DecompressionMethods.All,
+ ConnectTimeout = TimeSpan.FromSeconds(20),
+ };
+ _http = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
+ if (userAgent is not null)
+ _http.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
+ }
+
+ public long MaxBytes { get; init; } = DefaultMaxBytes;
+
+ public int MaxRedirects { get; init; } = 5;
+
+ /// <summary>How long the server may take to start answering.</summary>
+ public TimeSpan ResponseTimeout { get; init; } = TimeSpan.FromSeconds(30);
+
+ /// <summary>How long a download may go without receiving anything.</summary>
+ public TimeSpan StallTimeout { get; init; } = TimeSpan.FromSeconds(30);
+
+ /// <summary>
+ /// Downloads <paramref name="url"/> into <paramref name="folder"/> and returns the file's path. The name comes from
+ /// the server (Content-Disposition), else <paramref name="suggestedName"/>, else the address, and its extension
+ /// from the first bytes when they say what the file is.
+ /// </summary>
+ /// <exception cref="ConversionRefusedException">With the reason to show (<c>error.web_*</c>).</exception>
+ public async Task<string> DownloadAsync(Uri url, string folder, string? suggestedName, IProgress<double>? progress,
+ CancellationToken cancellationToken)
+ {
+ if (!IsWebAddress(url))
+ throw new ConversionRefusedException("error.web_download_failed", url.Scheme);
+
+ using var response = await GetFollowingRedirectsAsync(url, cancellationToken);
+ if (!response.IsSuccessStatusCode)
+ throw new ConversionRefusedException("error.web_download_failed", $"HTTP {(int)response.StatusCode}");
+
+ var headers = response.Content.Headers;
+ var mime = headers.ContentType?.MediaType;
+ if (WebFormats.IsPage(mime))
+ throw new ConversionRefusedException("error.web_page");
+ if (WebFormats.IsProgram(mime))
+ throw new ConversionRefusedException("error.web_blocked");
+ if (headers.ContentLength is { } length && length > MaxBytes)
+ throw new ConversionRefusedException("error.web_too_large", Megabytes(length));
+
+ var finalUrl = response.RequestMessage?.RequestUri ?? url;
+ var name = WebFileNames.FromContentDisposition(headers.ContentDisposition?.ToString())
+ ?? suggestedName
+ ?? WebFileNames.FromUrl(finalUrl)
+ ?? "download";
+ await using var body = await response.Content.ReadAsStreamAsync(cancellationToken);
+ return await SaveAsync(body, folder, name, mime, headers.ContentLength, progress, cancellationToken, refusePages: true);
+ }
+
+ /// <summary>
+ /// Writes <paramref name="source"/> into <paramref name="folder"/> as <paramref name="name"/> (sanitized, renamed to
+ /// what the first bytes are, numbered when taken) and returns the path. A file cut short by an error is deleted.
+ /// </summary>
+ /// <param name="refusePages">
+ /// A download: an HTML page where a file was expected is a sign-in or error page, not the file.
+ /// </param>
+ /// <exception cref="ConversionRefusedException">A program, a web page or a file over <see cref="MaxBytes"/>.</exception>
+ public async Task<string> SaveAsync(Stream source, string folder, string name, string? mime, long? length,
+ IProgress<double>? progress, CancellationToken cancellationToken, bool refusePages = false)
+ {
+ var head = new byte[WebFormats.SniffLength];
+ var headLength = await ReadAtLeastAsync(source, head, cancellationToken);
+ if (WebFormats.LooksLikeProgram(head.AsSpan(0, headLength)))
+ throw new ConversionRefusedException("error.web_blocked");
+ if (refusePages && WebFormats.LooksLikePage(head.AsSpan(0, headLength)))
+ throw new ConversionRefusedException("error.web_page");
+
+ name = WebFormats.NameFor(WebFileNames.Sanitize(name), head.AsSpan(0, headLength), mime);
+ if (WebFileNames.IsBlocked(name))
+ throw new ConversionRefusedException("error.web_blocked");
+
+ var file = WebFileNames.CreateUnique(folder, name, out var path);
+ try
+ {
+ await using (file)
+ {
+ await file.WriteAsync(head.AsMemory(0, headLength), cancellationToken);
+ long total = headLength;
+ var buffer = new byte[1 << 16];
+ while (true)
+ {
+ var read = await ReadWithStallTimeoutAsync(source, buffer, cancellationToken);
+ if (read == 0)
+ break;
+ total += read;
+ if (total > MaxBytes)
+ throw new ConversionRefusedException("error.web_too_large", Megabytes(total));
+ await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
+ if (length is > 0)
+ progress?.Report(Math.Min(1, (double)total / length.Value));
+ }
+ }
+ progress?.Report(1);
+ return path;
+ }
+ catch
+ {
+ TryDelete(path);
+ throw;
+ }
+ }
+
+ /// <summary>True for an http or https address, the only ones Filee downloads.</summary>
+ public static bool IsWebAddress(Uri url) =>
+ url.IsAbsoluteUri && (url.Scheme == Uri.UriSchemeHttps || url.Scheme == Uri.UriSchemeHttp);
+
+ private async Task<HttpResponseMessage> GetFollowingRedirectsAsync(Uri url, CancellationToken cancellationToken)
+ {
+ for (var hop = 0; ; hop++)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, url);
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
+ HttpResponseMessage response;
+ using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
+ {
+ timeout.CancelAfter(ResponseTimeout);
+ try
+ {
+ response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ throw new ConversionRefusedException("error.web_timeout");
+ }
+ catch (HttpRequestException ex)
+ {
+ throw new ConversionRefusedException("error.web_download_failed", ex.HttpRequestError switch
+ {
+ HttpRequestError.NameResolutionError => url.Host,
+ _ => ex.Message,
+ });
+ }
+ }
+
+ if ((int)response.StatusCode is >= 300 and < 400 && response.Headers.Location is { } location)
+ {
+ response.Dispose();
+ var next = location.IsAbsoluteUri ? location : new Uri(url, location);
+ // Never from https down to http, and never to anything but the web (file:, ftp:).
+ if (!IsWebAddress(next) || (url.Scheme == Uri.UriSchemeHttps && next.Scheme != Uri.UriSchemeHttps))
+ throw new ConversionRefusedException("error.web_download_failed", next.Scheme + ":");
+ if (hop >= MaxRedirects)
+ throw new ConversionRefusedException("error.web_download_failed", "too many redirects");
+ url = next;
+ continue;
+ }
+ return response;
+ }
+ }
+
+ private async Task<int> ReadAtLeastAsync(Stream source, byte[] buffer, CancellationToken cancellationToken)
+ {
+ var total = 0;
+ while (total < buffer.Length)
+ {
+ var read = await ReadWithStallTimeoutAsync(source, buffer.AsMemory(total), cancellationToken);
+ if (read == 0)
+ break;
+ total += read;
+ }
+ return total;
+ }
+
+ private async Task<int> ReadWithStallTimeoutAsync(Stream source, Memory<byte> buffer, CancellationToken cancellationToken)
+ {
+ using var stall = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ stall.CancelAfter(StallTimeout);
+ try
+ {
+ return await source.ReadAsync(buffer, stall.Token);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ throw new ConversionRefusedException("error.web_timeout");
+ }
+ catch (Exception ex) when (ex is IOException or HttpRequestException)
+ {
+ throw new ConversionRefusedException("error.web_download_failed", ex.Message);
+ }
+ }
+
+ private static string Megabytes(long bytes) => $"{bytes / (1024.0 * 1024):0} MB";
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+
+ public void Dispose() => _http.Dispose();
+}
diff --git a/src/Filee.Core/Web/WebDrop.cs b/src/Filee.Core/Web/WebDrop.cs
new file mode 100644
index 00000000..27621cf6
--- /dev/null
+++ b/src/Filee.Core/Web/WebDrop.cs
@@ -0,0 +1,221 @@
+// Files dragged out of a web browser (or another app that holds them only in memory): what they will be called, and
+// how they get onto disk. They are saved when their conversion runs (WebDropFetcher), not when they are dropped, so
+// the donut opens at once and a download shows its progress and errors like any conversion.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+
+namespace Filee.Core.Web;
+
+/// <summary>One file a drag brought from a browser, not saved yet.</summary>
+public abstract class WebDropItem : IDisposable
+{
+ protected WebDropItem(string name) => Name = WebFileNames.Sanitize(name);
+
+ /// <summary>
+ /// The name it will most likely be saved under; its extension decides the donut's slices. The saved file may
+ /// still get another extension when its bytes say it is something else.
+ /// </summary>
+ public string Name { get; }
+
+ /// <summary>Writes the file into <paramref name="folder"/> and returns its path.</summary>
+ public abstract Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<double>? progress,
+ CancellationToken cancellationToken);
+
+ public virtual void Dispose() => GC.SuppressFinalize(this);
+
+ /// <summary>Bytes the browser hands over (a picture's file, a data: address).</summary>
+ public static WebDropItem FromBytes(string name, byte[] bytes, string? mime = null) =>
+ new StreamItem(name, _ => Task.FromResult<Stream>(new MemoryStream(bytes, writable: false)), bytes.Length, mime, null);
+
+ /// <summary>
+ /// A file whose bytes the source app streams on request (a Windows virtual file). <paramref name="owner"/> is
+ /// disposed with the item, telling the source the transfer is over.
+ /// </summary>
+ public static WebDropItem FromStream(string name, Func<CancellationToken, Task<Stream>> open, long? size = null,
+ IDisposable? owner = null) =>
+ new StreamItem(name, open, size, null, owner);
+
+ /// <summary>A file the browser wrote somewhere temporary (Firefox): copied, the browser's copy left alone.</summary>
+ public static WebDropItem FromTemporaryFile(string path) =>
+ new StreamItem(Path.GetFileName(path),
+ _ => Task.FromResult<Stream>(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16, useAsync: true)),
+ null, null, null);
+
+ /// <summary>An address Filee downloads itself (without the browser's sign-in).</summary>
+ public static WebDropItem FromAddress(string name, Uri url) => new AddressItem(name, url);
+
+ private sealed class StreamItem(string name, Func<CancellationToken, Task<Stream>> open, long? size, string? mime, IDisposable? owner)
+ : WebDropItem(name)
+ {
+ public override async Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<double>? progress,
+ CancellationToken cancellationToken)
+ {
+ await using var stream = await open(cancellationToken);
+ return await downloader.SaveAsync(stream, folder, Name, mime, size, progress, cancellationToken);
+ }
+
+ public override void Dispose()
+ {
+ owner?.Dispose();
+ base.Dispose();
+ }
+ }
+
+ private sealed class AddressItem(string name, Uri url) : WebDropItem(name)
+ {
+ public Uri Url { get; } = url;
+
+ public override Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<double>? progress,
+ CancellationToken cancellationToken) =>
+ // A name the server sends wins; a guessed extension (".jpg" for a picture address without one) is
+ // corrected from the bytes.
+ downloader.DownloadAsync(Url, folder, Name, progress, cancellationToken);
+ }
+}
+
+/// <summary>
+/// The files of one browser drag, each standing in the donut and the job as a path that doesn't exist yet (a
+/// placeholder in <see cref="WorkFolder"/>, named like the file will be) until its conversion saves it.
+/// </summary>
+public sealed class WebDrop : IDisposable
+{
+ private readonly Dictionary<string, WebDropItem> _items = new(StringComparer.Ordinal);
+ private readonly List<string> _placeholders = [];
+ private int _disposed;
+
+ /// <param name="items">What the drag brought.</param>
+ /// <param name="workRoot">Folder for Filee's own copies (<see cref="DefaultWorkRoot"/>).</param>
+ public WebDrop(IReadOnlyList<WebDropItem> items, string workRoot)
+ {
+ WorkFolder = Path.Combine(workRoot, Guid.NewGuid().ToString("N")[..10]);
+ for (var i = 0; i < items.Count; i++)
+ {
+ // A folder per item: two pictures called "image.jpg" stay two files.
+ var placeholder = Path.Combine(WorkFolder, "drop", (i + 1).ToString(), items[i].Name);
+ _items[placeholder] = items[i];
+ _placeholders.Add(placeholder);
+ }
+ }
+
+ /// <summary>%TEMP%\Filee\web: originals that aren't kept are saved here and deleted after their conversion.</summary>
+ public static string DefaultWorkRoot => Path.Combine(Path.GetTempPath(), "Filee", "web");
+
+ /// <summary>This drop's own folder inside the work root.</summary>
+ public string WorkFolder { get; }
+
+ /// <summary>The paths the files stand as until they are saved.</summary>
+ public IReadOnlyList<string> Placeholders => _placeholders;
+
+ /// <summary>True for a placeholder of any drop (a path in the <see cref="DefaultWorkRoot"/>'s drop folders).</summary>
+ public static bool IsPlaceholder(string path)
+ {
+ try
+ {
+ var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(DefaultWorkRoot)) + Path.DirectorySeparatorChar;
+ var full = Path.GetFullPath(path);
+ return full.StartsWith(root, StringComparison.OrdinalIgnoreCase)
+ && full[root.Length..].Split(Path.DirectorySeparatorChar) is [_, "drop", _, _];
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>True for a path of this drop that isn't a file yet.</summary>
+ public bool Holds(string path) => _items.ContainsKey(path);
+
+ internal WebDropItem ItemFor(string placeholder) =>
+ _items.TryGetValue(placeholder, out var item) ? item : throw new ArgumentException("Not a file of this drop.", nameof(placeholder));
+
+ /// <summary>The fetcher that saves this drop's files when a conversion runs.</summary>
+ public WebDropFetcher CreateFetcher(WebDropOptions options, WebDownloader downloader) => new(this, options, downloader);
+
+ /// <summary>Ends the transfers the items still hold open (the source app may wait for that).</summary>
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0)
+ return;
+ foreach (var item in _items.Values)
+ {
+ try
+ {
+ item.Dispose();
+ }
+ catch (Exception ex) when (ex is IOException or InvalidOperationException or System.Runtime.InteropServices.COMException)
+ {
+ // The source app went away: nothing left to end.
+ }
+ }
+ }
+
+ /// <summary>
+ /// Deletes work folders older than <paramref name="age"/> that a crash or a power cut left behind. A folder still in
+ /// use is skipped.
+ /// </summary>
+ public static void DeleteStale(string workRoot, TimeSpan age)
+ {
+ try
+ {
+ if (!Directory.Exists(workRoot))
+ return;
+ foreach (var folder in Directory.EnumerateDirectories(workRoot))
+ {
+ if (DateTime.UtcNow - Directory.GetLastWriteTimeUtc(folder) > age)
+ TryDeleteFolder(folder);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ }
+ }
+
+ internal static void TryDeleteFolder(string folder)
+ {
+ try
+ {
+ if (Directory.Exists(folder))
+ Directory.Delete(folder, recursive: true);
+ }
+ catch (IOException) { /* a viewer still holds a file; the stale sweep deletes it later */ }
+ catch (UnauthorizedAccessException) { }
+ }
+}
+
+/// <summary>Where files dragged from a browser are saved (Settings → General).</summary>
+/// <param name="Folder">The download folder; "next to the source" means this folder for these files.</param>
+/// <param name="SaveOnlyConverted">The original goes into the work folder and is deleted after the conversion.</param>
+public sealed record WebDropOptions(string Folder, bool SaveOnlyConverted);
+
+/// <summary>Saves a <see cref="WebDrop"/>'s files for the job that converts them, and cleans up after it.</summary>
+public sealed class WebDropFetcher(WebDrop drop, WebDropOptions options, WebDownloader downloader) : ISourceFetcher
+{
+ public WebDropOptions Options => options;
+
+ /// <summary>
+ /// <paramref name="preset"/> with "next to the source" pointing at the download folder, also when the original is
+ /// only kept in the work folder.
+ /// </summary>
+ public Preset Apply(Preset preset)
+ {
+ var copy = preset.Clone();
+ copy.Output.SourceFolder = options.Folder;
+ return copy;
+ }
+
+ /// <summary>Folder the originals are saved in.</summary>
+ public string SaveFolder => options.SaveOnlyConverted ? Path.Combine(drop.WorkFolder, "files") : options.Folder;
+
+ public bool Fetches(string path) => drop.Holds(path);
+
+ public Task<string> FetchAsync(string placeholder, IProgress<double> progress, CancellationToken cancellationToken) =>
+ drop.ItemFor(placeholder).SaveAsync(SaveFolder, downloader, progress, cancellationToken);
+
+ public void Release(ConversionJob job)
+ {
+ drop.Dispose();
+ // Holds the originals of "Save only the converted file"; otherwise it was never created.
+ WebDrop.TryDeleteFolder(drop.WorkFolder);
+ }
+}
diff --git a/src/Filee.Core/Web/WebFileNames.cs b/src/Filee.Core/Web/WebFileNames.cs
new file mode 100644
index 00000000..cd80efb0
--- /dev/null
+++ b/src/Filee.Core/Web/WebFileNames.cs
@@ -0,0 +1,181 @@
+// Names for files that come from the web: whatever a server or a page says a file is called is cut down to a plain
+// file name that is safe on every supported OS, and files are created under a free name (never over an existing one).
+
+using System.Net.Http.Headers;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+
+namespace Filee.Core.Web;
+
+public static class WebFileNames
+{
+ /// <summary>Longest name Filee gives a downloaded file, extension included (paths stay well under 260 characters).</summary>
+ public const int MaxLength = 120;
+
+ /// <summary>
+ /// Programs, installers and scripts. Filee converts none of them; a drag or a server that offers one is refused
+ /// rather than saved.
+ /// </summary>
+ private static readonly HashSet<string> Blocked = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "exe", "msi", "msix", "msixbundle", "appx", "appxbundle", "msp", "com", "scr", "pif", "cpl", "dll", "sys",
+ "bat", "cmd", "ps1", "psm1", "psd1", "vbs", "vbe", "js", "jse", "mjs", "wsf", "wsh", "hta", "reg", "inf",
+ "lnk", "url", "scf", "application", "appref-ms", "gadget", "msc",
+ "sh", "bash", "zsh", "csh", "ksh", "command", "tool", "run", "bin", "appimage", "desktop",
+ "app", "dmg", "pkg", "mpkg", "kext", "workflow", "scpt", "applescript",
+ "jar", "jnlp", "apk", "xapk", "ipa", "deb", "rpm", "snap", "flatpak", "py", "pyw", "pl", "rb",
+ };
+
+ /// <summary>Extensions of web pages: a link to one is a page to read, not a file to convert.</summary>
+ private static readonly HashSet<string> PageExtensions = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "htm", "html", "xhtml", "shtml", "php", "php3", "php4", "php5", "phtml", "asp", "aspx", "jsp", "jspx", "cgi",
+ "cfm", "do", "action",
+ };
+
+ /// <summary>Names Windows keeps for devices, with or without an extension.</summary>
+ private static readonly HashSet<string> ReservedStems = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
+ "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
+ "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
+ };
+
+ /// <summary>True for a program, installer or script (by extension), which Filee never saves from the web.</summary>
+ public static bool IsBlocked(string name) => Blocked.Contains(LastExtension(name));
+
+ /// <summary>True for the extension of a web page (.html, .php, …).</summary>
+ public static bool IsPage(string name) => PageExtensions.Contains(LastExtension(name));
+
+ /// <summary>
+ /// A plain file name made from <paramref name="name"/>: only its last path part, without characters any supported
+ /// OS refuses, not a device name, at most <see cref="MaxLength"/> characters (the extension is kept), and never
+ /// empty (<paramref name="fallback"/>).
+ /// </summary>
+ public static string Sanitize(string? name, string fallback = "download")
+ {
+ name ??= "";
+ // Only the last part: "../../x.png", "C:\x.png" and "a/b.png" all become a name in the target folder.
+ var slash = name.LastIndexOfAny(['/', '\\']);
+ if (slash >= 0)
+ name = name[(slash + 1)..];
+ name = OutputPathResolver.Sanitize(name, "").Trim(' ', '.');
+ if (name.Length == 0)
+ name = fallback;
+
+ var extension = Path.GetExtension(name);
+ if (extension.Length > 16)
+ extension = "";
+ var stem = extension.Length == 0 ? name : name[..^extension.Length];
+ if (ReservedStems.Contains(stem.TrimEnd(' ', '.')))
+ stem = "_" + stem;
+ if (stem.Length + extension.Length > MaxLength)
+ stem = stem[..(MaxLength - extension.Length)].TrimEnd(' ', '.');
+ // Don't end in half of a surrogate pair after cutting.
+ if (stem.Length > 0 && char.IsHighSurrogate(stem[^1]))
+ stem = stem[..^1];
+ if (stem.Length == 0)
+ stem = fallback;
+ return stem + extension;
+ }
+
+ /// <summary>The file name a Content-Disposition header gives (RFC 6266, <c>filename*</c> first), or null.</summary>
+ public static string? FromContentDisposition(string? header)
+ {
+ if (string.IsNullOrWhiteSpace(header) || !ContentDispositionHeaderValue.TryParse(header, out var value))
+ return null;
+ var name = value.FileNameStar ?? value.FileName;
+ name = name?.Trim().Trim('"');
+ return string.IsNullOrWhiteSpace(name) ? null : name;
+ }
+
+ /// <summary>The last part of the URL's path, unescaped ("photo%201.jpg" → "photo 1.jpg"), or null when there is none.</summary>
+ public static string? FromUrl(Uri url)
+ {
+ if (!url.IsAbsoluteUri)
+ return null;
+ var path = url.AbsolutePath;
+ var slash = path.LastIndexOf('/');
+ var last = slash >= 0 ? path[(slash + 1)..] : path;
+ if (last.Length == 0)
+ return null;
+ try
+ {
+ last = Uri.UnescapeDataString(last);
+ }
+ catch (UriFormatException)
+ {
+ }
+ return string.IsNullOrWhiteSpace(last) ? null : last;
+ }
+
+ /// <summary>
+ /// <paramref name="name"/> with <paramref name="extension"/> (no dot) when it doesn't already have an extension of
+ /// the same format: "photo" → "photo.jpg", "photo.jpeg" stays, "photo.png" with "webp" → "photo.webp".
+ /// </summary>
+ public static string WithExtension(string name, string extension)
+ {
+ var current = FormatRegistry.ExtensionOf(name);
+ var wanted = FormatRegistry.FindByExtension(extension);
+ if (current.Length > 0 && wanted is not null && FormatRegistry.FindByExtension(current) == wanted)
+ return name;
+ var stem = current.Length > 0 && FormatRegistry.FindByExtension(current) is not null
+ ? FormatRegistry.NameWithoutExtension(name)
+ : name;
+ return Sanitize($"{stem}.{extension}");
+ }
+
+ /// <summary>
+ /// Creates <paramref name="name"/> in <paramref name="folder"/>, or "name (2).ext", "name (3).ext" … when that is
+ /// taken (as converted files are named), and returns the open file. Never replaces an existing file.
+ /// </summary>
+ public static FileStream CreateUnique(string folder, string name, out string path)
+ {
+ Directory.CreateDirectory(folder);
+ for (var n = 1; ; n++)
+ {
+ path = Path.Combine(folder, Numbered(name, n));
+ try
+ {
+ return new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true);
+ }
+ catch (IOException) when ((File.Exists(path) || Directory.Exists(path)) && n < 10_000)
+ {
+ }
+ }
+ }
+
+ /// <summary>
+ /// Moves <paramref name="source"/> into <paramref name="folder"/> as <paramref name="name"/>, numbered like
+ /// <see cref="CreateUnique"/> when taken, and returns where it went. Never replaces an existing file.
+ /// </summary>
+ public static string MoveUnique(string source, string folder, string name)
+ {
+ Directory.CreateDirectory(folder);
+ for (var n = 1; ; n++)
+ {
+ var path = Path.Combine(folder, Numbered(name, n));
+ if (File.Exists(path) || Directory.Exists(path))
+ continue;
+ try
+ {
+ File.Move(source, path, overwrite: false);
+ return path;
+ }
+ catch (IOException) when ((File.Exists(path) || Directory.Exists(path)) && n < 10_000)
+ {
+ }
+ }
+ }
+
+ private static string Numbered(string name, int n)
+ {
+ if (n == 1)
+ return name;
+ var extension = FormatRegistry.ExtensionOf(name);
+ var stem = extension.Length == 0 ? name : name[..^(extension.Length + 1)];
+ return extension.Length == 0 ? $"{stem} ({n})" : $"{stem} ({n}).{extension}";
+ }
+
+ private static string LastExtension(string name) => Path.GetExtension(name.TrimEnd(' ', '.')).TrimStart('.');
+}
diff --git a/src/Filee.Core/Web/WebFormats.cs b/src/Filee.Core/Web/WebFormats.cs
new file mode 100644
index 00000000..a8be5da6
--- /dev/null
+++ b/src/Filee.Core/Web/WebFormats.cs
@@ -0,0 +1,217 @@
+// What a file from the web is: by its media type (what a server or a drag says) and by its first bytes (what it
+// really is). Only formats whose signature is unambiguous are sniffed; a ZIP is not taken for a DOCX, nor the reverse.
+
+using System.Text;
+using Filee.Core.Formats;
+
+namespace Filee.Core.Web;
+
+public static class WebFormats
+{
+ private static readonly Dictionary<string, string> ByMime = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["image/png"] = "png",
+ ["image/apng"] = "apng",
+ ["image/jpeg"] = "jpg",
+ ["image/jpg"] = "jpg",
+ ["image/pjpeg"] = "jpg",
+ ["image/gif"] = "gif",
+ ["image/webp"] = "webp",
+ ["image/bmp"] = "bmp",
+ ["image/x-ms-bmp"] = "bmp",
+ ["image/tiff"] = "tiff",
+ ["image/svg+xml"] = "svg",
+ ["image/avif"] = "avif",
+ ["image/heic"] = "heic",
+ ["image/heif"] = "heic",
+ ["image/jxl"] = "jxl",
+ ["image/x-icon"] = "ico",
+ ["image/vnd.microsoft.icon"] = "ico",
+ ["image/jp2"] = "jp2",
+ ["image/vnd.adobe.photoshop"] = "psd",
+ ["application/pdf"] = "pdf",
+ ["application/x-pdf"] = "pdf",
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"] = "docx",
+ ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] = "xlsx",
+ ["application/vnd.openxmlformats-officedocument.presentationml.presentation"] = "pptx",
+ ["application/msword"] = "doc",
+ ["application/vnd.ms-excel"] = "xls",
+ ["application/vnd.ms-powerpoint"] = "ppt",
+ ["application/vnd.oasis.opendocument.text"] = "odt",
+ ["application/vnd.oasis.opendocument.spreadsheet"] = "ods",
+ ["application/vnd.oasis.opendocument.presentation"] = "odp",
+ ["application/rtf"] = "rtf",
+ ["text/rtf"] = "rtf",
+ ["application/epub+zip"] = "epub",
+ ["application/x-hwp"] = "hwp",
+ ["application/haansofthwp"] = "hwp",
+ ["application/vnd.hancom.hwp"] = "hwp",
+ ["application/vnd.hancom.hwpx"] = "hwpx",
+ ["application/hwp+zip"] = "hwpx",
+ ["text/plain"] = "txt",
+ ["text/csv"] = "csv",
+ ["text/markdown"] = "md",
+ ["application/json"] = "json",
+ ["application/xml"] = "xml",
+ ["text/xml"] = "xml",
+ ["application/zip"] = "zip",
+ ["application/x-zip-compressed"] = "zip",
+ ["application/x-7z-compressed"] = "7z",
+ ["application/vnd.rar"] = "rar",
+ ["application/x-rar-compressed"] = "rar",
+ ["application/gzip"] = "gz",
+ ["audio/mpeg"] = "mp3",
+ ["audio/mp4"] = "m4a",
+ ["audio/wav"] = "wav",
+ ["audio/x-wav"] = "wav",
+ ["audio/ogg"] = "ogg",
+ ["audio/flac"] = "flac",
+ ["audio/webm"] = "weba",
+ ["video/mp4"] = "mp4",
+ ["video/webm"] = "webm",
+ ["video/quicktime"] = "mov",
+ ["video/x-matroska"] = "mkv",
+ ["video/x-msvideo"] = "avi",
+ ["font/ttf"] = "ttf",
+ ["font/otf"] = "otf",
+ ["font/woff"] = "woff",
+ ["font/woff2"] = "woff2",
+ };
+
+ /// <summary>Types a server sends for programs. Refused like the extensions in <see cref="WebFileNames.IsBlocked"/>.</summary>
+ private static readonly HashSet<string> ProgramMimes = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "application/x-msdownload", "application/x-msdos-program", "application/x-msi", "application/x-ms-installer",
+ "application/vnd.microsoft.portable-executable", "application/x-dosexec", "application/x-executable",
+ "application/x-sh", "application/x-shellscript", "application/x-bat", "application/java-archive",
+ "application/x-java-archive", "application/vnd.android.package-archive", "application/x-apple-diskimage",
+ "application/x-debian-package", "application/x-rpm", "application/x-mach-binary", "text/javascript",
+ "application/javascript", "application/x-powershell",
+ };
+
+ /// <summary>The media type without parameters, lower case ("Image/PNG; charset=x" → "image/png"), or "".</summary>
+ public static string Normalize(string? mime)
+ {
+ if (string.IsNullOrWhiteSpace(mime))
+ return "";
+ var semicolon = mime.IndexOf(';');
+ return (semicolon >= 0 ? mime[..semicolon] : mime).Trim().ToLowerInvariant();
+ }
+
+ /// <summary>The extension (no dot) Filee writes for a media type it knows, or null.</summary>
+ public static string? ExtensionForMime(string? mime) => ByMime.GetValueOrDefault(Normalize(mime));
+
+ /// <summary>True for a web page (HTML) media type.</summary>
+ public static bool IsPage(string? mime) => Normalize(mime) is "text/html" or "application/xhtml+xml";
+
+ /// <summary>True for an image media type.</summary>
+ public static bool IsImage(string? mime) => Normalize(mime).StartsWith("image/", StringComparison.Ordinal);
+
+ /// <summary>True for a program's media type.</summary>
+ public static bool IsProgram(string? mime) => ProgramMimes.Contains(Normalize(mime));
+
+ /// <summary>Bytes enough for <see cref="Sniff"/>.</summary>
+ public const int SniffLength = 64;
+
+ /// <summary>
+ /// The extension (no dot) of a format recognised by its first bytes, or null. Only formats whose signature can't be
+ /// mistaken: images and PDF.
+ /// </summary>
+ public static string? Sniff(ReadOnlySpan<byte> head)
+ {
+ if (head.StartsWith(PngSignature))
+ return "png";
+ if (head.StartsWith(JpegSignature))
+ return "jpg";
+ if (head.StartsWith("GIF87a"u8) || head.StartsWith("GIF89a"u8))
+ return "gif";
+ if (head.Length >= 12 && head.StartsWith("RIFF"u8) && head[8..12].SequenceEqual("WEBP"u8))
+ return "webp";
+ if (head.StartsWith("%PDF-"u8))
+ return "pdf";
+ // BITMAPFILEHEADER: "BM", the file size, then two reserved words that are always zero.
+ if (head.Length >= 14 && head.StartsWith("BM"u8) && head[6] == 0 && head[7] == 0 && head[8] == 0 && head[9] == 0)
+ return "bmp";
+ if (head.StartsWith(TiffLittle) || head.StartsWith(TiffBig))
+ return "tiff";
+ if (head.StartsWith(IcoSignature))
+ return "ico";
+ if (head.StartsWith("8BPS"u8))
+ return "psd";
+ if (head.StartsWith(JxlCodestream) || head.StartsWith(JxlContainer))
+ return "jxl";
+ if (head.Length >= 12 && head[4..8].SequenceEqual("ftyp"u8))
+ {
+ // The major brand, then the compatible brands: an AVIF may name itself "mif1" first.
+ var brands = Encoding.ASCII.GetString(head[8..Math.Min(head.Length, 40)]);
+ if (brands.Contains("avif", StringComparison.Ordinal) || brands.Contains("avis", StringComparison.Ordinal))
+ return "avif";
+ return brands[..4] is "heic" or "heix" or "heim" or "heis" or "mif1" or "msf1" or "hevc" or "hevx" ? "heic" : null;
+ }
+ return null;
+ }
+
+ private static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
+ private static readonly byte[] JpegSignature = [0xFF, 0xD8, 0xFF];
+ private static readonly byte[] TiffLittle = [0x49, 0x49, 0x2A, 0x00];
+ private static readonly byte[] TiffBig = [0x4D, 0x4D, 0x00, 0x2A];
+ private static readonly byte[] IcoSignature = [0x00, 0x00, 0x01, 0x00];
+ private static readonly byte[] JxlCodestream = [0xFF, 0x0A];
+ private static readonly byte[] JxlContainer = [0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A];
+
+ private static readonly byte[][] ProgramSignatures =
+ [
+ [0x4D, 0x5A], // "MZ": Windows programs and libraries
+ [0x7F, 0x45, 0x4C, 0x46], // ELF: Linux programs
+ [0x23, 0x21], // "#!": scripts
+ [0xCA, 0xFE, 0xBA, 0xBE], // Mach-O universal binaries (also Java classes)
+ [0xCF, 0xFA, 0xED, 0xFE], // Mach-O 64-bit
+ [0xCE, 0xFA, 0xED, 0xFE], // Mach-O 32-bit
+ ];
+
+ /// <summary>True when the bytes start like a program or a script (Windows, Linux or macOS executables, "#!").</summary>
+ public static bool LooksLikeProgram(ReadOnlySpan<byte> head)
+ {
+ foreach (var signature in ProgramSignatures)
+ {
+ if (head.StartsWith(signature))
+ return true;
+ }
+ return false;
+ }
+
+ /// <summary>True when the bytes start like an HTML page (a sign-in or error page instead of the file).</summary>
+ public static bool LooksLikePage(ReadOnlySpan<byte> head)
+ {
+ var text = Encoding.UTF8.GetString(head).TrimStart('', ' ', '\t', '\r', '\n');
+ return text.StartsWith("<!doctype html", StringComparison.OrdinalIgnoreCase)
+ || text.StartsWith("<html", StringComparison.OrdinalIgnoreCase)
+ || text.StartsWith("<head", StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// <summary>
+ /// The name a file should have once its first bytes are known: a sniffed image or PDF replaces an extension that
+ /// says otherwise (a ".jpg" URL that serves WebP), or is added to a name Filee can't place; a known extension
+ /// whose format can't be sniffed (".docx" for a ZIP) stays.
+ /// </summary>
+ public static string NameFor(string name, ReadOnlySpan<byte> head, string? mime)
+ {
+ var sniffed = Sniff(head);
+ var current = FormatRegistry.Detect(name);
+ if (sniffed is not null)
+ {
+ var real = FormatRegistry.FindByExtension(sniffed);
+ // "a.apng" sniffs as PNG and "a.ai" as PDF: keep a name whose format is a kind of what was sniffed.
+ if (current is null || (current != real && IsSniffable(current)))
+ return WebFileNames.WithExtension(name, sniffed);
+ return name;
+ }
+ if (current is null && ExtensionForMime(mime) is { } fromMime)
+ return WebFileNames.WithExtension(name, fromMime);
+ return name;
+ }
+
+ private static readonly HashSet<string> SniffableIds = ["png", "jpg", "gif", "webp", "pdf", "bmp", "tiff", "ico", "psd", "jxl", "avif", "heic"];
+
+ private static bool IsSniffable(FileFormat format) => SniffableIds.Contains(format.Id);
+}
diff --git a/tests/Filee.Core.Tests/BrowserDragFormatsTests.cs b/tests/Filee.Core.Tests/BrowserDragFormatsTests.cs
new file mode 100644
index 00000000..4b756934
--- /dev/null
+++ b/tests/Filee.Core.Tests/BrowserDragFormatsTests.cs
@@ -0,0 +1,278 @@
+// The forms browsers put dragged pictures, links and downloads into (BrowserDragFormats), the names files from the web
+// get (WebFileNames) and what they are taken for before and after their bytes are known (WebFormats).
+
+using System.Runtime.InteropServices;
+using System.Text;
+using Filee.Core.Web;
+
+namespace Filee.Core.Tests;
+
+public class BrowserDragFormatsTests
+{
+ /// <summary>FILEDESCRIPTORW as shlobj.h declares it, to check the parser's offsets against the real layout.</summary>
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 4)]
+ private struct FileDescriptorW
+ {
+ public uint dwFlags;
+ public Guid clsid;
+ public long sizel;
+ public long pointl;
+ public uint dwFileAttributes;
+ public long ftCreationTime;
+ public long ftLastAccessTime;
+ public long ftLastWriteTime;
+ public uint nFileSizeHigh;
+ public uint nFileSizeLow;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
+ public string cFileName;
+ }
+
+ private static byte[] Native(params FileDescriptorW[] entries)
+ {
+ var size = Marshal.SizeOf<FileDescriptorW>();
+ Assert.Equal(592, size);
+ var data = new byte[4 + entries.Length * size];
+ BitConverter.GetBytes((uint)entries.Length).CopyTo(data, 0);
+ var buffer = Marshal.AllocHGlobal(size);
+ try
+ {
+ for (var i = 0; i < entries.Length; i++)
+ {
+ Marshal.StructureToPtr(entries[i], buffer, false);
+ Marshal.Copy(buffer, data, 4 + i * size, size);
+ }
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
+ }
+ return data;
+ }
+
+ [Fact]
+ public void Reads_names_sizes_and_folders_from_a_native_FileGroupDescriptorW()
+ {
+ var data = Native(
+ new FileDescriptorW { dwFlags = 0x40, nFileSizeHigh = 1, nFileSizeLow = 5, cFileName = "사진 1.jpg" },
+ new FileDescriptorW { dwFlags = 0x4, dwFileAttributes = 0x10, cFileName = "album" },
+ new FileDescriptorW { dwFlags = 0, cFileName = "Example Domain.url" });
+
+ var entries = BrowserDragFormats.ParseFileGroupDescriptor(data);
+
+ Assert.Equal(3, entries.Count);
+ Assert.Equal(new FileDescriptor("사진 1.jpg", (1L << 32) + 5, false), entries[0]);
+ Assert.Equal(new FileDescriptor("album", null, true), entries[1]);
+ Assert.Equal("Example Domain.url", entries[2].Name);
+ }
+
+ [Fact]
+ public void A_descriptor_cut_short_or_absurd_gives_nothing()
+ {
+ var data = BrowserDragFormats.BuildFileGroupDescriptor([new FileDescriptor("a.png", 3, false), new FileDescriptor("b.png", null, false)]);
+ Assert.Equal(2, BrowserDragFormats.ParseFileGroupDescriptor(data).Count);
+ Assert.Empty(BrowserDragFormats.ParseFileGroupDescriptor(data.AsSpan(0, data.Length - 1)));
+ Assert.Empty(BrowserDragFormats.ParseFileGroupDescriptor([0xFF, 0xFF, 0xFF, 0x7F]));
+ Assert.Empty(BrowserDragFormats.ParseFileGroupDescriptor([]));
+ }
+
+ [Fact]
+ public void Reads_DownloadURL_whose_address_has_colons()
+ {
+ var download = BrowserDragFormats.ParseDownloadUrl("application/pdf:Q3 report.pdf:https://mail.example.com:8443/attachment?id=1:2");
+
+ Assert.NotNull(download);
+ Assert.Equal("application/pdf", download.Mime);
+ Assert.Equal("Q3 report.pdf", download.Name);
+ Assert.Equal("https://mail.example.com:8443/attachment?id=1:2", download.Url.OriginalString);
+ Assert.Null(BrowserDragFormats.ParseDownloadUrl("https://example.com/a.pdf"));
+ Assert.Null(BrowserDragFormats.ParseDownloadUrl("pdf:a.pdf:https://example.com/a.pdf")); // no media type
+ Assert.Null(BrowserDragFormats.ParseDownloadUrl("application/pdf::https://example.com/a.pdf")); // no name
+ }
+
+ [Fact]
+ public void Reads_uri_lists_without_comments()
+ {
+ var urls = BrowserDragFormats.ParseUriList("# dragged from Firefox\r\nhttps://example.com/a.png\r\n\r\nhttps://example.com/b.pdf\r\n");
+ Assert.Equal(["https://example.com/a.png", "https://example.com/b.pdf"], urls);
+ }
+
+ [Fact]
+ public void Reads_moz_url_pairs_from_UTF16_bytes_padded_with_NULs()
+ {
+ var bytes = Encoding.Unicode.GetBytes("https://example.com/a.png\nPicture A\nhttps://example.com/b.pdf\nReport\0\0\0");
+ var text = BrowserDragFormats.DecodeText(bytes);
+
+ Assert.Equal(["https://example.com/a.png", "https://example.com/b.pdf"], BrowserDragFormats.ParseMozUrl(text));
+ }
+
+ [Theory]
+ [InlineData(new byte[] { 0x68, 0x00, 0x69, 0x00 }, "hi")] // UTF-16 LE
+ [InlineData(new byte[] { 0xFF, 0xFE, 0x68, 0x00, 0x69, 0x00 }, "hi")] // with BOM
+ [InlineData(new byte[] { 0x68, 0x69, 0x00, 0x00 }, "hi")] // UTF-8, padded
+ [InlineData(new byte[] { 0xEF, 0xBB, 0xBF, 0xED, 0x95, 0x9C }, "한")] // UTF-8 with BOM
+ [InlineData(new byte[] { 0xED, 0x95, 0x9C, 0x2E, 0x70, 0x6E, 0x67 }, "한.png")] // UTF-8
+ public void Decodes_text_the_way_each_platform_writes_it(byte[] bytes, string expected) =>
+ Assert.Equal(expected, BrowserDragFormats.DecodeText(bytes));
+
+ [Fact]
+ public void Reads_the_address_of_an_internet_shortcut()
+ {
+ Assert.Equal("https://example.com/", BrowserDragFormats.ParseInternetShortcut("[InternetShortcut]\r\nURL=https://example.com/\r\n"));
+ Assert.Null(BrowserDragFormats.ParseInternetShortcut("[InternetShortcut]"));
+ }
+
+ [Fact]
+ public void A_picture_is_an_HTML_fragment_of_one_image_and_no_text()
+ {
+ const string windowsHtml = "Version:0.9\r\nStartHTML:000000105\r\nEndHTML:000000300\r\n<html><body>\r\n<!--StartFragment-->" +
+ "<a href=\"https://example.com/post\"><img src=\"https://cdn.example.com/p/cat.webp?w=800&amp;h=600\" alt=\"A cat\"></a>" +
+ "<!--EndFragment-->\r\n</body></html>";
+
+ Assert.Equal("https://cdn.example.com/p/cat.webp?w=800&h=600", BrowserDragFormats.ImageOnly(windowsHtml));
+ Assert.Equal("/img/dog.png", BrowserDragFormats.ImageOnly("<meta charset='utf-8'><img src='/img/dog.png'>"));
+ Assert.Equal("data:image/png;base64,iVBO", BrowserDragFormats.ImageOnly("<img src=data:image/png;base64,iVBO>"));
+ // A selection of text with a picture in it, or two pictures, is not "a picture".
+ Assert.Null(BrowserDragFormats.ImageOnly("<p>Look at this <img src=\"a.png\"> cat</p>"));
+ Assert.Null(BrowserDragFormats.ImageOnly("<img src=\"a.png\"><img src=\"b.png\">"));
+ Assert.Null(BrowserDragFormats.ImageOnly("<p>Just text</p>"));
+ Assert.Null(BrowserDragFormats.ImageOnly(null));
+ }
+
+ [Fact]
+ public void Decodes_data_addresses()
+ {
+ var png = BrowserDragFormats.DecodeDataUrl("data:image/png;base64,iVBORw0KGgo=");
+ Assert.NotNull(png);
+ Assert.Equal("image/png", png.Value.Mime);
+ Assert.Equal([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], png.Value.Bytes);
+
+ var svg = BrowserDragFormats.DecodeDataUrl("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%2F%3E");
+ Assert.Equal("<svg xmlns=\"http://www.w3.org/2000/svg\"/>", Encoding.UTF8.GetString(svg!.Value.Bytes));
+
+ Assert.Null(BrowserDragFormats.DecodeDataUrl("data:image/png;base64,***"));
+ Assert.Null(BrowserDragFormats.DecodeDataUrl("https://example.com/a.png"));
+ Assert.Null(BrowserDragFormats.DecodeDataUrl("data:image/png;base64,iVBORw0KGgo=", maxBytes: 4));
+ }
+
+ [Theory]
+ [InlineData("../../Windows/System32/evil.png", "evil.png")]
+ [InlineData(@"C:\Users\me\photo.jpg", "photo.jpg")]
+ [InlineData("a<b>:c|d?.jpg", "a_b__c_d_.jpg")]
+ [InlineData("CON.txt", "_CON.txt")]
+ [InlineData("lpt1", "_lpt1")]
+ [InlineData(" report.pdf. . ", "report.pdf")]
+ [InlineData(".hidden", "hidden")]
+ [InlineData("", "download")]
+ [InlineData("...", "download")]
+ [InlineData("tab\there.png", "tab_here.png")]
+ public void File_names_from_the_web_are_made_safe(string name, string expected) =>
+ Assert.Equal(expected, WebFileNames.Sanitize(name));
+
+ [Fact]
+ public void A_long_name_is_cut_and_keeps_its_extension()
+ {
+ var name = WebFileNames.Sanitize(new string('가', 300) + ".pdf");
+ Assert.Equal(WebFileNames.MaxLength, name.Length);
+ Assert.EndsWith(".pdf", name);
+ }
+
+ [Theory]
+ [InlineData("setup.exe", true)]
+ [InlineData("SETUP.EXE ", true)]
+ [InlineData("install.msi", true)]
+ [InlineData("run.ps1", true)]
+ [InlineData("Filee.dmg", true)]
+ [InlineData("app.jar", true)]
+ [InlineData("Example.url", true)]
+ [InlineData("photo.jpg", false)]
+ [InlineData("backup.tar.gz", false)]
+ [InlineData("noextension", false)]
+ public void Programs_installers_and_scripts_are_blocked(string name, bool blocked) =>
+ Assert.Equal(blocked, WebFileNames.IsBlocked(name));
+
+ [Theory]
+ [InlineData("attachment; filename=\"report.pdf\"", "report.pdf")]
+ [InlineData("attachment; filename=plain.png", "plain.png")]
+ [InlineData("attachment; filename=\"fallback.pdf\"; filename*=UTF-8''%ED%95%9C%EA%B8%80.pdf", "한글.pdf")]
+ [InlineData("inline", null)]
+ [InlineData("", null)]
+ public void Reads_the_name_a_server_gives(string header, string? expected) =>
+ Assert.Equal(expected, WebFileNames.FromContentDisposition(header));
+
+ [Fact]
+ public void Reads_the_name_an_address_ends_in()
+ {
+ Assert.Equal("my photo.jpg", WebFileNames.FromUrl(new Uri("https://example.com/a/my%20photo.jpg?w=1#x")));
+ Assert.Null(WebFileNames.FromUrl(new Uri("https://example.com/")));
+ }
+
+ [Fact]
+ public void Files_are_created_under_a_free_name_and_never_replace_one()
+ {
+ using var dir = new TempDir();
+ File.WriteAllText(Path.Combine(dir.Path, "a.pdf"), "old");
+
+ using (var first = WebFileNames.CreateUnique(dir.Path, "a.pdf", out var path))
+ Assert.Equal(Path.Combine(dir.Path, "a (2).pdf"), path);
+ using (WebFileNames.CreateUnique(dir.Path, "a.pdf", out var path))
+ Assert.Equal(Path.Combine(dir.Path, "a (3).pdf"), path);
+ Assert.Equal("old", File.ReadAllText(Path.Combine(dir.Path, "a.pdf")));
+
+ var source = dir.File("incoming.tmp", "new");
+ Assert.Equal(Path.Combine(dir.Path, "a (4).pdf"), WebFileNames.MoveUnique(source, dir.Path, "a.pdf"));
+ Assert.Equal("old", File.ReadAllText(Path.Combine(dir.Path, "a.pdf")));
+ }
+
+ [Theory]
+ [InlineData(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0 }, "png")]
+ [InlineData(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10 }, "jpg")]
+ [InlineData(new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, "gif")]
+ [InlineData(new byte[] { 0x52, 0x49, 0x46, 0x46, 1, 0, 0, 0, 0x57, 0x45, 0x42, 0x50 }, "webp")]
+ [InlineData(new byte[] { 0x25, 0x50, 0x44, 0x46, 0x2D, 0x31 }, "pdf")]
+ [InlineData(new byte[] { 0, 0, 0, 0x1C, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66 }, "avif")]
+ [InlineData(new byte[] { 0, 0, 0, 0x1C, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x69, 0x66, 0x31, 0, 0, 0, 0, 0x61, 0x76, 0x69, 0x66 }, "avif")]
+ [InlineData(new byte[] { 0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63 }, "heic")]
+ [InlineData(new byte[] { 0x50, 0x4B, 0x03, 0x04 }, null)] // a ZIP may be a DOCX: not guessed
+ [InlineData(new byte[] { 0x3C, 0x68, 0x74, 0x6D, 0x6C }, null)]
+ public void Recognises_formats_by_their_first_bytes(byte[] head, string? expected) =>
+ Assert.Equal(expected, WebFormats.Sniff(head));
+
+ [Fact]
+ public void Programs_and_pages_are_recognised_by_their_first_bytes()
+ {
+ Assert.True(WebFormats.LooksLikeProgram("MZ\x90\0"u8));
+ Assert.True(WebFormats.LooksLikeProgram("#!/bin/sh\n"u8));
+ Assert.False(WebFormats.LooksLikeProgram("%PDF-1.7"u8));
+ Assert.True(WebFormats.LooksLikePage("\n <!DOCTYPE html><html>"u8));
+ Assert.False(WebFormats.LooksLikePage("%PDF-1.7"u8));
+ }
+
+ [Theory]
+ [InlineData("photo.jpg", "webp", null, "photo.webp")] // the address said JPG, the server sent WebP
+ [InlineData("photo.jpeg", "jpg", null, "photo.jpeg")] // the same format, another extension: kept
+ [InlineData("download", "pdf", null, "download.pdf")]
+ [InlineData("report.docx", null, null, "report.docx")] // can't be sniffed: kept
+ [InlineData("export", null, "application/pdf", "export.pdf")]
+ [InlineData("export", null, "image/png; charset=binary", "export.png")]
+ public void A_name_follows_what_the_file_really_is(string name, string? sniffed, string? mime, string expected)
+ {
+ byte[] head = sniffed switch
+ {
+ "webp" => [0x52, 0x49, 0x46, 0x46, 1, 0, 0, 0, 0x57, 0x45, 0x42, 0x50],
+ "jpg" => [0xFF, 0xD8, 0xFF, 0xE0],
+ "pdf" => "%PDF-1.4"u8.ToArray(),
+ _ => [0x50, 0x4B, 0x03, 0x04],
+ };
+ Assert.Equal(expected, WebFormats.NameFor(name, head, mime));
+ }
+
+ [Fact]
+ public void Media_types_map_to_extensions()
+ {
+ Assert.Equal("jpg", WebFormats.ExtensionForMime("image/JPEG"));
+ Assert.Equal("docx", WebFormats.ExtensionForMime("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
+ Assert.Null(WebFormats.ExtensionForMime("application/octet-stream"));
+ Assert.True(WebFormats.IsPage("text/html; charset=utf-8"));
+ Assert.True(WebFormats.IsProgram("application/x-msdownload"));
+ }
+}
diff --git a/tests/Filee.Core.Tests/BrowserDragTests.cs b/tests/Filee.Core.Tests/BrowserDragTests.cs
new file mode 100644
index 00000000..656da4ef
--- /dev/null
+++ b/tests/Filee.Core.Tests/BrowserDragTests.cs
@@ -0,0 +1,164 @@
+// What in a drag from a browser counts as a file (BrowserDrag): pictures always, links only when they point at a file
+// Filee converts, never a page or a selection of text.
+
+using Filee.Core.Web;
+
+namespace Filee.Core.Tests;
+
+public class BrowserDragTests
+{
+ private static BrowserDragContent Drag(params (string Format, string Text)[] texts) =>
+ new() { Texts = texts.ToDictionary(t => t.Format, t => t.Text, StringComparer.OrdinalIgnoreCase) };
+
+ private static IReadOnlyList<string> Names(BrowserDragContent content) =>
+ BrowserDrag.Files(content).Select(f => f.Name).ToList();
+
+ private sealed class Tracked(string name) : IDisposable
+ {
+ public string Name { get; } = name;
+ public bool Disposed { get; private set; }
+ public void Dispose() => Disposed = true;
+ }
+
+ [Fact]
+ public void A_picture_the_browser_hands_over_is_taken_and_its_link_shortcut_is_not()
+ {
+ // Chrome on Windows: the picture as a virtual file. A dragged link comes as "Title.url" instead.
+ var picture = new Tracked("cat.webp");
+ var shortcut = new Tracked("Cats - Example.url");
+ var content = new BrowserDragContent
+ {
+ Files =
+ [
+ WebDropItem.FromStream(picture.Name, _ => Task.FromResult<Stream>(new MemoryStream()), owner: picture),
+ WebDropItem.FromStream(shortcut.Name, _ => Task.FromResult<Stream>(new MemoryStream()), owner: shortcut),
+ ],
+ Texts = new Dictionary<string, string> { [BrowserDragFormats.UniformResourceLocatorW] = "https://example.com/cats" },
+ };
+
+ Assert.Equal(["cat.webp"], Names(content));
+ Assert.False(picture.Disposed);
+ Assert.True(shortcut.Disposed);
+ }
+
+ [Theory]
+ [InlineData("https://example.com/files/Q3%20report.pdf?download=1", "Q3 report.pdf")]
+ [InlineData("https://example.com/a/photo.JPG", "photo.JPG")]
+ [InlineData("http://example.com/sheet.xlsx", "sheet.xlsx")]
+ public void A_link_to_a_file_Filee_converts_is_a_file(string url, string name) =>
+ Assert.Equal([name], Names(Drag((BrowserDragFormats.MozUrl, url + "\nTitle"))));
+
+ [Theory]
+ [InlineData("https://example.com/news/article")]
+ [InlineData("https://example.com/")]
+ [InlineData("https://example.com/index.html")]
+ [InlineData("https://example.com/view.php?id=3")]
+ [InlineData("https://example.com/setup.exe")]
+ [InlineData("ftp://example.com/a.pdf")]
+ [InlineData("file:///C:/Users/me/a.pdf")]
+ [InlineData("javascript:alert(1)")]
+ public void A_link_to_a_page_a_program_or_anything_but_the_web_is_not(string url) =>
+ Assert.Empty(Names(Drag((BrowserDragFormats.UniformResourceLocatorW, url))));
+
+ [Fact]
+ public void A_text_selection_is_not_a_file_even_with_a_picture_in_it()
+ {
+ Assert.Empty(Names(Drag((BrowserDragFormats.Html, "<p>See <img src=\"https://example.com/a.png\"> here</p>"))));
+ Assert.Empty(Names(Drag()));
+ }
+
+ [Fact]
+ public void A_dragged_picture_is_its_address_even_inside_a_link_and_without_an_extension()
+ {
+ // Firefox/Chrome on Linux and macOS: the link the picture sits in, and the picture in the HTML.
+ var inLink = Drag(
+ (BrowserDragFormats.MozUrl, "https://example.com/post/42\nPost"),
+ (BrowserDragFormats.Html, "<a href=\"https://example.com/post/42\"><img src=\"/media/sunset.png\"></a>"));
+ var item = Assert.Single(BrowserDrag.Files(inLink));
+ Assert.Equal("sunset.png", item.Name);
+
+ var noExtension = Drag(
+ (BrowserDragFormats.NetscapeUrl, "https://cdn.example.com/image?id=7\nimage"),
+ (BrowserDragFormats.Html, "<img src=\"https://cdn.example.com/image?id=7\">"));
+ Assert.Equal(["image.jpg"], Names(noExtension)); // the bytes decide later
+ }
+
+ [Fact]
+ public void An_inline_data_picture_is_decoded()
+ {
+ var content = Drag(
+ (BrowserDragFormats.UniformResourceLocatorW, "data:image/png;base64,iVBORw0KGgo="),
+ (BrowserDragFormats.Html, "<img src=\"data:image/png;base64,iVBORw0KGgo=\">"));
+ Assert.Equal(["image.png"], Names(content));
+ }
+
+ [Fact]
+ public void A_download_a_page_offers_is_named_as_the_page_says()
+ {
+ var content = Drag((BrowserDragFormats.DownloadUrlFormat, "application/pdf:Invoice 2026-10.pdf:https://mail.example.com/attachment?id=9"));
+ Assert.Equal(["Invoice 2026-10.pdf"], Names(content));
+
+ var noExtension = Drag((BrowserDragFormats.DownloadUrlFormat, "image/png:screenshot:https://example.com/dl?id=1"));
+ Assert.Equal(["screenshot.png"], Names(noExtension));
+ }
+
+ [Fact]
+ public void A_Firefox_file_promise_is_a_picture()
+ {
+ var content = Drag(
+ (BrowserDragFormats.MozFilePromiseUrl, "https://example.com/render?id=3"),
+ (BrowserDragFormats.MozFilePromiseName, "render.png"));
+ Assert.Equal(["render.png"], Names(content));
+ }
+
+ [Fact]
+ public void Several_links_give_several_files_once_each()
+ {
+ var content = Drag(
+ (BrowserDragFormats.UriList, "https://example.com/a.pdf\r\nhttps://example.com/b.png\r\nhttps://example.com/page"),
+ (BrowserDragFormats.MozUrl, "https://example.com/a.pdf\nA"));
+ Assert.Equal(["a.pdf", "b.png"], Names(content));
+ }
+
+ [Fact]
+ public void Pixels_only_stand_in_when_the_picture_has_no_address_Filee_can_fetch()
+ {
+ var asked = 0;
+ WebDropItem Pixels()
+ {
+ asked++;
+ return WebDropItem.FromBytes("image.png", [1, 2, 3]);
+ }
+
+ var blob = new BrowserDragContent
+ {
+ Texts = new Dictionary<string, string> { [BrowserDragFormats.UniformResourceLocatorW] = "blob:https://example.com/0b1c" },
+ Picture = Pixels,
+ };
+ Assert.Equal(["image.png"], Names(blob));
+
+ var fetchable = new BrowserDragContent
+ {
+ Texts = new Dictionary<string, string> { [BrowserDragFormats.UniformResourceLocatorW] = "https://example.com/photo.jpg" },
+ Picture = Pixels,
+ };
+ Assert.Equal(["photo.jpg"], Names(fetchable));
+ Assert.Equal(1, asked);
+
+ // Pixels from an app that isn't a browser (no address at all) are not taken.
+ Assert.Empty(Names(new BrowserDragContent { Picture = Pixels }));
+ }
+
+ [Fact]
+ public void Placeholders_are_named_like_the_files_and_kept_apart()
+ {
+ using var drop = new WebDrop([WebDropItem.FromBytes("image.png", [1]), WebDropItem.FromBytes("image.png", [2])], WebDrop.DefaultWorkRoot);
+
+ Assert.Equal(2, drop.Placeholders.Count);
+ Assert.All(drop.Placeholders, p => Assert.Equal("image.png", Path.GetFileName(p)));
+ Assert.NotEqual(drop.Placeholders[0], drop.Placeholders[1]);
+ Assert.All(drop.Placeholders, p => Assert.True(WebDrop.IsPlaceholder(p)));
+ Assert.All(drop.Placeholders, p => Assert.False(File.Exists(p)));
+ Assert.False(WebDrop.IsPlaceholder(Path.Combine(Path.GetTempPath(), "image.png")));
+ }
+}
diff --git a/tests/Filee.Core.Tests/WebDownloaderTests.cs b/tests/Filee.Core.Tests/WebDownloaderTests.cs
new file mode 100644
index 00000000..cbce856d
--- /dev/null
+++ b/tests/Filee.Core.Tests/WebDownloaderTests.cs
@@ -0,0 +1,282 @@
+// WebDownloader against a local HTTP server: names, redirects, the size cap, timeouts, cancelling, and what is refused.
+
+using System.Net;
+using System.Net.Sockets;
+using Filee.Core.Conversion;
+using Filee.Core.Web;
+
+namespace Filee.Core.Tests;
+
+public sealed class WebDownloaderTests : IDisposable
+{
+ private static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, 0x49, 0x48, 0x44, 0x52];
+
+ private readonly HttpListener _listener = new();
+ private readonly CancellationTokenSource _stop = new();
+ private readonly Dictionary<string, Func<HttpListenerContext, Task>> _routes = new(StringComparer.Ordinal);
+ private readonly TempDir _dir = new();
+ private readonly string _root;
+
+ public WebDownloaderTests()
+ {
+ var port = FreePort();
+ _root = $"http://127.0.0.1:{port}/";
+ _listener.Prefixes.Add(_root);
+ _listener.Start();
+ _ = Task.Run(ServeAsync);
+ }
+
+ private static int FreePort()
+ {
+ var probe = new TcpListener(IPAddress.Loopback, 0);
+ probe.Start();
+ var port = ((IPEndPoint)probe.LocalEndpoint).Port;
+ probe.Stop();
+ return port;
+ }
+
+ private async Task ServeAsync()
+ {
+ while (!_stop.IsCancellationRequested)
+ {
+ HttpListenerContext context;
+ try
+ {
+ context = await _listener.GetContextAsync();
+ }
+ catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
+ {
+ return;
+ }
+ _ = Task.Run(async () =>
+ {
+ try
+ {
+ if (_routes.TryGetValue(context.Request.Url!.AbsolutePath, out var route))
+ await route(context);
+ else
+ context.Response.StatusCode = 404;
+ context.Response.Close();
+ }
+ catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or IOException or InvalidOperationException)
+ {
+ // The client went away (a test that cancels or times out).
+ }
+ });
+ }
+ }
+
+ private void Serve(string path, byte[] body, string? contentType = null, string? disposition = null, bool chunked = false) =>
+ _routes[path] = async context =>
+ {
+ if (contentType is not null)
+ context.Response.ContentType = contentType;
+ if (disposition is not null)
+ context.Response.AddHeader("Content-Disposition", disposition);
+ if (chunked)
+ context.Response.SendChunked = true;
+ else
+ context.Response.ContentLength64 = body.Length;
+ await context.Response.OutputStream.WriteAsync(body);
+ };
+
+ private void Redirect(string path, string location, int status = 302) =>
+ _routes[path] = context =>
+ {
+ context.Response.StatusCode = status;
+ context.Response.RedirectLocation = location;
+ return Task.CompletedTask;
+ };
+
+ private Uri Url(string path) => new(_root + path.TrimStart('/'));
+
+ private static WebDownloader Downloader() => new(userAgent: "Filee-tests/1.0");
+
+ [Fact]
+ public async Task Names_the_file_as_the_server_says_and_by_what_it_is()
+ {
+ Serve("/get", Png, "application/octet-stream", "attachment; filename*=UTF-8''%EC%82%AC%EC%A7%84.jpg");
+ using var downloader = Downloader();
+
+ var path = await downloader.DownloadAsync(Url("/get"), _dir.Path, null, null, TestContext.Current.CancellationToken);
+
+ Assert.Equal(Path.Combine(_dir.Path, "사진.png"), path); // named "사진.jpg", but the bytes are a PNG
+ Assert.Equal(Png, await File.ReadAllBytesAsync(path, TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public async Task Names_the_file_after_the_address_and_never_replaces_one()
+ {
+ Serve("/files/report.pdf", "%PDF-1.7 test"u8.ToArray(), "application/pdf");
+ File.WriteAllText(Path.Combine(_dir.Path, "report.pdf"), "mine");
+ using var downloader = Downloader();
+
+ var path = await downloader.DownloadAsync(Url("/files/report.pdf"), _dir.Path, null, null, TestContext.Current.CancellationToken);
+
+ Assert.Equal(Path.Combine(_dir.Path, "report (2).pdf"), path);
+ Assert.Equal("mine", File.ReadAllText(Path.Combine(_dir.Path, "report.pdf")));
+ }
+
+ [Fact]
+ public async Task Follows_a_few_redirects_and_no_more()
+ {
+ Serve("/real/photo.png", Png, "image/png");
+ Redirect("/short", "/hop");
+ Redirect("/hop", _root + "real/photo.png", 301);
+ for (var i = 0; i < 8; i++)
+ Redirect($"/loop{i}", $"/loop{i + 1}");
+ using var downloader = Downloader();
+
+ var path = await downloader.DownloadAsync(Url("/short"), _dir.Path, null, null, TestContext.Current.CancellationToken);
+ Assert.Equal("photo.png", Path.GetFileName(path));
+
+ var refused = await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ downloader.DownloadAsync(Url("/loop0"), _dir.Path, null, null, TestContext.Current.CancellationToken));
+ Assert.Equal("error.web_download_failed", refused.ErrorKey);
+ }
+
+ [Fact]
+ public async Task Never_follows_a_redirect_off_the_web()
+ {
+ Redirect("/sneaky", "file:///C:/Windows/win.ini");
+ using var downloader = Downloader();
+
+ var refused = await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ downloader.DownloadAsync(Url("/sneaky"), _dir.Path, null, null, TestContext.Current.CancellationToken));
+ Assert.Equal("error.web_download_failed", refused.ErrorKey);
+ Assert.Empty(Directory.GetFiles(_dir.Path));
+ }
+
+ [Fact]
+ public async Task Refuses_a_file_over_the_size_cap_said_or_not_and_leaves_nothing_behind()
+ {
+ var big = new byte[64 * 1024];
+ Png.CopyTo(big, 0);
+ Serve("/said.png", big, "image/png");
+ Serve("/unsaid.png", big, "image/png", chunked: true);
+ using var downloader = new WebDownloader { MaxBytes = 10_000 };
+
+ var said = await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ downloader.DownloadAsync(Url("/said.png"), _dir.Path, null, null, TestContext.Current.CancellationToken));
+ var unsaid = await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ downloader.DownloadAsync(Url("/unsaid.png"), _dir.Path, null, null, TestContext.Current.CancellationToken));
+
+ Assert.Equal("error.web_too_large", said.ErrorKey);
+ Assert.Equal("error.web_too_large", unsaid.ErrorKey);
+ Assert.Empty(Directory.GetFiles(_dir.Path));
+ }
+
+ [Fact]
+ public async Task Refuses_web_pages_and_programs()
+ {
+ Serve("/doc.pdf", "<!doctype html><title>Sign in</title>"u8.ToArray(), "text/html; charset=utf-8");
+ Serve("/sneaky.pdf", "<html><body>Sign in</body></html>"u8.ToArray(), "application/octet-stream");
+ Serve("/tool.png", "MZ\x90\0\x03\0\0\0"u8.ToArray(), "image/png");
+ Serve("/x.bin", "%PDF-1.4"u8.ToArray(), "application/x-msdownload");
+ using var downloader = Downloader();
+ var ct = TestContext.Current.CancellationToken;
+
+ Assert.Equal("error.web_page", (await Assert.ThrowsAsync<ConversionRefusedException>(() => downloader.DownloadAsync(Url("/doc.pdf"), _dir.Path, null, null, ct))).ErrorKey);
+ Assert.Equal("error.web_page", (await Assert.ThrowsAsync<ConversionRefusedException>(() => downloader.DownloadAsync(Url("/sneaky.pdf"), _dir.Path, null, null, ct))).ErrorKey);
+ Assert.Equal("error.web_blocked", (await Assert.ThrowsAsync<ConversionRefusedException>(() => downloader.DownloadAsync(Url("/tool.png"), _dir.Path, null, null, ct))).ErrorKey);
+ Assert.Equal("error.web_blocked", (await Assert.ThrowsAsync<ConversionRefusedException>(() => downloader.DownloadAsync(Url("/x.bin"), _dir.Path, null, null, ct))).ErrorKey);
+ Assert.Empty(Directory.GetFiles(_dir.Path));
+ }
+
+ [Fact]
+ public async Task Reports_a_missing_file_with_its_status()
+ {
+ using var downloader = Downloader();
+ var refused = await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ downloader.DownloadAsync(Url("/nothing.pdf"), _dir.Path, null, null, TestContext.Current.CancellationToken));
+ Assert.Equal("error.web_download_failed", refused.ErrorKey);
+ Assert.Equal("HTTP 404", refused.Detail);
+ }
+
+ [Fact]
+ public async Task Gives_up_on_a_server_that_doesnt_answer_or_stalls()
+ {
+ _routes["/silent.png"] = async _ => await Task.Delay(TimeSpan.FromSeconds(5), _stop.Token);
+ _routes["/stalls.png"] = async context =>
+ {
+ context.Response.ContentType = "image/png";
+ context.Response.ContentLength64 = 10_000;
+ await context.Response.OutputStream.WriteAsync(Png);
+ await context.Response.OutputStream.FlushAsync();
+ await Task.Delay(TimeSpan.FromSeconds(5), _stop.Token);
+ };
+ using var downloader = new WebDownloader
+ {
+ ResponseTimeout = TimeSpan.FromMilliseconds(300),
+ StallTimeout = TimeSpan.FromMilliseconds(300),
+ };
+ var ct = TestContext.Current.CancellationToken;
+
+ Assert.Equal("error.web_timeout", (await Assert.ThrowsAsync<ConversionRefusedException>(() => downloader.DownloadAsync(Url("/silent.png"), _dir.Path, null, null, ct))).ErrorKey);
+ Assert.Equal("error.web_timeout", (await Assert.ThrowsAsync<ConversionRefusedException>(() => downloader.DownloadAsync(Url("/stalls.png"), _dir.Path, null, null, ct))).ErrorKey);
+ Assert.Empty(Directory.GetFiles(_dir.Path));
+ }
+
+ [Fact]
+ public async Task Cancelling_stops_the_download_and_removes_the_partial_file()
+ {
+ var started = new TaskCompletionSource();
+ _routes["/slow.png"] = async context =>
+ {
+ context.Response.ContentType = "image/png";
+ context.Response.ContentLength64 = 10_000;
+ await context.Response.OutputStream.WriteAsync(Png);
+ await context.Response.OutputStream.FlushAsync();
+ started.TrySetResult();
+ await Task.Delay(TimeSpan.FromSeconds(5), _stop.Token);
+ };
+ using var downloader = Downloader();
+ using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
+ var progress = new List<double>();
+
+ var download = downloader.DownloadAsync(Url("/slow.png"), _dir.Path, null, new SyncProgress(progress), cancel.Token);
+ await started.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
+ await WaitUntil(() => Directory.GetFiles(_dir.Path).Length == 1);
+ cancel.Cancel();
+
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => download);
+ Assert.Empty(Directory.GetFiles(_dir.Path));
+ }
+
+ [Fact]
+ public async Task Bytes_a_browser_handed_over_are_saved_like_a_download()
+ {
+ using var downloader = Downloader();
+ var item = WebDropItem.FromBytes("image.jpg", Png);
+
+ var path = await item.SaveAsync(_dir.Path, downloader, null, TestContext.Current.CancellationToken);
+
+ Assert.Equal(Path.Combine(_dir.Path, "image.png"), path);
+ var program = WebDropItem.FromBytes("innocent.png", "MZ\x90\0"u8.ToArray());
+ Assert.Equal("error.web_blocked", (await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ program.SaveAsync(_dir.Path, downloader, null, TestContext.Current.CancellationToken))).ErrorKey);
+ }
+
+ private static async Task WaitUntil(Func<bool> condition)
+ {
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
+ while (!condition() && DateTime.UtcNow < deadline)
+ await Task.Delay(10);
+ }
+
+ private sealed class SyncProgress(List<double> values) : IProgress<double>
+ {
+ public void Report(double value)
+ {
+ lock (values)
+ values.Add(value);
+ }
+ }
+
+ public void Dispose()
+ {
+ _stop.Cancel();
+ _listener.Close();
+ _dir.Dispose();
+ }
+}
diff --git a/tests/Filee.Core.Tests/WebDropJobTests.cs b/tests/Filee.Core.Tests/WebDropJobTests.cs
new file mode 100644
index 00000000..502fbe33
--- /dev/null
+++ b/tests/Filee.Core.Tests/WebDropJobTests.cs
@@ -0,0 +1,163 @@
+// Files from a browser through a whole conversion: saved into the download folder (or a work folder that is deleted
+// afterwards with "Save only the converted file"), converted next to where the user wanted them, failures reported
+// per file.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Web;
+
+namespace Filee.Core.Tests;
+
+public class WebDropJobTests
+{
+ private static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D];
+
+ private static JobQueue Queue() =>
+ new(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("png", "jpg"), new ConversionEdge("png", "pdf"))]));
+
+ private static async Task<ConversionJob> Convert(WebDrop drop, WebDropOptions options, Preset preset)
+ {
+ using var downloader = new WebDownloader();
+ var fetcher = drop.CreateFetcher(options, downloader);
+ await using var queue = Queue();
+ var job = new ConversionJob(drop.Placeholders, fetcher.Apply(preset), "Test", fetcher);
+ await queue.RunAsync(job);
+ return job;
+ }
+
+ [Fact]
+ public async Task The_original_is_kept_in_the_download_folder_and_converted_next_to_it()
+ {
+ using var downloads = new TempDir();
+ using var work = new TempDir();
+ var drop = new WebDrop([WebDropItem.FromBytes("cat.png", Png)], work.Path);
+
+ var job = await Convert(drop, new WebDropOptions(downloads.Path, SaveOnlyConverted: false),
+ new Preset { TargetFormat = "jpg", Output = { Location = OutputLocation.SameFolder } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(Path.Combine(downloads.Path, "cat.png"), job.Files[0].SourcePath);
+ Assert.Equal([Path.Combine(downloads.Path, "cat.jpg")], job.Outputs);
+ Assert.True(File.Exists(Path.Combine(downloads.Path, "cat.png")));
+ Assert.Equal([Path.Combine(downloads.Path, "cat.png")], job.Sources); // the history records where it went
+ Assert.False(Directory.Exists(drop.WorkFolder));
+ }
+
+ [Fact]
+ public async Task With_save_only_converted_the_original_is_deleted_and_the_output_still_goes_to_the_download_folder()
+ {
+ using var downloads = new TempDir();
+ using var work = new TempDir();
+ var drop = new WebDrop([WebDropItem.FromBytes("cat.png", Png), WebDropItem.FromBytes("dog.png", Png)], work.Path);
+
+ var job = await Convert(drop, new WebDropOptions(downloads.Path, SaveOnlyConverted: true),
+ new Preset { TargetFormat = "jpg", Output = { Location = OutputLocation.SameFolder } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(["cat.jpg", "dog.jpg"], Directory.GetFiles(downloads.Path).Select(Path.GetFileName).Order());
+ Assert.False(Directory.Exists(drop.WorkFolder));
+ Assert.All(job.Files, f => Assert.False(File.Exists(f.SourcePath)));
+ }
+
+ [Fact]
+ public async Task A_subfolder_is_made_in_the_download_folder_and_a_fixed_folder_stays_fixed()
+ {
+ using var downloads = new TempDir();
+ using var fixedFolder = new TempDir();
+ using var work = new TempDir();
+
+ var sub = await Convert(new WebDrop([WebDropItem.FromBytes("a.png", Png)], work.Path), new WebDropOptions(downloads.Path, true),
+ new Preset { TargetFormat = "pdf", Output = { Location = OutputLocation.Subfolder, SubfolderName = "converted" } });
+ Assert.Equal([Path.Combine(downloads.Path, "converted", "a.pdf")], sub.Outputs);
+
+ var custom = await Convert(new WebDrop([WebDropItem.FromBytes("b.png", Png)], work.Path), new WebDropOptions(downloads.Path, true),
+ new Preset { TargetFormat = "pdf", Output = { Location = OutputLocation.CustomFolder, CustomFolder = fixedFolder.Path } });
+ Assert.Equal([Path.Combine(fixedFolder.Path, "b.pdf")], custom.Outputs);
+ }
+
+ [Fact]
+ public async Task A_file_that_cant_be_saved_fails_with_its_reason_and_the_others_still_convert()
+ {
+ using var downloads = new TempDir();
+ using var work = new TempDir();
+ var drop = new WebDrop(
+ [
+ WebDropItem.FromBytes("good.png", Png),
+ WebDropItem.FromBytes("bad.png", "MZ\x90\0"u8.ToArray()),
+ WebDropItem.FromStream("gone.png", _ => throw new IOException("The source app went away")),
+ ], work.Path);
+
+ var job = await Convert(drop, new WebDropOptions(downloads.Path, SaveOnlyConverted: true), new Preset { TargetFormat = "jpg" });
+
+ Assert.Equal(JobState.CompletedWithErrors, job.State);
+ Assert.Equal(FileState.Done, job.Files[0].State);
+ Assert.Equal(("error.web_blocked", FileState.Failed), (job.Files[1].ErrorKey, job.Files[1].State));
+ Assert.Equal(("error.web_download_failed", FileState.Failed), (job.Files[2].ErrorKey, job.Files[2].State));
+ Assert.Equal(["good.jpg"], Directory.GetFiles(downloads.Path).Select(Path.GetFileName));
+ Assert.Equal(1, job.Progress);
+ Assert.False(Directory.Exists(drop.WorkFolder));
+ }
+
+ [Fact]
+ public async Task A_job_cancelled_before_it_runs_still_cleans_up_and_ends_the_transfer()
+ {
+ using var downloads = new TempDir();
+ using var work = new TempDir();
+ var ended = false;
+ var drop = new WebDrop([WebDropItem.FromStream("a.png", _ => Task.FromResult<Stream>(new MemoryStream(Png)), owner: new Disposer(() => ended = true))], work.Path);
+ using var downloader = new WebDownloader();
+ var fetcher = drop.CreateFetcher(new WebDropOptions(downloads.Path, true), downloader);
+ var gate = new TaskCompletionSource();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("png", "jpg"))]));
+ var finished = new TaskCompletionSource<ConversionJob>();
+ queue.JobFinished += (_, j) => finished.TrySetResult(j);
+
+ var job = queue.Enqueue(drop.Placeholders, fetcher.Apply(new Preset { TargetFormat = "jpg" }), "Test", fetcher);
+ job.Cancel();
+ await finished.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
+
+ Assert.Equal(JobState.Cancelled, job.State);
+ Assert.True(ended);
+ Assert.Empty(Directory.GetFiles(downloads.Path));
+ }
+
+ [Fact]
+ public void Next_to_the_source_means_the_download_folder_only_for_this_job()
+ {
+ using var downloads = new TempDir();
+ var drop = new WebDrop([WebDropItem.FromBytes("a.png", Png)], downloads.Path);
+ using var downloader = new WebDownloader();
+ var preset = new Preset { TargetFormat = "jpg", Output = { Location = OutputLocation.SameFolder } };
+
+ var applied = drop.CreateFetcher(new WebDropOptions(downloads.Path, true), downloader).Apply(preset);
+
+ Assert.Equal(downloads.Path, applied.Output.SourceFolder);
+ Assert.Null(preset.Output.SourceFolder);
+ var json = System.Text.Json.JsonSerializer.Serialize(applied.Output);
+ Assert.DoesNotContain("SourceFolder", json, StringComparison.OrdinalIgnoreCase);
+
+ var resolved = OutputPathResolver.Resolve(applied.Output,
+ new OutputPathResolver.Tokens(Path.Combine(Path.GetTempPath(), "work", "a.png"), "x", 1, DateTime.Now), "jpg", _ => false);
+ Assert.Equal(Path.Combine(downloads.Path, "a.jpg"), resolved);
+ }
+
+ [Fact]
+ public void Stale_work_folders_are_deleted_and_fresh_ones_kept()
+ {
+ using var root = new TempDir();
+ var stale = Directory.CreateDirectory(Path.Combine(root.Path, "old")).FullName;
+ File.WriteAllText(Path.Combine(stale, "x.png"), "x");
+ Directory.SetLastWriteTimeUtc(stale, DateTime.UtcNow.AddDays(-3));
+ var fresh = Directory.CreateDirectory(Path.Combine(root.Path, "new")).FullName;
+
+ WebDrop.DeleteStale(root.Path, TimeSpan.FromDays(1));
+
+ Assert.False(Directory.Exists(stale));
+ Assert.True(Directory.Exists(fresh));
+ }
+
+ private sealed class Disposer(Action action) : IDisposable
+ {
+ public void Dispose() => action();
+ }
+}