Files
Febe/src/Febe.Core/Import/ImportSources.cs
T

374 lines
16 KiB
C#

using Febe.Core.Library;
namespace Febe.Core.Import;
/// <summary>Where sources may be chosen (spec §9.1 «Sorgente», §11).</summary>
public sealed record ImportSourceOptions
{
/// <summary>
/// Root of the sources. In Docker the volume <c>/importa</c>: a source is that folder or one of its subfolders.
/// Null on Windows: any folder Alberto chooses.
/// </summary>
public string? Root { get; init; }
/// <summary>
/// The root is mounted read-only (the <c>/importa</c> volume, spec §11): «Sposta» is never offered below it, whatever
/// the mount table says.
/// </summary>
public bool RootIsReadOnly { get; init; }
/// <summary>Docker: sources under <paramref name="root"/>, read-only.</summary>
public static ImportSourceOptions Docker(string root = "/importa") => new() { Root = root, RootIsReadOnly = true };
/// <summary>Windows (and development): any folder.</summary>
public static ImportSourceOptions AnyFolder { get; } = new();
}
/// <summary>What step 1 knows about a chosen source.</summary>
/// <param name="FullPath">Full path of the folder.</param>
/// <param name="DisplayPath">Path shown to Alberto (relative to the root in Docker, e.g. «/importa/4K Stogram»).</param>
/// <param name="Name">Folder name.</param>
/// <param name="ReadOnly">The source cannot be written: «Sposta» does not appear (spec §9.4).</param>
/// <param name="LooksLikeFebeLibrary">Account folders with <c>_febe.jsonl</c> were found.</param>
/// <param name="LooksLikeStogram">
/// A 4K Stogram database file is present (only its existence is checked): the interface may offer the hypothesis
/// recognizer, saying it is unverified.
/// </param>
/// <param name="RootIsAccount">The folder itself looks like one account (see <see cref="SourceLayout"/>).</param>
/// <param name="Folders">First-level subfolders.</param>
public sealed record ImportSourceInfo(
string FullPath,
string DisplayPath,
string Name,
bool ReadOnly,
bool LooksLikeFebeLibrary,
bool LooksLikeStogram,
bool RootIsAccount,
IReadOnlyList<string> Folders)
{
/// <summary>«Sposta» is offered only for writable sources.</summary>
public bool CanMove => !ReadOnly;
}
/// <summary>A folder offered by the source picker (Docker: below <c>/importa</c>).</summary>
/// <param name="Name">Folder name.</param>
/// <param name="Path">Path to pass back to <see cref="ImportSources.Inspect"/> (relative to the root when there is one).</param>
/// <param name="HasSubfolders">The folder has subfolders to open.</param>
public sealed record SourceFolderChoice(string Name, string Path, bool HasSubfolders);
/// <summary>A source that cannot be used; the message (Italian) says why and what to do.</summary>
public sealed class ImportSourceException : Exception
{
public ImportSourceException()
{
}
public ImportSourceException(string message)
: base(message)
{
}
public ImportSourceException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>Tells whether a folder can be written, without writing into it.</summary>
public interface ISourceAccessProbe
{
bool IsReadOnly(string fullPath);
}
/// <summary>
/// Read-only detection that never writes into the source: on Linux the mount options of the file system that holds the
/// folder (<c>ro</c>, as for a Docker volume mounted with <c>:ro</c>); on Windows optical drives. A folder that is
/// writable for the system but not for Febe is not detected: there «Sposta» stays offered and an original that cannot be
/// deleted stays where it is (the report says so).
/// </summary>
public sealed class SystemSourceAccessProbe(Func<string?>? readMounts = null) : ISourceAccessProbe
{
private readonly Func<string?> _readMounts = readMounts ?? ReadProcMounts;
public bool IsReadOnly(string fullPath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fullPath);
if (OperatingSystem.IsWindows())
{
try
{
var root = Path.GetPathRoot(Path.GetFullPath(fullPath));
return !string.IsNullOrEmpty(root) && new DriveInfo(root).DriveType == DriveType.CDRom;
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
{
return false;
}
}
var content = _readMounts();
return content is not null && MountIsReadOnly(content, Path.GetFullPath(fullPath));
}
/// <summary>True when the mount that contains <paramref name="fullPath"/> has the <c>ro</c> option.</summary>
public static bool MountIsReadOnly(string mountTable, string fullPath)
{
ArgumentNullException.ThrowIfNull(mountTable);
string? bestPoint = null;
var readOnly = false;
foreach (var raw in mountTable.Split('\n'))
{
var fields = raw.Trim().Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
if (fields.Length < 4)
{
continue;
}
var point = MountTable.Unescape(fields[1]);
var trimmed = point.Length > 1 ? point.TrimEnd('/') : point;
var contains = trimmed == "/" || fullPath == trimmed || fullPath.StartsWith(trimmed + "/", StringComparison.Ordinal);
if (contains && (bestPoint is null || trimmed.Length >= bestPoint.Length))
{
bestPoint = trimmed;
readOnly = fields[3].Split(',').Contains("ro", StringComparer.Ordinal);
}
}
return readOnly;
}
private static string? ReadProcMounts()
{
try
{
if (File.Exists("/proc/self/mounts"))
{
return File.ReadAllText("/proc/self/mounts");
}
return File.Exists("/proc/mounts") ? File.ReadAllText("/proc/mounts") : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
}
/// <summary>
/// Step 1 of the import (spec §9.1): checks a chosen folder and tells whether it is read-only. Never writes into the
/// source. A source may not be, contain or sit inside the Data folder, contain the library, or sit inside an account
/// folder of the library (folders of the library without <c>_febe.jsonl</c> may be imported, as the rebuild suggests).
/// </summary>
public sealed class ImportSources
{
private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private static readonly HashSet<string> IgnoredNames = new(StringComparer.OrdinalIgnoreCase)
{
AccountJournal.FileName, "Thumbs.db", "desktop.ini", ".DS_Store", "stogram.sqlite", "stogram.app.sqlite", "stogram.sqlite.backup",
"stogram.sqlite-wal", "stogram.sqlite-shm", "stogram.app.sqlite-wal", "stogram.app.sqlite-shm",
};
private readonly ImportSourceOptions _options;
private readonly ISourceAccessProbe _probe;
private readonly string? _libraryRoot;
private readonly string? _dataRoot;
/// <param name="options">Root and read-only flag.</param>
/// <param name="libraryRoot">The library folder (a source may not contain it).</param>
/// <param name="dataRoot">The Data folder (a source may not overlap it).</param>
/// <param name="probe">Read-only detection; <see cref="SystemSourceAccessProbe"/> by default.</param>
public ImportSources(ImportSourceOptions options, string? libraryRoot = null, string? dataRoot = null, ISourceAccessProbe? probe = null)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
_probe = probe ?? new SystemSourceAccessProbe();
_libraryRoot = libraryRoot is null ? null : Trim(Path.GetFullPath(libraryRoot));
_dataRoot = dataRoot is null ? null : Trim(Path.GetFullPath(dataRoot));
Root = options.Root is null ? null : Trim(Path.GetFullPath(options.Root));
}
/// <summary>Full path of the root of the sources (Docker), or null (any folder).</summary>
public string? Root { get; }
/// <summary>Enumeration used everywhere on sources: hidden, system files and links are skipped.</summary>
public static EnumerationOptions Enumeration(bool recursive) => new()
{
RecurseSubdirectories = recursive,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint,
ReturnSpecialDirectories = false,
MatchType = MatchType.Simple,
};
/// <summary>
/// Files that are not content and are not listed at all: Febe's journal, its temporary files, the 4K Stogram
/// databases, Windows and macOS housekeeping files.
/// </summary>
public static bool IsIgnoredFile(string fileName)
{
ArgumentNullException.ThrowIfNull(fileName);
return IgnoredNames.Contains(fileName) || SafeFileWriter.IsTemporaryFile(fileName) || fileName.StartsWith("._", StringComparison.Ordinal);
}
/// <summary>The full path of a chosen folder, checked.</summary>
/// <exception cref="ImportSourceException">The folder cannot be used; the message says why.</exception>
public string Resolve(string chosen)
{
if (string.IsNullOrWhiteSpace(chosen))
{
throw new ImportSourceException("Scegli la cartella da importare.");
}
if (Root is null && !Path.IsPathFullyQualified(chosen))
{
throw new ImportSourceException("Scegli la cartella con il suo percorso completo.");
}
string full;
try
{
full = Trim(Root is { } root && !Path.IsPathFullyQualified(chosen)
? Path.GetFullPath(Path.Combine(root, chosen.TrimStart('/', '\\')))
: Path.GetFullPath(chosen));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
throw new ImportSourceException("Il percorso scelto non è valido: scegli di nuovo la cartella.", ex);
}
if (Root is { } r && !IsSameOrInside(full, r))
{
throw new ImportSourceException($"In Docker si importa solo da {r} o da una sua sottocartella: monta la cartella da importare in quel volume.");
}
if (!Directory.Exists(full))
{
throw new ImportSourceException(File.Exists(full)
? "Hai scelto un file: scegli la cartella che lo contiene."
: $"La cartella {full} non esiste più: controlla che il disco sia collegato e sceglila di nuovo.");
}
if (Root is not null && new DirectoryInfo(full).LinkTarget is not null)
{
throw new ImportSourceException("La cartella scelta è un collegamento: scegli la cartella a cui punta.");
}
if (_dataRoot is { } data && (IsSameOrInside(full, data) || IsSameOrInside(data, full)))
{
throw new ImportSourceException("La cartella scelta contiene la cartella dei dati di Febe o ne fa parte: scegli la cartella con le foto e i video da importare.");
}
if (_libraryRoot is { } library)
{
if (IsSameOrInside(library, full))
{
throw new ImportSourceException("La cartella scelta contiene la libreria di Febe: scegli una cartella fuori dalla libreria.");
}
if (IsSameOrInside(full, library) && InsideAccountFolder(full, library))
{
throw new ImportSourceException("La cartella scelta è la cartella di un account della libreria: i suoi file sono già in libreria.");
}
}
return full;
}
/// <summary>Checks a chosen folder and tells what it looks like (step 1).</summary>
/// <exception cref="ImportSourceException">The folder cannot be used.</exception>
public ImportSourceInfo Inspect(string chosen)
{
var full = Resolve(chosen);
var layout = SourceLayout.Inspect(full);
var looksLikeFebe = layout.UnitFolders.Any(f => File.Exists(AccountJournal.PathFor(layout.FolderPath(f))));
var looksLikeStogram = StogramHypothesisRecognizer.LooksLikeStogramFolder(full)
|| layout.FirstLevelFolders.Take(200).Any(f => StogramHypothesisRecognizer.LooksLikeStogramFolder(Path.Combine(full, f)));
return new ImportSourceInfo(full, DisplayPath(full), layout.RootName, IsReadOnly(full), looksLikeFebe, looksLikeStogram, layout.RootIsAccount, layout.FirstLevelFolders);
}
/// <summary>True when the folder cannot be written (configured read-only root, or the system says so).</summary>
public bool IsReadOnly(string fullPath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fullPath);
var full = Trim(Path.GetFullPath(fullPath));
return (_options.RootIsReadOnly && Root is { } root && IsSameOrInside(full, root)) || _probe.IsReadOnly(full);
}
/// <summary>
/// Subfolders offered by the picker. With a root (Docker) <paramref name="path"/> is relative to it and the result
/// paths are relative too; without a root it is an absolute folder.
/// </summary>
public IReadOnlyList<SourceFolderChoice> Browse(string? path = null)
{
string folder;
if (Root is { } root)
{
folder = string.IsNullOrWhiteSpace(path) ? root : Trim(Path.GetFullPath(Path.Combine(root, path.TrimStart('/', '\\'))));
if (!IsSameOrInside(folder, root))
{
throw new ImportSourceException($"Si sfoglia solo dentro {root}.");
}
}
else if (string.IsNullOrWhiteSpace(path))
{
throw new ImportSourceException("Scegli la cartella da sfogliare.");
}
else
{
folder = Trim(Path.GetFullPath(path));
}
if (!Directory.Exists(folder))
{
throw new ImportSourceException($"La cartella {folder} non esiste.");
}
return Directory.EnumerateDirectories(folder, "*", Enumeration(recursive: false))
.Order(StringComparer.Ordinal)
.Select(d => new SourceFolderChoice(
Path.GetFileName(d),
Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d,
Directory.EnumerateDirectories(d, "*", Enumeration(recursive: false)).Any()))
.ToList();
}
/// <summary>The path shown to Alberto: in Docker relative to the root, with the root's name in front.</summary>
public string DisplayPath(string fullPath)
{
if (Root is { } root && IsSameOrInside(fullPath, root))
{
var relative = Path.GetRelativePath(root, fullPath);
return relative == "." ? root : LibraryLayout.ToStored(Path.Combine(root, relative));
}
return fullPath;
}
private static bool InsideAccountFolder(string full, string library)
{
for (var folder = full; folder is not null && IsSameOrInside(folder, library) && !Same(folder, library); folder = Path.GetDirectoryName(folder))
{
if (File.Exists(AccountJournal.PathFor(folder)))
{
return true;
}
}
return false;
}
private static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison);
private static bool IsSameOrInside(string path, string folder)
{
var p = Trim(path);
var f = Trim(folder);
return string.Equals(p, f, PathComparison)
|| p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison);
}
private static string Trim(string path) => path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path;
}