CI / Build and test (pull_request) Successful in 8m52s
CI / PostgreSQL 16 integration (pull_request) Successful in 9m21s
CI / Docker image (pull_request) Successful in 1m48s
CI / YAML check (pull_request) Successful in 7s
CI / Windows tests and installer (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Successful in 8m59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1241 lines
75 KiB
C#
1241 lines
75 KiB
C#
using System.IO;
|
||
using System.Text.Json;
|
||
using Chronos.App.Infrastructure;
|
||
using Chronos.Core.Archiving;
|
||
using Chronos.Core.Diagnostics;
|
||
using Chronos.Core.IO;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Core.Project;
|
||
using Chronos.Data;
|
||
using Chronos.Data.Archiving;
|
||
using Chronos.Data.Archiving.Jobs;
|
||
using Chronos.Data.Jobs;
|
||
using Chronos.Data.Projects;
|
||
using Chronos.Data.Workspaces;
|
||
using Chronos.Protocol;
|
||
|
||
namespace Chronos.App.Workspace;
|
||
|
||
/// <summary>A workspace operation was refused for a reason the user can act on; the message is one localized sentence.</summary>
|
||
public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner)
|
||
{
|
||
/// <summary>The workspace folder itself was refused (it lies inside a library): another folder is the way on (Settings › Workspace › Change).</summary>
|
||
public bool FolderRefused { get; init; }
|
||
}
|
||
|
||
/// <summary>A project of this PC's workspace, as Edit's picker and the editor list it.</summary>
|
||
/// <param name="HasMedia">The workspace holds the project's media (a copy that ended); without them it cannot open.</param>
|
||
/// <param name="Saved">When its working state was last written.</param>
|
||
/// <param name="Damaged">
|
||
/// Its working state (<c>project.chronos</c>) cannot be read: listed by the name it is still known by (else its folder), it
|
||
/// cannot open, and Remove local copy can only keep its files aside in the workspace's trash (Discard).
|
||
/// </param>
|
||
/// <remarks>
|
||
/// A copy this Chronos cannot read is no project of its sequence here (<see cref="SequenceId"/> is empty): nothing opens,
|
||
/// checks out or is copied over it.
|
||
/// </remarks>
|
||
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
|
||
DateTimeOffset Saved, bool Damaged = false)
|
||
{
|
||
/// <summary>
|
||
/// Its working state was written by a newer Chronos (a project file format this one does not know): listed as such,
|
||
/// it neither opens nor goes from here, and nothing in it is changed; a newer Chronos opens it.
|
||
/// </summary>
|
||
public bool Newer { get; init; }
|
||
|
||
/// <summary>
|
||
/// A copy this Chronos cannot read (<see cref="Damaged"/> or <see cref="Newer"/>): the name it is still known by (its
|
||
/// project's, else its sequence's), from what of its project file can be read or from the library's index; null when
|
||
/// neither knows it.
|
||
/// </summary>
|
||
public string? KnownName { get; init; }
|
||
|
||
/// <summary>This Chronos reads its working state: it can open.</summary>
|
||
public bool IsReadable => !Damaged && !Newer;
|
||
|
||
/// <summary>The project's home is a server (phase 5b), not this PC's archive.</summary>
|
||
public bool IsServerHome => !Home.IsArchive;
|
||
}
|
||
|
||
/// <summary>What changing the workspace folder to <see cref="Folder"/> does: Edit lists its projects from then on; nothing is moved.</summary>
|
||
/// <param name="Current">The folder in use, whose projects stay where they are (listed again once it is chosen back).</param>
|
||
/// <param name="ProjectsLeft">The projects the folder in use holds.</param>
|
||
/// <param name="ProjectsFound">The projects <see cref="Folder"/> holds already (a workspace used before).</param>
|
||
/// <param name="InsideLibrary">The folder lies inside a library: refused, as the copy would put its files among the library's.</param>
|
||
public sealed record WorkspaceFolderPlan(string Current, string Folder, int ProjectsLeft, int ProjectsFound, bool InsideLibrary)
|
||
{
|
||
/// <summary>The folder chosen is the one in use: nothing to change.</summary>
|
||
public bool IsSame => string.Equals(Path.TrimEndingDirectorySeparator(Current), Path.TrimEndingDirectorySeparator(Folder), StringComparison.OrdinalIgnoreCase);
|
||
}
|
||
|
||
/// <summary>What "Open in workspace" shows of the copy it queues: its bytes (as the copy reckons them) and the free bytes of the workspace's drive.</summary>
|
||
/// <param name="Bytes">What the copy of the proxies writes.</param>
|
||
/// <param name="OriginalsBytes">What the copy of the originals writes besides (phase 5c); null when not known.</param>
|
||
public sealed record WorkspaceCopyFacts(long Bytes, long? Free, long? OriginalsBytes = null)
|
||
{
|
||
/// <summary>
|
||
/// The drive lacks room for the copy of <paramref name="media"/> (<see cref="BundleMedia.Originals"/>: the proxies and the
|
||
/// originals) and the reserve the copy keeps free.
|
||
/// </summary>
|
||
public bool TooLittleSpaceFor(string media) =>
|
||
Free is { } free && free < Bytes + (media == BundleMedia.Originals ? OriginalsBytes ?? 0 : 0) + WorkspaceJobs.CopySpaceReserve;
|
||
|
||
/// <summary>The drive lacks the copy and the reserve the copy keeps: it would stop saying so.</summary>
|
||
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
|
||
}
|
||
|
||
/// <summary>
|
||
/// A workspace project's home told that the project changed there (owner review 2, R8, phase 5b: a server's
|
||
/// <c>projectChanged</c>): <see cref="Change"/> is one of <c>Protocol.ProjectChanges</c>; null for every project of
|
||
/// <see cref="Server"/> when changes may have been missed (its events were lost for a while).
|
||
/// </summary>
|
||
public sealed record WorkspaceHomeChange(string Server, Guid? ProjectId, string? Change);
|
||
|
||
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
|
||
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
|
||
|
||
/// <summary>What Save version did: the version (null when nothing changed), its sync when Sync automatically is on, where the project stands.</summary>
|
||
/// <param name="SyncError">Why the sync after it did not happen (the home out of reach, the project busy); the version waits here.</param>
|
||
public sealed record WorkspaceSaveResult(ProjectVersion? Version, WorkspaceSyncResult? Synced, WorkspaceStatus Status, Exception? SyncError);
|
||
|
||
/// <summary>A project's history as the History flyout lists it: newest first, the versions not sent yet on top.</summary>
|
||
/// <param name="Unsent">The ids among <paramref name="Versions"/> that wait to be sent to the home.</param>
|
||
/// <param name="Offline">The home could not be asked: only the versions this workspace keeps are listed.</param>
|
||
public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IReadOnlySet<Guid> Unsent, bool Offline);
|
||
|
||
/// <summary>
|
||
/// The plan of "Remove local copy": what the project's folder holds (files and bytes) and what would not be at the home
|
||
/// after it (versions not sent, changes not saved as a version, a conflict to settle).
|
||
/// </summary>
|
||
/// <param name="Gone">
|
||
/// The home answered it no longer has the project or its sequence: nothing can be sent or checked there, so the copy can
|
||
/// only go with its work kept aside (Discard).
|
||
/// </param>
|
||
/// <param name="Damaged">The working state cannot be read: what it holds is not known, so the copy can only go with its files kept aside (Discard).</param>
|
||
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false,
|
||
bool Damaged = false)
|
||
{
|
||
/// <summary>
|
||
/// A damaged copy: the name Discard asks to type (<see cref="WorkspaceEntry.KnownName"/>); null when no name is known,
|
||
/// and the number of its files is typed instead.
|
||
/// </summary>
|
||
public string? KnownName { get; init; }
|
||
|
||
/// <summary>
|
||
/// Local renders not at the home yet (phase 5c, the project's ledger): Send first sends them, Discard keeps them in the
|
||
/// workspace's trash with the rest of the work not sent.
|
||
/// </summary>
|
||
public int UnsentRenders { get; init; }
|
||
|
||
/// <summary>
|
||
/// Originals the workspace holds that the home no longer holds with the same SHA-256 (phase 5c): they go to the
|
||
/// workspace's trash, never deleted, when the copy is removed.
|
||
/// </summary>
|
||
public int LastOriginals { get; init; }
|
||
|
||
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
|
||
public bool IsSafe => Unsent == 0 && UnsentRenders == 0 && !Modified && !Conflict && !Damaged;
|
||
}
|
||
|
||
/// <summary>
|
||
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
|
||
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
|
||
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and the homes of its projects: this PC's
|
||
/// archive (<see cref="ArchiveProjectHome"/>) or, from phase 5b, the signed-in server (<see cref="ServerHomes"/>, a
|
||
/// <see cref="ServerProjectHome"/>; a project of a server this PC is not signed in to reads as offline, its work waiting
|
||
/// here). Every operation runs off the UI thread and returns where the project stands. Nothing a workspace holds is lost: a
|
||
/// version is sent before its copy goes, a copy is removed only once the home verifiably holds its head, the work a user
|
||
/// chose to discard is kept in <c><workspace>/.trash</c>, and versions the home holds are pruned past Settings ›
|
||
/// Workspace › Kept versions only after the home returned each, a page of its history at a time. A capture (sample data, no
|
||
/// engine) has no workspace: Edit opens the library there.
|
||
/// </summary>
|
||
public sealed partial class WorkspaceHost
|
||
{
|
||
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
|
||
public const string TrashFolder = ".trash";
|
||
|
||
private readonly AppEnvironment _environment;
|
||
private readonly AppSettings _settings;
|
||
private readonly Action _savePreferences;
|
||
private readonly Func<ChronosDatabase?> _db;
|
||
private readonly Func<ArchiveService?> _archives;
|
||
private readonly Func<JobEngine?> _engine;
|
||
private readonly Lock _gate = new();
|
||
private readonly Dictionary<Guid, Guid> _copies = [];
|
||
private OpenWorkspace? _open;
|
||
|
||
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
|
||
Func<JobEngine?> engine)
|
||
{
|
||
_environment = environment;
|
||
_settings = settings;
|
||
_savePreferences = savePreferences;
|
||
_db = db;
|
||
_archives = archives;
|
||
_engine = engine;
|
||
}
|
||
|
||
/// <summary>
|
||
/// The PC versions made here carry ("STUDIO-PC"): data, shown as it is by History (no words of the UI in it, so every
|
||
/// language reads it alike).
|
||
/// </summary>
|
||
public static string ClientName { get; } = Environment.MachineName;
|
||
|
||
/// <summary>How long an operation waits for a project another writer holds (a copy job writing its media index).</summary>
|
||
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
|
||
|
||
/// <summary>The workspace folder of a data folder: <c>workspace</c> beside the index.</summary>
|
||
public static string DefaultRoot(AppEnvironment environment)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(environment);
|
||
return Path.Combine(environment.DataDirectory, WorkspaceStore.DefaultFolderName);
|
||
}
|
||
|
||
/// <summary>The folder in use: Settings › Workspace › Folder, else <see cref="DefaultRoot"/>.</summary>
|
||
public string Root => _settings.WorkspaceFolder is { Length: > 0 } folder ? Path.GetFullPath(folder) : DefaultRoot(_environment);
|
||
|
||
/// <summary>Edit opens workspace projects (false in a capture, whose sample library has no engine to copy media).</summary>
|
||
public bool IsEnabled => !_environment.IsCapture;
|
||
|
||
/// <summary>The workspace can be used now: enabled, with the index and the archive engine open.</summary>
|
||
public bool IsAvailable => IsEnabled && _db() is not null && _archives() is not null;
|
||
|
||
public AppSettings Settings => _settings;
|
||
|
||
/// <summary>The sync over the workspace folder in use (made, with the folder and its manifest, at first use).</summary>
|
||
/// <exception cref="IOException">The folder cannot be made or read.</exception>
|
||
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
|
||
public WorkspaceSync Sync
|
||
{
|
||
get
|
||
{
|
||
var root = Root;
|
||
lock (_gate)
|
||
{
|
||
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
var store = new WorkspaceStore(root);
|
||
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
|
||
}
|
||
return open.Sync;
|
||
}
|
||
}
|
||
}
|
||
|
||
public WorkspaceStore Store => Sync.Store;
|
||
|
||
/// <summary>
|
||
/// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not
|
||
/// signed in to that server, or it keeps no projects. Without it every server home reads as out of reach.
|
||
/// </summary>
|
||
public Func<BundleHome, IProjectHome?>? ServerHomes { get; set; }
|
||
|
||
/// <summary>A workspace project's home told that it changed there (any thread): its state is read again.</summary>
|
||
public event Action<WorkspaceHomeChange>? HomeChanged;
|
||
|
||
/// <summary>The home of a workspace project; null for a home this PC cannot reach now (the index not open, a server it is not signed in to).</summary>
|
||
public IProjectHome? HomeOf(BundleHome home)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(home);
|
||
if (!home.IsArchive) return ServerHomes?.Invoke(home);
|
||
return _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
|
||
}
|
||
|
||
/// <summary>The home of a sequence of this PC's archive (<paramref name="sequenceId"/> is in its index).</summary>
|
||
public static BundleHome ArchiveHome(Guid sequenceId) => new(BundleHome.ArchiveKind, sequenceId);
|
||
|
||
/// <summary>The home of a sequence of this PC's archive.</summary>
|
||
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
|
||
public IProjectHome HomeOfSequence(Guid sequenceId) => Reachable(ArchiveHome(sequenceId));
|
||
|
||
/// <summary>The home <paramref name="home"/> names, which must be reachable now.</summary>
|
||
/// <exception cref="WorkspaceException">The index or the archive engine is not open (this PC's archive).</exception>
|
||
/// <exception cref="HomeUnavailableException">This PC is not signed in to the server, or it keeps no projects.</exception>
|
||
public IProjectHome Reachable(BundleHome home) =>
|
||
HomeOf(home) ?? (home.IsArchive
|
||
? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"))
|
||
: throw new HomeUnavailableException("This PC is not signed in to the server of the project, or it keeps no projects."));
|
||
|
||
/// <summary>
|
||
/// The signed-in server told that a project changed there (phase 5b), or (<paramref name="change"/> null) that changes
|
||
/// may have been missed: projects of this workspace whose home it is are told (<see cref="HomeChanged"/>).
|
||
/// </summary>
|
||
public void OnServerProjectChanged(string server, ProjectChangedEvent? change)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(server);
|
||
if (change is null)
|
||
{
|
||
HomeChanged?.Invoke(new WorkspaceHomeChange(server, null, null));
|
||
return;
|
||
}
|
||
// The folder is named by the project's id: only a project this workspace holds, of that server and sequence, is told.
|
||
BundleHome home;
|
||
try
|
||
{
|
||
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
|
||
|| !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase))
|
||
return;
|
||
home = held;
|
||
}
|
||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||
{
|
||
Log.Info("workspace", $"A change of project {change.ProjectId} on {server} could not be matched: {ex.Message}");
|
||
return;
|
||
}
|
||
if (change.Change != ProjectChanges.Renamed)
|
||
{
|
||
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
|
||
return;
|
||
}
|
||
// A rename at the server is written to the copy here before it is told, so the state read again shows the new name.
|
||
_ = FollowNameThenTellAsync(server, home, change);
|
||
}
|
||
|
||
private async Task FollowNameThenTellAsync(string server, BundleHome home, ProjectChangedEvent change)
|
||
{
|
||
try
|
||
{
|
||
// Nothing is written into a folder being moved: the next status read takes the name.
|
||
if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move");
|
||
else if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} could not be followed: {ex.Message}");
|
||
}
|
||
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
|
||
}
|
||
|
||
/// <summary>
|
||
/// The projects of the workspace; one whose working state cannot be read is listed as damaged (<see cref="WorkspaceEntry.Damaged"/>),
|
||
/// one a newer Chronos wrote as such (<see cref="WorkspaceEntry.Newer"/>), never hidden, and logged. A workspace folder not
|
||
/// made yet that lies inside a library is not made by listing it: it lists nothing.
|
||
/// </summary>
|
||
public Task<IReadOnlyList<WorkspaceEntry>> ListAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
|
||
var entries = new List<WorkspaceEntry>();
|
||
foreach (var project in Store.List())
|
||
{
|
||
try
|
||
{
|
||
entries.Add(await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false));
|
||
}
|
||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||
{
|
||
// One copy that cannot be listed never hides the others.
|
||
Log.Warning("workspace", $"The project in {project.Folder} could not be listed", ex);
|
||
}
|
||
}
|
||
return (IReadOnlyList<WorkspaceEntry>)entries;
|
||
}, cancellationToken);
|
||
|
||
/// <summary>The workspace projects of one sequence, as Edit opens one.</summary>
|
||
/// <exception cref="WorkspaceException">The workspace folder is being moved (<c>Errors.Workspace.Moving</c>).</exception>
|
||
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||
{
|
||
EnsureNotMoving();
|
||
return [.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
|
||
}
|
||
|
||
/// <summary>A workspace project by id (damaged or newer when this Chronos cannot read its working state); null when the workspace has none.</summary>
|
||
/// <exception cref="WorkspaceException">The workspace folder is being moved (<c>Errors.Workspace.Moving</c>).</exception>
|
||
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
|
||
return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
|
||
}, cancellationToken);
|
||
|
||
/// <summary>Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged.</summary>
|
||
public static WorkspaceException Unreadable(WorkspaceEntry entry)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(entry);
|
||
return new WorkspaceException(Loc.L(entry.Newer ? "Errors.Workspace.NewerCopy" : "Errors.Workspace.Damaged"));
|
||
}
|
||
|
||
/// <summary>
|
||
/// What changing the workspace folder to <paramref name="folder"/> would do (Settings › Workspace › Change, and the
|
||
/// refusal of a folder inside a library): the projects the folder in use keeps where they are, those the new one holds
|
||
/// already, and whether it lies inside a library. Nothing is written.
|
||
/// </summary>
|
||
public Task<WorkspaceFolderPlan> PlanFolderAsync(string folder, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||
var target = Path.GetFullPath(folder);
|
||
return new WorkspaceFolderPlan(Root, target, CountProjects(Root), CountProjects(target), await InsideALibraryAsync(target, cancellationToken).ConfigureAwait(false));
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// Edit's workspace becomes <paramref name="folder"/> (made, with its manifest, when it is new): Settings › Workspace ›
|
||
/// Folder names it from now on (none when it is the default). The projects of the folder left stay there, untouched.
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">The folder lies inside a library (<see cref="WorkspaceException.FolderRefused"/>), or the workspace is being moved.</exception>
|
||
/// <exception cref="IOException">The folder cannot be made or read.</exception>
|
||
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
|
||
public async Task UseFolderAsync(string folder, CancellationToken cancellationToken = default)
|
||
{
|
||
EnsureNotMoving();
|
||
var plan = await PlanFolderAsync(folder, cancellationToken).ConfigureAwait(false);
|
||
if (plan.IsSame) return;
|
||
if (plan.InsideLibrary) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder)) { FolderRefused = true };
|
||
// Opened before it is named: a folder that is no workspace is refused while the one in use still is.
|
||
await Task.Run(() => new WorkspaceStore(plan.Folder), cancellationToken).ConfigureAwait(false);
|
||
// Back on the caller's thread (the UI's): the settings are written there.
|
||
_settings.WorkspaceFolder = string.Equals(plan.Folder, Path.GetFullPath(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : plan.Folder;
|
||
_savePreferences();
|
||
Log.Info("workspace", $"The workspace folder is now {plan.Folder} ({plan.ProjectsLeft} project(s) stay in {plan.Current})");
|
||
}
|
||
|
||
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
|
||
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||
{
|
||
var projects = await ProjectsOfAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var last) && projects.FirstOrDefault(p => p.ProjectId == last) is { } recent) return recent;
|
||
return projects.OrderByDescending(p => p.Saved).FirstOrDefault();
|
||
}
|
||
|
||
/// <summary>Remembers <paramref name="projectId"/> as the project of <paramref name="sequenceId"/> to open next time.</summary>
|
||
public void Remember(Guid sequenceId, Guid projectId)
|
||
{
|
||
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId) return;
|
||
_settings.WorkspaceRecent[sequenceId] = projectId;
|
||
_savePreferences();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Records that Edit opened <paramref name="projectId"/> at <paramref name="at"/> (now when null): the clean-up's Clean
|
||
/// after goes by it (phase 5c, <see cref="AppSettings.WorkspaceOpened"/>). Call it on the UI thread, which writes the settings.
|
||
/// </summary>
|
||
public void RecordOpened(Guid projectId, DateTimeOffset? at = null)
|
||
{
|
||
_settings.WorkspaceOpened[projectId] = at ?? DateTimeOffset.UtcNow;
|
||
_savePreferences();
|
||
}
|
||
|
||
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
|
||
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
|
||
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
|
||
|
||
/// <summary>The live projects of <paramref name="home"/>'s sequence, Main first (made from the sequence's settings when it has none yet).</summary>
|
||
/// <exception cref="HomeUnavailableException">A server home this PC cannot reach now.</exception>
|
||
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(BundleHome home, CancellationToken cancellationToken = default)
|
||
{
|
||
var reached = Reachable(home);
|
||
return Task.Run(() => reached.ListAsync(cancellationToken), cancellationToken);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Brings a project of <paramref name="sequenceId"/> into the workspace and queues the copy of its media: the project
|
||
/// <paramref name="projectId"/>, else a new one named <paramref name="newName"/> (from Main's head), else Main. A
|
||
/// project already here keeps its working state; only its media are copied again.
|
||
/// </summary>
|
||
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
|
||
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
|
||
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
|
||
public Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
|
||
CancellationToken cancellationToken = default) =>
|
||
CheckoutAsync(ArchiveHome(sequenceId), projectId, newName, media, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// Brings a project of <paramref name="home"/>'s sequence (this PC's archive, or the signed-in server) into the workspace
|
||
/// and queues the copy of its media, as <see cref="CheckoutAsync(Guid, Guid?, string?, string, CancellationToken)"/>.
|
||
/// </summary>
|
||
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
|
||
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
|
||
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
|
||
public async Task<WorkspaceCheckout> CheckoutAsync(BundleHome home, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
|
||
CancellationToken cancellationToken = default)
|
||
{
|
||
var reached = Reachable(home);
|
||
var sequenceId = home.SequenceId;
|
||
var checkout = await Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
|
||
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false))
|
||
throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root)) { FolderRefused = true };
|
||
SequenceProject project;
|
||
if (newName is not null)
|
||
{
|
||
project = await reached.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
else
|
||
{
|
||
var listed = await reached.ListAsync(cancellationToken).ConfigureAwait(false);
|
||
project = projectId is { } id
|
||
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
|
||
// A server's sequence with no photo yet has no projects at all.
|
||
: listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet.");
|
||
}
|
||
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
|
||
if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
|
||
throw Unreadable(unreadable);
|
||
var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
|
||
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
|
||
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
|
||
}, cancellationToken);
|
||
// Back on the caller's thread (the UI's): the settings are written there.
|
||
Remember(sequenceId, checkout.Project.Id);
|
||
return checkout;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Queues the copy of a workspace project's media again ("Update media": the home's frames changed), unless one is
|
||
/// waiting or running already: that one is returned.
|
||
/// </summary>
|
||
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
var bundle = Existing(projectId).ReadBundle();
|
||
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, cancellationToken)
|
||
.ConfigureAwait(false);
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached
|
||
/// (a server this PC is not signed in to among them) reads as offline; one that answers it no longer has the project or
|
||
/// its sequence (the sequence left the index, the project was deleted there) reads as <see cref="WorkspaceState.Gone"/>,
|
||
/// whose local copy can then only be removed (nothing is removed by itself).
|
||
/// </summary>
|
||
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
var project = Existing(projectId);
|
||
var named = project.ReadBundle().Workspace!.Home;
|
||
var home = askHome ? HomeOf(named) : null;
|
||
try
|
||
{
|
||
if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
|
||
{
|
||
var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
|
||
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"The home of project {projectId} could not be asked: {ex.Message}");
|
||
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||
return local with
|
||
{
|
||
Offline = true,
|
||
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict && !gone ? local.State
|
||
: gone ? WorkspaceState.Gone
|
||
: WorkspaceState.Offline,
|
||
// Gone holds no conflict to answer; the one recorded stays in the copy.
|
||
Conflict = gone ? null : local.Conflict,
|
||
};
|
||
}
|
||
|
||
static WorkspaceStatus Offline(WorkspaceStatus local) =>
|
||
local with
|
||
{
|
||
Offline = true,
|
||
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline,
|
||
};
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// "Save version": the working state as a new local version with <paramref name="note"/> (none when nothing changed
|
||
/// since the last), then, with Settings › Workspace › Sync automatically, the sync with the home
|
||
/// (<see cref="SyncAsync"/>); a home out of reach leaves the version waiting here.
|
||
/// </summary>
|
||
/// <exception cref="InvalidOperationException">The project is read-only, has a conflict to settle, or names frames the workspace has no media of.</exception>
|
||
public async Task<WorkspaceSaveResult> SaveVersionAsync(Guid projectId, string? note, CancellationToken cancellationToken = default)
|
||
{
|
||
var version = await Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
|
||
}, cancellationToken).ConfigureAwait(false);
|
||
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
|
||
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
|
||
try
|
||
{
|
||
var synced = await SyncAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||
return new WorkspaceSaveResult(version, synced, synced.Status, null);
|
||
}
|
||
catch (Exception ex) when (ex is HomeUnavailableException or LeaseUnavailableException or WorkspaceSyncException or WorkspaceException or ProjectException
|
||
or DatabaseException)
|
||
{
|
||
// The version is saved here all the same: it waits for the next sync.
|
||
Log.Info("workspace", $"Version of project {projectId} not sent yet: {ex.Message}");
|
||
return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
|
||
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// "Sync": the home's new versions taken (the working state and the local versions moved onto them), then the local
|
||
/// versions sent in order, then the versions past Kept versions pruned. A real conflict stops it before anything is
|
||
/// sent (<see cref="WorkspaceState.Conflict"/>).
|
||
/// </summary>
|
||
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost.</exception>
|
||
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
|
||
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
var home = HomeOfProject(projectId);
|
||
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
|
||
if (pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone) return pulled;
|
||
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
|
||
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// Settles the conflict a sync stopped at, as <paramref name="shown"/> listed it to the user (else as recorded), then
|
||
/// sends what waits. When what differs now is not what was shown, nothing is settled: the conflict found now comes back
|
||
/// (<see cref="WorkspaceState.Conflict"/>) to be asked again. <see cref="ConflictChoice.SaveBoth"/> sends this
|
||
/// workspace's versions to a sibling project named "<name> (<this PC>)" (a number added when that name is taken).
|
||
/// </summary>
|
||
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
|
||
WorkspaceConflict? shown = null, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
var home = HomeOfProject(projectId);
|
||
WorkspaceSyncResult resolved;
|
||
if (choice == ConflictChoice.SaveBoth)
|
||
{
|
||
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
|
||
try
|
||
{
|
||
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
|
||
{
|
||
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
if (resolved.Status.State == WorkspaceState.Conflict)
|
||
{
|
||
Log.Info("workspace", $"Conflict of project {projectId} not settled ({choice}): what differs changed since it was shown");
|
||
return resolved;
|
||
}
|
||
// Deleted in the library: nothing more to send (a Save both's copy holds the versions already).
|
||
if (resolved.Status.State == WorkspaceState.Gone) return resolved;
|
||
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
|
||
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs)
|
||
{
|
||
Kept = resolved.Kept,
|
||
};
|
||
}, cancellationToken);
|
||
|
||
/// <summary>"<paramref name="name"/> (<c>PC</c>)", within the 60 characters of a project name.</summary>
|
||
public static string SiblingName(string name)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(name);
|
||
var suffix = " (" + Environment.MachineName + ")";
|
||
if (suffix.Length >= ProjectService.MaxNameLength) suffix = suffix[..(ProjectService.MaxNameLength / 2)] + ")";
|
||
var room = ProjectService.MaxNameLength - suffix.Length;
|
||
return (name.Length > room ? name[..room].TrimEnd() : name) + suffix;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Brings version <paramref name="versionId"/> back as the working state (uncommitted changes saved as a version first);
|
||
/// returns it, its positions on the media's frames.
|
||
/// </summary>
|
||
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
|
||
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
|
||
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
|
||
var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
|
||
return restored;
|
||
}, cancellationToken);
|
||
|
||
/// <summary>The project's history, newest first: the versions not sent yet, then the home's (this workspace's own while the home is out of reach).</summary>
|
||
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
var project = Existing(projectId);
|
||
var unsent = Sync.Unpushed(projectId);
|
||
var home = HomeOf(project.ReadBundle().Workspace!.Home);
|
||
IReadOnlyList<ProjectVersion> stored;
|
||
var offline = false;
|
||
try
|
||
{
|
||
stored = home is null
|
||
? throw new HomeUnavailableException("The project's home cannot be reached from this PC.")
|
||
: await home.HistoryAsync(projectId, null, limit, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
|
||
{
|
||
Log.Info("workspace", $"The history of project {projectId} is read from the workspace: {ex.Message}");
|
||
offline = true;
|
||
stored = [.. project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).Take(limit)];
|
||
}
|
||
var ids = unsent.Select(v => v.Id).ToHashSet();
|
||
return new WorkspaceHistory([.. unsent.Reverse(), .. stored.Where(v => !ids.Contains(v.Id))], ids, offline);
|
||
}, cancellationToken);
|
||
|
||
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
|
||
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
|
||
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default) =>
|
||
CreateProjectAsync(ArchiveHome(sequenceId), name, fromVersionId, cancellationToken);
|
||
|
||
/// <summary>A new project of <paramref name="home"/>'s sequence named <paramref name="name"/> from <paramref name="fromVersionId"/>, else from Main's head.</summary>
|
||
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
|
||
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
|
||
public Task<SequenceProject> CreateProjectAsync(BundleHome home, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
|
||
{
|
||
var reached = Reachable(home);
|
||
return Task.Run(async () =>
|
||
{
|
||
var created = await reached.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {home.SequenceId}");
|
||
return created;
|
||
}, cancellationToken);
|
||
}
|
||
|
||
/// <summary>Renames a project at its home, then its working state here.</summary>
|
||
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
|
||
/// <exception cref="HomeUnavailableException">The home cannot be reached now: the name stays.</exception>
|
||
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
var project = Existing(projectId);
|
||
var renamed = await HomeOfProject(projectId).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
|
||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||
{
|
||
var bundle = project.ReadBundle();
|
||
project.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Name = renamed.Name } });
|
||
}
|
||
Log.Info("workspace", $"Project {projectId} renamed '{renamed.Name}'");
|
||
return renamed.Name;
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// Deletes a project (never Main): the working state saved and sent first, so its home's trash
|
||
/// (<c>.chronos/projects/.trash</c>) holds every version; then the local copy goes.
|
||
/// </summary>
|
||
/// <returns>
|
||
/// False when the home deleted the project but its local copy could not be removed (a file in use): the copy stays,
|
||
/// and Remove local copy takes it later.
|
||
/// </returns>
|
||
/// <exception cref="WorkspaceException">Something could not be sent (the home out of reach, a conflict): nothing was deleted.</exception>
|
||
/// <exception cref="ProjectException">Main, or the project is gone.</exception>
|
||
public async Task<bool> DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
|
||
{
|
||
var (sequenceId, removed) = await Task.Run(async () =>
|
||
{
|
||
EnsureNotMoving();
|
||
var project = Existing(projectId);
|
||
var workspace = project.ReadBundle().Workspace!;
|
||
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
|
||
var home = HomeOfProject(projectId);
|
||
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
|
||
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
|
||
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
|
||
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(workspace.Home));
|
||
await home.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
|
||
try
|
||
{
|
||
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
|
||
return (workspace.Home.SequenceId, true);
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or LeaseUnavailableException)
|
||
{
|
||
// The home's delete stands (its trash holds every version); the copy, all of it sent and put back whole, waits
|
||
// for Remove local copy. One whose working state could not go back is no longer listed: nothing waits for it.
|
||
Log.Warning("workspace", $"Project {projectId} was deleted at its home, but its local copy stays", ex);
|
||
return (workspace.Home.SequenceId, !project.Exists);
|
||
}
|
||
}, cancellationToken);
|
||
Forget(sequenceId, projectId);
|
||
return removed;
|
||
}
|
||
|
||
/// <summary>
|
||
/// "Send first" for a project not open in the editor (the picker's Remove local copy): its working state saved as a
|
||
/// version when it can be, then the sync.
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">A conflict waits (open the project and Sync to settle it), or something is still not at the home.</exception>
|
||
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
|
||
{
|
||
var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
|
||
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
|
||
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(Existing(projectId).ReadBundle().Workspace!.Home));
|
||
}
|
||
|
||
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
|
||
/// <exception cref="WorkspaceException">A newer Chronos wrote the copy: it goes from there, never from here.</exception>
|
||
public Task<WorkspaceRemovalPlan> PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||
{
|
||
var project = Existing(projectId);
|
||
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
|
||
if (entry.Newer) throw Unreadable(entry);
|
||
if (entry.Damaged)
|
||
{
|
||
// What it holds is not known: every version file not marked sent, or not readable, counts as unsent work, kept aside by Discard.
|
||
var (count, size) = Measure(project.Folder);
|
||
var unsent = project.Versions().Count(v => v.StoredAt is null) + project.UnreadableVersions().Count;
|
||
return new WorkspaceRemovalPlan(projectId, entry.Name, count, size, unsent, true, false, false, Damaged: true) { KnownName = entry.KnownName };
|
||
}
|
||
var name = project.ReadBundle().Workspace!.Name;
|
||
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||
var (files, bytes) = Measure(project.Folder);
|
||
// A conflict recorded counts as work not at the home, also once the library no longer has the project (Gone asks none);
|
||
// one a settling replay took past its commit point is over, as the status reads it.
|
||
var conflict = status.Conflict is not null || project.OpenConflict() is not null;
|
||
var (unsentRenders, lastOriginals) = await RemovalMediaAsync(project, cancellationToken).ConfigureAwait(false);
|
||
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, conflict, status.Offline,
|
||
status.State == WorkspaceState.Gone)
|
||
{ UnsentRenders = unsentRenders, LastOriginals = lastOriginals };
|
||
}, cancellationToken);
|
||
|
||
/// <summary>
|
||
/// Removes a project's local copy. Without <paramref name="discard"/> it is refused while anything is not at the home,
|
||
/// and the home's head and the base this copy was made from are read back and checked against their hashes first.
|
||
/// With <paramref name="discard"/> (the user's explicit word) every file of the folder but the media (the versions not
|
||
/// sent, the working state, whatever else it holds) is moved to <c><workspace>/.trash</c> rather than erased. The
|
||
/// media (copies the home can make again) are deleted.
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">
|
||
/// Something is not at the home yet, the home's copy does not check out, or a newer Chronos wrote the copy (it goes from there).
|
||
/// </exception>
|
||
public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default)
|
||
{
|
||
var sequenceId = await Task.Run(async () =>
|
||
{
|
||
// A move takes every project folder as it stands: none goes to the trash meanwhile.
|
||
EnsureNotMoving();
|
||
var project = Existing(projectId);
|
||
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
|
||
if (entry.Newer) throw Unreadable(entry);
|
||
if (entry.Damaged)
|
||
{
|
||
// Its working state cannot be read: only Discard, which keeps every file of it aside, takes it out.
|
||
if (!discard) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged"));
|
||
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Damaged local copy of project {projectId} removed, its files kept in {TrashFolder}");
|
||
return (Guid?)null;
|
||
}
|
||
var workspace = project.ReadBundle().Workspace!;
|
||
if (!discard)
|
||
{
|
||
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
|
||
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
|
||
throw new WorkspaceException(Unsent(workspace.Home));
|
||
await EnsureRendersSentAsync(project, workspace, cancellationToken).ConfigureAwait(false);
|
||
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
|
||
Log.Info("workspace", $"Local copy of project {projectId} ('{workspace.Name}') removed{(discard ? ", its unsent work kept in " + TrashFolder : string.Empty)}");
|
||
return (Guid?)workspace.Home.SequenceId;
|
||
}, cancellationToken);
|
||
if (sequenceId is { } sequence) Forget(sequence, projectId);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Drops the oldest versions this workspace took from the home, keeping Settings › Workspace › Kept versions of them
|
||
/// (the base among them), the versions not sent and the set-aside ones; a version goes only once the home was asked
|
||
/// and holds it with the same content.
|
||
/// </summary>
|
||
public async Task<int> PruneAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(home);
|
||
var project = Existing(projectId);
|
||
var keep = Math.Max(1, _settings.WorkspaceKeptVersions);
|
||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||
{
|
||
var basis = project.ReadBundle().Workspace!.Base;
|
||
var stored = project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).ToList();
|
||
var kept = stored.Where(v => v.Id != basis?.VersionId).Take(keep - (basis is null ? 0 : 1)).Select(v => v.Id).ToHashSet();
|
||
var removed = 0;
|
||
foreach (var version in stored.Where(v => v.Id != basis?.VersionId && !kept.Contains(v.Id)))
|
||
{
|
||
// Read back from where the home keeps it, not from an index of it.
|
||
if (!await home.HoldsAsync(projectId, version, cancellationToken).ConfigureAwait(false)) continue;
|
||
File.Delete(project.VersionPath(version));
|
||
removed++;
|
||
}
|
||
return removed;
|
||
}
|
||
}
|
||
|
||
private async Task PruneQuietlyAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
|
||
{
|
||
try
|
||
{
|
||
var removed = await PruneAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
if (removed > 0) Log.Info("workspace", $"{removed} older version(s) of project {projectId} dropped from the workspace (kept at the home)");
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ProjectException)
|
||
{
|
||
Log.Warning("workspace", $"Older versions of project {projectId} could not be pruned", ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary>
|
||
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
|
||
{
|
||
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
|
||
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
|
||
{
|
||
var server = !workspace.Home.IsArchive;
|
||
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server));
|
||
ProjectVersion head;
|
||
ProjectVersion? basis;
|
||
bool held;
|
||
try
|
||
{
|
||
head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||
basis = workspace.Base is { } b ? await home.GetVersionAsync(projectId, b.VersionId, cancellationToken).ConfigureAwait(false) : head;
|
||
// Read back from where the home keeps them, not from an index of them.
|
||
held = basis is not null && await home.HoldsAsync(projectId, head, cancellationToken).ConfigureAwait(false)
|
||
&& (basis.Id == head.Id || await home.HoldsAsync(projectId, basis, cancellationToken).ConfigureAwait(false));
|
||
}
|
||
catch (ProjectException ex) when (ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
|
||
{
|
||
// Deleted at the home (its trash keeps every version sent): this copy goes only when its user discards it.
|
||
throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"), ex);
|
||
}
|
||
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
|
||
{
|
||
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server), ex);
|
||
}
|
||
if (!held || !ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|
||
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
|
||
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.HomeCheck", server));
|
||
}
|
||
|
||
/// <summary>"Some work is not in the library (on the server) yet": worded for the project's home.</summary>
|
||
private static string Unsent(BundleHome home) => WorkspaceText.ForHome("Errors.Workspace.Unsent", !home.IsArchive);
|
||
|
||
/// <summary>
|
||
/// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the
|
||
/// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved
|
||
/// to <c>.trash/<id>-<time></c> as it is (kept: nothing a user made is erased), the media deleted; the emptied
|
||
/// folder goes once the lease is released, only when nothing else came into it meanwhile. A file that cannot be moved
|
||
/// (held open) puts back what was moved, so the copy stays whole and listed, and the failure is thrown.
|
||
/// </summary>
|
||
/// <exception cref="IOException">A file of the copy could not be moved; the copy is as it was.</exception>
|
||
private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken)
|
||
{
|
||
// A copy of its media still under way would write them again behind the removal.
|
||
Guid copy;
|
||
lock (_gate) _copies.Remove(project.ProjectId, out copy);
|
||
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
|
||
{ State: JobState.Queued or JobState.Running or JobState.Paused })
|
||
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
|
||
// Filled under a staging name Empty… never lists, and named once whole.
|
||
using var trash = WorkspaceTrash.Begin(Store.Root, project.ProjectId, DateTime.UtcNow);
|
||
var aside = trash.Path;
|
||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||
{
|
||
var moved = new List<(string From, string To)>();
|
||
try
|
||
{
|
||
// The working state first: without it the folder is no project any more, whatever happens after.
|
||
Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile));
|
||
foreach (var entry in Directory.EnumerateFileSystemEntries(project.Folder).ToList())
|
||
{
|
||
var name = Path.GetFileName(entry);
|
||
if (IsLease(name) || string.Equals(name, WorkspaceProject.MediaFolder, StringComparison.OrdinalIgnoreCase)) continue;
|
||
Move(entry, Path.Combine(aside, name));
|
||
}
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||
{
|
||
// A file held open (another program's): everything moved goes back, the working state last, so the copy stays
|
||
// whole and listed, and Remove local copy can be asked again.
|
||
Log.Warning("workspace", $"The copy in {project.Folder} could not be moved aside: what was moved goes back", ex);
|
||
for (var i = moved.Count - 1; i >= 0; i--)
|
||
{
|
||
try
|
||
{
|
||
if (Directory.Exists(moved[i].To)) Directory.Move(moved[i].To, moved[i].From);
|
||
else File.Move(moved[i].To, moved[i].From);
|
||
}
|
||
catch (Exception back) when (back is IOException or UnauthorizedAccessException)
|
||
{
|
||
Log.Error("workspace", $"{moved[i].To} could not go back to {moved[i].From}: it is kept there", back);
|
||
}
|
||
}
|
||
try
|
||
{
|
||
if (!Directory.EnumerateFileSystemEntries(aside).Any()) Directory.Delete(aside);
|
||
}
|
||
catch (Exception left) when (left is IOException or UnauthorizedAccessException)
|
||
{
|
||
Log.Debug("workspace", $"{aside} stays: {left.Message}");
|
||
}
|
||
throw;
|
||
}
|
||
// Every original is hashed and goes aside unless the home holds the same bytes; only what the home can make again
|
||
// is deleted. One that can be neither deleted nor moved stays where it is, and the media folder with it.
|
||
if (await ClearOriginalsAsync(project, aside, cancellationToken).ConfigureAwait(false) == 0)
|
||
{
|
||
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
|
||
}
|
||
else
|
||
{
|
||
foreach (var entry in Directory.EnumerateFileSystemEntries(project.MediaDirectory).ToList())
|
||
{
|
||
if (string.Equals(Path.GetFileName(entry), WorkspaceProject.OriginalsFolder, StringComparison.OrdinalIgnoreCase)) continue;
|
||
if (Directory.Exists(entry)) Directory.Delete(entry, recursive: true);
|
||
else File.Delete(entry);
|
||
}
|
||
}
|
||
|
||
void Move(string from, string to)
|
||
{
|
||
if (Directory.Exists(from)) Directory.Move(from, to);
|
||
else File.Move(from, to);
|
||
moved.Add((from, to));
|
||
}
|
||
}
|
||
try
|
||
{
|
||
// Only the lease's leftovers may be left: anything else is kept where it is.
|
||
if (Directory.EnumerateFileSystemEntries(project.Folder).All(e => IsLease(Path.GetFileName(e)))) Directory.Delete(project.Folder, recursive: true);
|
||
else Log.Info("workspace", $"The folder {project.Folder} stays: files came into it while its copy was removed");
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||
{
|
||
Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}");
|
||
}
|
||
|
||
static bool IsLease(string name) => name.StartsWith(".lock.lease", StringComparison.OrdinalIgnoreCase);
|
||
}
|
||
|
||
/// <summary>A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.</summary>
|
||
/// <exception cref="WorkspaceException">Why not.</exception>
|
||
private static void EnsureWritable(WorkspaceStatus status)
|
||
{
|
||
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
|
||
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
|
||
}
|
||
|
||
/// <summary>
|
||
/// The workspace folder lies inside a library this index knows (a portable copy's <c>data</c> folder under a library
|
||
/// at a drive's root): editing happens outside every library, so nothing is checked out or copied there.
|
||
/// </summary>
|
||
private Task<bool> InsideALibraryAsync(CancellationToken cancellationToken) => InsideALibraryAsync(Root, cancellationToken);
|
||
|
||
private async Task<bool> InsideALibraryAsync(string folder, CancellationToken cancellationToken)
|
||
{
|
||
if (_db() is not { } db) return false;
|
||
var root = Plain(Path.GetFullPath(folder));
|
||
foreach (var archive in await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false))
|
||
{
|
||
if (DataLocation.IsUnder(root, Plain(Path.GetFullPath(archive.RootPath)))) return true;
|
||
}
|
||
return false;
|
||
|
||
// Without the long-path prefix, which only one of the two may carry.
|
||
static string Plain(string path) =>
|
||
path.StartsWith(@"\\?\UNC\", StringComparison.Ordinal) ? @"\\" + path[8..]
|
||
: path.StartsWith(@"\\?\", StringComparison.Ordinal) ? path[4..]
|
||
: path;
|
||
}
|
||
|
||
private void Forget(Guid sequenceId, Guid projectId)
|
||
{
|
||
var changed = _settings.WorkspaceOpened.Remove(projectId);
|
||
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId)
|
||
{
|
||
_settings.WorkspaceRecent.Remove(sequenceId);
|
||
changed = true;
|
||
}
|
||
if (changed) _savePreferences();
|
||
}
|
||
|
||
/// <summary>
|
||
/// The copy of a project's media from its home, unless one is waiting or running: a sequence of this PC's archive copied
|
||
/// from there, a server's downloaded from it (<paramref name="title"/> labels that job: the index has no row for it).
|
||
/// </summary>
|
||
private async Task<Job> QueueCopyCoreAsync(BundleHome home, Guid projectId, string media, string title, CancellationToken cancellationToken)
|
||
{
|
||
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||
Guid known;
|
||
lock (_gate) _copies.TryGetValue(projectId, out known);
|
||
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
|
||
ArchiveJobRequest request;
|
||
if (home.IsArchive)
|
||
{
|
||
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
|
||
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
|
||
request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media);
|
||
}
|
||
else
|
||
{
|
||
request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root,
|
||
projectId, media);
|
||
}
|
||
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||
lock (_gate) _copies[projectId] = job.Id;
|
||
return job;
|
||
}
|
||
|
||
/// <exception cref="HomeUnavailableException">The project's home cannot be reached now.</exception>
|
||
private IProjectHome HomeOfProject(Guid projectId)
|
||
{
|
||
var home = Existing(projectId).ReadBundle().Workspace!.Home;
|
||
return HomeOf(home) ?? throw new HomeUnavailableException(home.IsArchive
|
||
? "The project's home cannot be reached from this PC."
|
||
: "This PC is not signed in to the server of the project, or it keeps no projects.");
|
||
}
|
||
|
||
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||
|
||
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
|
||
{
|
||
var workspace = bundle.Workspace!;
|
||
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
|
||
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, WorkspaceCleaner.HoldsMedia(project), bundle.Saved);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The project's entry; when its working state cannot be read (logged), one written by a newer Chronos
|
||
/// (<see cref="WorkspaceEntry.Newer"/>) or a damaged one (<see cref="WorkspaceEntry.Damaged"/>), named as it is still
|
||
/// known (what of its project file reads, else the library's index), else by its folder.
|
||
/// </summary>
|
||
private async Task<WorkspaceEntry> EntryOrUnreadableAsync(WorkspaceProject project, CancellationToken cancellationToken)
|
||
{
|
||
try
|
||
{
|
||
return Entry(project, project.ReadBundle());
|
||
}
|
||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||
{
|
||
var peek = BundlePeek.Of(project);
|
||
if (peek.Newer) Log.Info("workspace", $"The project in {project.Folder} was saved by a newer Chronos (project file format {peek.Format}): it is left as it is");
|
||
else Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
|
||
var (name, isMain, title) = (peek.Name, peek.IsMain, peek.Title);
|
||
if ((name is null || title is null) && _db() is { } db)
|
||
{
|
||
try
|
||
{
|
||
if (await db.Projects.GetAsync(project.ProjectId, cancellationToken).ConfigureAwait(false) is { } known)
|
||
{
|
||
if (name is null) (name, isMain) = (known.Name, known.IsMain);
|
||
title ??= (await db.Sequences.GetAsync(known.SequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle;
|
||
}
|
||
}
|
||
catch (Exception dbx) when (dbx is not OperationCanceledException and not OutOfMemoryException)
|
||
{
|
||
// The index closing (the program ending), or any other failure: the copy is listed by what is known.
|
||
Log.Info("workspace", $"The index could not name the project in {project.Folder}: {dbx.Message}");
|
||
}
|
||
}
|
||
var saved = File.Exists(project.BundlePath) ? new DateTimeOffset(File.GetLastWriteTimeUtc(project.BundlePath), TimeSpan.Zero) : DateTimeOffset.MinValue;
|
||
var shown = name is null ? null : WorkspaceText.ProjectName(name, isMain);
|
||
return new WorkspaceEntry(project.ProjectId, Guid.Empty, name ?? Path.GetFileName(project.Folder), isMain && name is not null,
|
||
new BundleHome(BundleHome.ArchiveKind, Guid.Empty), title ?? project.Folder, false, peek.Saved ?? saved, Damaged: !peek.Newer)
|
||
{
|
||
Newer = peek.Newer,
|
||
KnownName = shown ?? title,
|
||
};
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// What a working state this Chronos cannot read still says, read as loosely as its JSON allows: whether a newer
|
||
/// Chronos wrote it (a format newer than <see cref="ProjectBundle.CurrentFormatVersion"/>), and the project's name,
|
||
/// its sequence's title and when it was saved, each when it is there.
|
||
/// </summary>
|
||
private sealed record BundlePeek(bool Newer, int Format, string? Name, bool IsMain, string? Title, DateTimeOffset? Saved)
|
||
{
|
||
private static readonly BundlePeek Nothing = new(false, 0, null, false, null, null);
|
||
|
||
public static BundlePeek Of(WorkspaceProject project)
|
||
{
|
||
try
|
||
{
|
||
var info = new FileInfo(project.BundlePath);
|
||
if (!info.Exists || info.Length > ProjectBundle.MaxBytes) return Nothing;
|
||
using var document = JsonDocument.Parse(File.ReadAllBytes(info.FullName), new JsonDocumentOptions { MaxDepth = 64 });
|
||
var root = document.RootElement;
|
||
if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != ProjectBundle.FormatName) return Nothing;
|
||
var format = root.TryGetProperty("formatVersion", out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n) ? n : 0;
|
||
string? name = null;
|
||
var isMain = false;
|
||
if (root.TryGetProperty("workspace", out var workspace) && workspace.ValueKind == JsonValueKind.Object
|
||
&& Text(workspace, "projectId") is { } id && Guid.TryParse(id, out var projectId) && projectId == project.ProjectId)
|
||
{
|
||
name = Text(workspace, "name") is { Length: > 0 } named ? named : null;
|
||
isMain = workspace.TryGetProperty("isMain", out var main) && main.ValueKind == JsonValueKind.True;
|
||
}
|
||
var title = root.TryGetProperty("sequence", out var sequence) && sequence.ValueKind == JsonValueKind.Object
|
||
? Text(sequence, "title") is { Length: > 0 } t ? t : Text(sequence, "folder") is { Length: > 0 } f ? f : null
|
||
: null;
|
||
DateTimeOffset? saved = root.TryGetProperty("saved", out var s) && s.ValueKind == JsonValueKind.String && s.TryGetDateTimeOffset(out var when)
|
||
? when
|
||
: null;
|
||
return new BundlePeek(format > ProjectBundle.CurrentFormatVersion, format, name, isMain, title, saved);
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||
{
|
||
return Nothing;
|
||
}
|
||
|
||
static string? Text(JsonElement element, string property) =>
|
||
element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||
}
|
||
}
|
||
|
||
/// <summary>The projects a workspace folder holds (folders named by a project id with a working state), without making or opening it.</summary>
|
||
private static int CountProjects(string folder)
|
||
{
|
||
if (!Directory.Exists(folder)) return 0;
|
||
try
|
||
{
|
||
return Directory.EnumerateDirectories(folder).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
|
||
&& File.Exists(Path.Combine(d, WorkspaceProject.BundleFile)));
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||
{
|
||
Log.Info("workspace", $"The projects of {folder} could not be counted: {ex.Message}");
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/// <summary>Files and bytes under <paramref name="folder"/>, the lease left out.</summary>
|
||
private static (int Files, long Bytes) Measure(string folder)
|
||
{
|
||
var (files, bytes) = (0, 0L);
|
||
if (!Directory.Exists(folder)) return (files, bytes);
|
||
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
|
||
{
|
||
if (file.Name.EndsWith(".lease", StringComparison.OrdinalIgnoreCase)) continue;
|
||
files++;
|
||
bytes += file.Length;
|
||
}
|
||
return (files, bytes);
|
||
}
|
||
|
||
private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
|
||
}
|