using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace Febe.Web.Hosting;
///
/// The interface files (wwwroot) embedded in the Febe.Web assembly, as an for the
/// static file middleware. Resources are named wwwroot/<relative path> (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 (.., rooted paths, backslashes) is simply not found.
///
public sealed class EmbeddedWwwroot : IFileProvider
{
/// Prefix of the manifest resource names.
public const string Prefix = "wwwroot/";
private readonly Assembly _assembly;
private readonly string? _folder;
private readonly Dictionary _files = new(StringComparer.Ordinal);
private readonly HashSet _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;
}
///
/// 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 .
///
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;
}
/// True when files come from a folder on disk instead of the assembly.
public bool FromDisk => _folder is not null;
/// Relative paths of every embedded file ('/' separated).
public IReadOnlyCollection 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();
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());
}
/// Embedded files never change while the program runs.
public IChangeToken Watch(string filter) => NullChangeToken.Singleton;
/// Opens an embedded file, or returns null.
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;
}
/// Reads an embedded text file (UTF-8), or returns null.
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 entries) : IDirectoryContents
{
public bool Exists => true;
public IEnumerator GetEnumerator() => entries.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}