using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.Core.IO;
///
/// The folders each home of the desktop keeps apart (owner review 5, #66): this PC's archive is the home ,
/// and every Chronos Server is a home of its own under , named by the server's stable id
/// (servers\<id:N>), or, for a server that announces none (an older server), by a hash of its address key
/// (servers\addr-<16 hex>: 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 (<workspace>\local, <workspace>\servers\<folder>)
/// and in the cache (<cache>\servers\<folder>\{proxies,render-node,import}). A folder name is never renamed
/// after the server: its name lives in beside it.
///
public static class HomeFolders
{
/// The folder of this PC's archive's home.
public const string Local = "local";
/// The folder that holds one folder per server home.
public const string Servers = "servers";
/// What a server home's folder says about its server (id, name, last address), for someone browsing it.
public const string ServerFile = "server.json";
/// A server home's proxies of its sequences, in the cache.
public const string Proxies = "proxies";
/// A server home's render-node downloads, in the cache.
public const string RenderNode = "render-node";
/// A server home's staged card imports, in the cache.
public const string Import = "import";
/// The start of a server key made from the server's announced id (id:<32 hex>).
public const string IdKeyPrefix = "id:";
/// The start of the folder of a server known by its address only.
public const string AddressPrefix = "addr-";
/// Hex digits of the address hash in a folder name (as the 1.0 proxy cache used).
public const int HashLength = 16;
///
/// The folder of a server home: the 32 hex digits of the id of an id key (id:<N>), else addr- and the
/// first 16 hex digits of the SHA-256 of the key (an address key, as SyncService.ServerKey makes it).
///
public static string ServerFolder(string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
return IdOfKey(serverKey) is { } id ? id.ToString("N") : AddressPrefix + AddressHash(serverKey);
}
/// The 16 hex digits the 1.0 proxy cache named a server's folder by: the start of the SHA-256 of its key.
public static string AddressHash(string serverKey)
{
ArgumentNullException.ThrowIfNull(serverKey);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(serverKey)))[..HashLength];
}
/// The id an id key names (id:<N>); null for an address key.
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;
/// The key of a server known by its announced id.
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");
}
///
/// A name a server home's folder can have: 32 lower-case hex digits (an id) or addr- with 16 lower-case hex
/// digits. Anything else under is not a home (left alone).
///
public static bool IsServerFolder(string? name) => name is { Length: > 0 } && (IdOfFolder(name) is not null || IsAddressFolder(name));
/// The server id a folder named by one stands for; null for an address folder or another name.
public static Guid? IdOfFolder(string? name) =>
name is { Length: 32 } && IsLowerHex(name) && Guid.TryParseExact(name, "N", out var id) && id != Guid.Empty ? id : null;
/// A folder of a server known by its address only (addr- and 16 lower-case hex digits).
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));
/// The folder of this PC's home under (a workspace or a cache folder).
public static string LocalPath(string root)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Local);
}
/// The folder of the home of under (a workspace or a cache folder).
public static string ServerPath(string root, string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Servers, ServerFolder(serverKey));
}
///
/// Where the originals a server's sequences download go by default (owner review 5, Q1): an archive of their own beside
/// this PC's, <parent of the archive>\<archive folder name> - <server name>, for example
/// D:\ChronosArchive - Studio NAS. The server's name is made safe as a folder name (); a
/// folder says is taken gets " (2)", " (3)"… With no archive of this PC's,
/// (where a first archive would go) stands for it.
///
/// The root of this PC's archive; null when there is none.
/// The server's name as its server/info gives it.
/// Where this PC's first archive would go (the desktop's default archive folder).
/// Whether a folder is taken (it exists, or another archive uses it); null takes an existing folder or file.
public static string OriginalsArchiveRoot(string? localArchiveRoot, string serverName, string fallbackArchiveRoot, Func? 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;
}
}
/// Characters no folder name may hold on Windows (and so on any PC a folder may be copied to).
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",
];
/// The longest folder name gives.
public const int MaxNameLength = 60;
///
/// 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 . "Server" when nothing is left.
///
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 text)
{
foreach (var c in text)
{
if (c is not ((>= '0' and <= '9') or (>= 'a' and <= 'f'))) return false;
}
return true;
}
}