Files
Chronos/src/Chronos.Core/IO/HomeFolders.cs
T
Alby96 20d64af4a4
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-15 18:11:43 +01:00

179 lines
9.4 KiB
C#

using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.Core.IO;
/// <summary>
/// The folders each home of the desktop keeps apart (owner review 5, #66): this PC's archive is the home <see cref="Local"/>,
/// and every Chronos Server is a home of its own under <see cref="Servers"/>, named by the server's stable id
/// (<c>servers\&lt;id:N&gt;</c>), or, for a server that announces none (an older server), by a hash of its address key
/// (<c>servers\addr-&lt;16 hex&gt;</c>: the hash the 1.0 proxy cache named its folders by, so moving them is a rename).
/// The same names are used in the workspace (<c>&lt;workspace&gt;\local</c>, <c>&lt;workspace&gt;\servers\&lt;folder&gt;</c>)
/// and in the cache (<c>&lt;cache&gt;\servers\&lt;folder&gt;\{proxies,render-node,import}</c>). A folder name is never renamed
/// after the server: its name lives in <see cref="ServerFile"/> beside it.
/// </summary>
public static class HomeFolders
{
/// <summary>The folder of this PC's archive's home.</summary>
public const string Local = "local";
/// <summary>The folder that holds one folder per server home.</summary>
public const string Servers = "servers";
/// <summary>What a server home's folder says about its server (id, name, last address), for someone browsing it.</summary>
public const string ServerFile = "server.json";
/// <summary>A server home's proxies of its sequences, in the cache.</summary>
public const string Proxies = "proxies";
/// <summary>A server home's render-node downloads, in the cache.</summary>
public const string RenderNode = "render-node";
/// <summary>A server home's staged card imports, in the cache.</summary>
public const string Import = "import";
/// <summary>The start of a server key made from the server's announced id (<c>id:&lt;32 hex&gt;</c>).</summary>
public const string IdKeyPrefix = "id:";
/// <summary>The start of the folder of a server known by its address only.</summary>
public const string AddressPrefix = "addr-";
/// <summary>Hex digits of the address hash in a folder name (as the 1.0 proxy cache used).</summary>
public const int HashLength = 16;
/// <summary>
/// The folder of a server home: the 32 hex digits of the id of an id key (<c>id:&lt;N&gt;</c>), else <c>addr-</c> and the
/// first 16 hex digits of the SHA-256 of the key (an address key, as <c>SyncService.ServerKey</c> makes it).
/// </summary>
public static string ServerFolder(string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
return IdOfKey(serverKey) is { } id ? id.ToString("N") : AddressPrefix + AddressHash(serverKey);
}
/// <summary>The 16 hex digits the 1.0 proxy cache named a server's folder by: the start of the SHA-256 of its key.</summary>
public static string AddressHash(string serverKey)
{
ArgumentNullException.ThrowIfNull(serverKey);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(serverKey)))[..HashLength];
}
/// <summary>The id an id key names (<c>id:&lt;N&gt;</c>); null for an address key.</summary>
public static Guid? IdOfKey(string? serverKey) =>
serverKey is { Length: > 0 } key && key.StartsWith(IdKeyPrefix, StringComparison.OrdinalIgnoreCase)
&& Guid.TryParseExact(key.AsSpan(IdKeyPrefix.Length), "N", out var id) && id != Guid.Empty
? id
: null;
/// <summary>The key of a server known by its announced id.</summary>
public static string IdKey(Guid serverId)
{
if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId));
return IdKeyPrefix + serverId.ToString("N");
}
/// <summary>
/// A name a server home's folder can have: 32 lower-case hex digits (an id) or <c>addr-</c> with 16 lower-case hex
/// digits. Anything else under <see cref="Servers"/> is not a home (left alone).
/// </summary>
public static bool IsServerFolder(string? name) => name is { Length: > 0 } && (IdOfFolder(name) is not null || IsAddressFolder(name));
/// <summary>The server id a folder named by one stands for; null for an address folder or another name.</summary>
public static Guid? IdOfFolder(string? name) =>
name is { Length: 32 } && IsLowerHex(name) && Guid.TryParseExact(name, "N", out var id) && id != Guid.Empty ? id : null;
/// <summary>A folder of a server known by its address only (<c>addr-</c> and 16 lower-case hex digits).</summary>
public static bool IsAddressFolder(string? name) =>
name is { Length: > 0 } && name.Length == AddressPrefix.Length + HashLength && name.StartsWith(AddressPrefix, StringComparison.Ordinal)
&& IsLowerHex(name.AsSpan(AddressPrefix.Length));
/// <summary>The folder of this PC's home under <paramref name="root"/> (a workspace or a cache folder).</summary>
public static string LocalPath(string root)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Local);
}
/// <summary>The folder of the home of <paramref name="serverKey"/> under <paramref name="root"/> (a workspace or a cache folder).</summary>
public static string ServerPath(string root, string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Servers, ServerFolder(serverKey));
}
/// <summary>
/// Where the originals a server's sequences download go by default (owner review 5, Q1): an archive of their own beside
/// this PC's, <c>&lt;parent of the archive&gt;\&lt;archive folder name&gt; - &lt;server name&gt;</c>, for example
/// <c>D:\ChronosArchive - Studio NAS</c>. The server's name is made safe as a folder name (<see cref="SafeName"/>); a
/// folder <paramref name="taken"/> says is taken gets " (2)", " (3)"… With no archive of this PC's,
/// <paramref name="fallbackArchiveRoot"/> (where a first archive would go) stands for it.
/// </summary>
/// <param name="localArchiveRoot">The root of this PC's archive; null when there is none.</param>
/// <param name="serverName">The server's name as its <c>server/info</c> gives it.</param>
/// <param name="fallbackArchiveRoot">Where this PC's first archive would go (the desktop's default archive folder).</param>
/// <param name="taken">Whether a folder is taken (it exists, or another archive uses it); null takes an existing folder or file.</param>
public static string OriginalsArchiveRoot(string? localArchiveRoot, string serverName, string fallbackArchiveRoot, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fallbackArchiveRoot);
var archive = Path.TrimEndingDirectorySeparator(Path.GetFullPath(string.IsNullOrWhiteSpace(localArchiveRoot) ? fallbackArchiveRoot : localArchiveRoot));
var parent = Path.GetDirectoryName(archive) ?? archive;
var name = Path.GetFileName(archive);
if (string.IsNullOrEmpty(name)) name = SafeName(Path.GetFileName(Path.TrimEndingDirectorySeparator(fallbackArchiveRoot)));
var stem = name + " - " + SafeName(serverName);
taken ??= path => Directory.Exists(path) || File.Exists(path);
for (var n = 1; ; n++)
{
var candidate = Path.Combine(parent, n == 1 ? stem : stem + " (" + n.ToString(CultureInfo.InvariantCulture) + ")");
if (!taken(candidate)) return candidate;
}
}
/// <summary>Characters no folder name may hold on Windows (and so on any PC a folder may be copied to).</summary>
private static readonly char[] Unsafe = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
private static readonly string[] Reserved =
[
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9",
];
/// <summary>The longest folder name <see cref="SafeName"/> gives.</summary>
public const int MaxNameLength = 60;
/// <summary>
/// <paramref name="name"/> as a folder name every Windows file system takes: characters it refuses and control characters
/// become spaces, runs of spaces one, leading and trailing spaces and dots go, a device name (CON, NUL, COM1…) gets an
/// underscore, and it is cut to <see cref="MaxNameLength"/>. "Server" when nothing is left.
/// </summary>
public static string SafeName(string? name)
{
var text = new StringBuilder(name?.Length ?? 0);
foreach (var c in name ?? string.Empty)
{
var bad = char.IsControl(c) || Array.IndexOf(Unsafe, c) >= 0;
var space = bad || char.IsWhiteSpace(c);
if (space)
{
if (text.Length > 0 && text[^1] != ' ') text.Append(' ');
continue;
}
text.Append(c);
}
var safe = text.ToString().Trim(' ', '.');
if (safe.Length > MaxNameLength) safe = safe[..MaxNameLength].TrimEnd(' ', '.');
if (safe.Length == 0) return "Server";
var stem = safe.Split('.')[0];
return Reserved.Contains(stem, StringComparer.OrdinalIgnoreCase) ? safe + "_" : safe;
}
private static bool IsLowerHex(ReadOnlySpan<char> text)
{
foreach (var c in text)
{
if (c is not ((>= '0' and <= '9') or (>= 'a' and <= 'f'))) return false;
}
return true;
}
}