using Febe.Core.Library; namespace Febe.Core.Import; /// Where sources may be chosen (spec §9.1 «Sorgente», §11). public sealed record ImportSourceOptions { /// /// Root of the sources. In Docker the volume /importa: a source is that folder or one of its subfolders. /// Null on Windows: any folder Alberto chooses. /// public string? Root { get; init; } /// /// The root is mounted read-only (the /importa volume, spec §11): «Sposta» is never offered below it, whatever /// the mount table says. /// public bool RootIsReadOnly { get; init; } /// Docker: sources under , read-only. public static ImportSourceOptions Docker(string root = "/importa") => new() { Root = root, RootIsReadOnly = true }; /// Windows (and development): any folder. public static ImportSourceOptions AnyFolder { get; } = new(); } /// What step 1 knows about a chosen source. /// Full path of the folder. /// Path shown to Alberto (relative to the root in Docker, e.g. «/importa/4K Stogram»). /// Folder name. /// The source cannot be written: «Sposta» does not appear (spec §9.4). /// Account folders with _febe.jsonl were found. /// /// A 4K Stogram database file is present (only its existence is checked): the interface may offer the hypothesis /// recognizer, saying it is unverified. /// /// The folder itself looks like one account (see ). /// First-level subfolders. public sealed record ImportSourceInfo( string FullPath, string DisplayPath, string Name, bool ReadOnly, bool LooksLikeFebeLibrary, bool LooksLikeStogram, bool RootIsAccount, IReadOnlyList Folders) { /// «Sposta» is offered only for writable sources. public bool CanMove => !ReadOnly; } /// A folder offered by the source picker (Docker: below /importa). /// Folder name. /// Path to pass back to (relative to the root when there is one). /// The folder has subfolders to open. public sealed record SourceFolderChoice(string Name, string Path, bool HasSubfolders); /// A source that cannot be used; the message (Italian) says why and what to do. public sealed class ImportSourceException : Exception { public ImportSourceException() { } public ImportSourceException(string message) : base(message) { } public ImportSourceException(string message, Exception innerException) : base(message, innerException) { } } /// Tells whether a folder can be written, without writing into it. public interface ISourceAccessProbe { bool IsReadOnly(string fullPath); } /// /// Read-only detection that never writes into the source: on Linux the mount options of the file system that holds the /// folder (ro, as for a Docker volume mounted with :ro); 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). /// public sealed class SystemSourceAccessProbe(Func? readMounts = null) : ISourceAccessProbe { private readonly Func _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)); } /// True when the mount that contains has the ro option. 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; } } } /// /// 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 _febe.jsonl may be imported, as the rebuild suggests). /// public sealed class ImportSources { private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; private static readonly HashSet 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; /// Root and read-only flag. /// The library folder (a source may not contain it). /// The Data folder (a source may not overlap it). /// Read-only detection; by default. 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)); } /// Full path of the root of the sources (Docker), or null (any folder). public string? Root { get; } /// Enumeration used everywhere on sources: hidden, system files and links are skipped. public static EnumerationOptions Enumeration(bool recursive) => new() { RecurseSubdirectories = recursive, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint, ReturnSpecialDirectories = false, MatchType = MatchType.Simple, }; /// /// 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. /// public static bool IsIgnoredFile(string fileName) { ArgumentNullException.ThrowIfNull(fileName); return IgnoredNames.Contains(fileName) || SafeFileWriter.IsTemporaryFile(fileName) || fileName.StartsWith("._", StringComparison.Ordinal); } /// The full path of a chosen folder, checked. /// The folder cannot be used; the message says why. 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; } /// Checks a chosen folder and tells what it looks like (step 1). /// The folder cannot be used. 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); } /// True when the folder cannot be written (configured read-only root, or the system says so). 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); } /// /// Subfolders offered by the picker. With a root (Docker) is relative to it and the result /// paths are relative too; without a root it is an absolute folder. /// public IReadOnlyList 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(); } /// The path shown to Alberto: in Docker relative to the root, with the root's name in front. 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; }