Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
287 lines
9.8 KiB
C#
287 lines
9.8 KiB
C#
using System.Collections;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Reflection;
|
|
using Microsoft.Extensions.FileProviders;
|
|
using Microsoft.Extensions.Primitives;
|
|
|
|
namespace Febe.Web.Hosting;
|
|
|
|
/// <summary>
|
|
/// The interface files (<c>wwwroot</c>) embedded in the Febe.Web assembly, as an <see cref="IFileProvider"/> for the
|
|
/// static file middleware. Resources are named <c>wwwroot/<relative path></c> (see Febe.Web.csproj): one
|
|
/// executable carries the whole interface, also on Windows. Paths are case-sensitive, '/' separated; anything that
|
|
/// tries to leave the root (<c>..</c>, rooted paths, backslashes) is simply not found.
|
|
/// </summary>
|
|
public sealed class EmbeddedWwwroot : IFileProvider
|
|
{
|
|
/// <summary>Prefix of the manifest resource names.</summary>
|
|
public const string Prefix = "wwwroot/";
|
|
|
|
private readonly Assembly _assembly;
|
|
private readonly string? _folder;
|
|
private readonly Dictionary<string, string> _files = new(StringComparer.Ordinal);
|
|
private readonly HashSet<string> _directories = new(StringComparer.Ordinal) { string.Empty };
|
|
private readonly DateTimeOffset _lastModified;
|
|
|
|
public EmbeddedWwwroot()
|
|
: this(typeof(EmbeddedWwwroot).Assembly)
|
|
{
|
|
}
|
|
|
|
[UnconditionalSuppressMessage("SingleFile", "IL3000:Avoid accessing Assembly file path when publishing as a single file", Justification = "In a single file the location is empty and the executable's own time is used instead.")]
|
|
public EmbeddedWwwroot(Assembly assembly)
|
|
{
|
|
_assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
|
|
foreach (var name in assembly.GetManifestResourceNames())
|
|
{
|
|
if (!name.StartsWith(Prefix, StringComparison.Ordinal))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
// MSBuild keeps the platform separator of %(RecursiveDir): normalize to '/'.
|
|
var relative = name[Prefix.Length..].Replace('\\', '/');
|
|
_files[relative] = name;
|
|
var slash = relative.LastIndexOf('/');
|
|
while (slash > 0)
|
|
{
|
|
_directories.Add(relative[..slash]);
|
|
slash = relative.LastIndexOf('/', slash - 1);
|
|
}
|
|
}
|
|
|
|
// Embedded files change only with the assembly: its time is a good Last-Modified (and ETag) for all of them. In a
|
|
// single-file executable (Windows) the assembly has no file of its own: the executable's time stands for it.
|
|
var location = assembly.Location;
|
|
if (string.IsNullOrEmpty(location))
|
|
{
|
|
location = Environment.ProcessPath ?? string.Empty;
|
|
}
|
|
|
|
_lastModified = !string.IsNullOrEmpty(location) && File.Exists(location)
|
|
? new DateTimeOffset(File.GetLastWriteTimeUtc(location), TimeSpan.Zero)
|
|
: DateTimeOffset.UtcNow;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Development only: serves the interface from a folder on disk (the wwwroot of the sources), so that a change to
|
|
/// a page shows at the next reload without rebuilding. Set by <see cref="FebeWebOptions.InterfaceFolder"/>.
|
|
/// </summary>
|
|
public EmbeddedWwwroot(string folder)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
|
_assembly = typeof(EmbeddedWwwroot).Assembly;
|
|
_folder = Path.GetFullPath(folder);
|
|
foreach (var file in Directory.EnumerateFiles(_folder, "*", SearchOption.AllDirectories))
|
|
{
|
|
var relative = Path.GetRelativePath(_folder, file).Replace('\\', '/');
|
|
_files[relative] = file;
|
|
var slash = relative.LastIndexOf('/');
|
|
while (slash > 0)
|
|
{
|
|
_directories.Add(relative[..slash]);
|
|
slash = relative.LastIndexOf('/', slash - 1);
|
|
}
|
|
}
|
|
|
|
_lastModified = DateTimeOffset.UtcNow;
|
|
}
|
|
|
|
/// <summary>True when files come from a folder on disk instead of the assembly.</summary>
|
|
public bool FromDisk => _folder is not null;
|
|
|
|
/// <summary>Relative paths of every embedded file ('/' separated).</summary>
|
|
public IReadOnlyCollection<string> Files => _files.Keys;
|
|
|
|
public IFileInfo GetFileInfo(string subpath)
|
|
{
|
|
var path = Normalize(subpath);
|
|
if (path is null)
|
|
{
|
|
return new NotFoundFileInfo(subpath ?? string.Empty);
|
|
}
|
|
|
|
if (_folder is not null)
|
|
{
|
|
var full = Path.Combine(_folder, path.Replace('/', Path.DirectorySeparatorChar));
|
|
return File.Exists(full) ? new PhysicalFile(full) : new NotFoundFileInfo(subpath ?? string.Empty);
|
|
}
|
|
|
|
if (!_files.TryGetValue(path, out var resource))
|
|
{
|
|
return new NotFoundFileInfo(subpath ?? string.Empty);
|
|
}
|
|
|
|
return new EmbeddedFile(_assembly, resource, path[(path.LastIndexOf('/') + 1)..], _lastModified);
|
|
}
|
|
|
|
public IDirectoryContents GetDirectoryContents(string subpath)
|
|
{
|
|
var path = Normalize(subpath);
|
|
if (path is null || !_directories.Contains(path))
|
|
{
|
|
return NotFoundDirectoryContents.Singleton;
|
|
}
|
|
|
|
var prefix = path.Length == 0 ? string.Empty : path + "/";
|
|
var entries = new List<IFileInfo>();
|
|
foreach (var (relative, resource) in _files)
|
|
{
|
|
if (relative.StartsWith(prefix, StringComparison.Ordinal) && relative.IndexOf('/', prefix.Length) < 0)
|
|
{
|
|
entries.Add(_folder is null ? new EmbeddedFile(_assembly, resource, relative[prefix.Length..], _lastModified) : new PhysicalFile(resource));
|
|
}
|
|
}
|
|
|
|
foreach (var directory in _directories)
|
|
{
|
|
if (directory.Length > prefix.Length && directory.StartsWith(prefix, StringComparison.Ordinal) && directory.IndexOf('/', prefix.Length) < 0)
|
|
{
|
|
entries.Add(new EmbeddedDirectory(directory[prefix.Length..], _lastModified));
|
|
}
|
|
}
|
|
|
|
return new Contents(entries.OrderBy(e => e.Name, StringComparer.Ordinal).ToList());
|
|
}
|
|
|
|
/// <summary>Embedded files never change while the program runs.</summary>
|
|
public IChangeToken Watch(string filter) => NullChangeToken.Singleton;
|
|
|
|
/// <summary>Opens an embedded file, or returns null.</summary>
|
|
public Stream? Open(string subpath)
|
|
{
|
|
var path = Normalize(subpath);
|
|
if (path is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (_folder is not null)
|
|
{
|
|
var full = Path.Combine(_folder, path.Replace('/', Path.DirectorySeparatorChar));
|
|
return File.Exists(full) ? File.OpenRead(full) : null;
|
|
}
|
|
|
|
return _files.TryGetValue(path, out var resource) ? _assembly.GetManifestResourceStream(resource) : null;
|
|
}
|
|
|
|
/// <summary>Reads an embedded text file (UTF-8), or returns null.</summary>
|
|
public string? ReadText(string subpath)
|
|
{
|
|
using var stream = Open(subpath);
|
|
if (stream is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
using var reader = new StreamReader(stream);
|
|
return reader.ReadToEnd();
|
|
}
|
|
|
|
private static string? Normalize(string? subpath)
|
|
{
|
|
if (subpath is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var path = subpath.TrimStart('/');
|
|
if (path.EndsWith('/'))
|
|
{
|
|
path = path.TrimEnd('/');
|
|
}
|
|
|
|
if (path.Contains('\\', StringComparison.Ordinal) || path.Contains(':', StringComparison.Ordinal) || path.Contains('\0', StringComparison.Ordinal))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
foreach (var segment in path.Split('/'))
|
|
{
|
|
if (segment is "." or ".." || (segment.Length == 0 && path.Length > 0))
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
return path;
|
|
}
|
|
|
|
private sealed class PhysicalFile(string path) : IFileInfo
|
|
{
|
|
private readonly FileInfo _info = new(path);
|
|
|
|
public bool Exists => _info.Exists;
|
|
|
|
public long Length => _info.Length;
|
|
|
|
public string? PhysicalPath => _info.FullName;
|
|
|
|
public string Name => _info.Name;
|
|
|
|
public DateTimeOffset LastModified => _info.LastWriteTimeUtc;
|
|
|
|
public bool IsDirectory => false;
|
|
|
|
public Stream CreateReadStream() => File.OpenRead(_info.FullName);
|
|
}
|
|
|
|
private sealed class EmbeddedFile(Assembly assembly, string resource, string name, DateTimeOffset lastModified) : IFileInfo
|
|
{
|
|
private long? _length;
|
|
|
|
public bool Exists => true;
|
|
|
|
public long Length
|
|
{
|
|
get
|
|
{
|
|
if (_length is null)
|
|
{
|
|
using var stream = assembly.GetManifestResourceStream(resource);
|
|
_length = stream?.Length ?? 0;
|
|
}
|
|
|
|
return _length.Value;
|
|
}
|
|
}
|
|
|
|
public string? PhysicalPath => null;
|
|
|
|
public string Name => name;
|
|
|
|
public DateTimeOffset LastModified => lastModified;
|
|
|
|
public bool IsDirectory => false;
|
|
|
|
public Stream CreateReadStream() =>
|
|
assembly.GetManifestResourceStream(resource) ?? throw new FileNotFoundException("Risorsa incorporata mancante.", name);
|
|
}
|
|
|
|
private sealed class EmbeddedDirectory(string name, DateTimeOffset lastModified) : IFileInfo
|
|
{
|
|
public bool Exists => true;
|
|
|
|
public long Length => -1;
|
|
|
|
public string? PhysicalPath => null;
|
|
|
|
public string Name => name;
|
|
|
|
public DateTimeOffset LastModified => lastModified;
|
|
|
|
public bool IsDirectory => true;
|
|
|
|
public Stream CreateReadStream() => throw new InvalidOperationException("Una cartella non si legge come file.");
|
|
}
|
|
|
|
private sealed class Contents(IReadOnlyList<IFileInfo> entries) : IDirectoryContents
|
|
{
|
|
public bool Exists => true;
|
|
|
|
public IEnumerator<IFileInfo> GetEnumerator() => entries.GetEnumerator();
|
|
|
|
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
|
}
|
|
}
|