using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Web.Library;
///
/// The library as the web layer uses it: Data folder, library folder, thumbnails, journal and deletion. The library
/// folder can change at run time (Impostazioni, Generali): swaps the layout.
///
public sealed class FebeLibrary
{
private readonly IFebeStorage _storage;
private readonly IClock _clock;
private readonly PerceptualHashIndex? _index;
private volatile LibraryLayout _layout;
public FebeLibrary(IFebeStorage storage, DataFolderLayout data, LibraryLayout layout, IClock clock, PerceptualHashIndex? index = null)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
Data = data ?? throw new ArgumentNullException(nameof(data));
_layout = layout ?? throw new ArgumentNullException(nameof(layout));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_index = index;
Thumbnails = new ThumbnailStore(data.Thumbnails);
Journal = new AccountJournal(clock);
}
public DataFolderLayout Data { get; }
public LibraryLayout Layout => _layout;
public ThumbnailStore Thumbnails { get; }
public AccountJournal Journal { get; }
/// «Elimina dalla libreria», on Alberto's explicit choice only (rule 12).
public LibraryDeletion Deletion => new(_storage, _layout, Journal, _clock, Thumbnails, _index);
/// The library folder changed: new files go there; existing accounts keep their stored folders.
public void UseLibraryRoot(string root) => _layout = new LibraryLayout(root, _layout.MaxPathLength);
}
/// Where the file of a media record is on disk. The demo maps its shared sample files; the real one uses the layout.
public interface IMediaFileResolver
{
/// Full path of an existing file, or null when the file is not on disk.
string? Resolve(Account account, Media media);
}
/// Files under the account folders of the library (spec §4.7).
public sealed class LibraryFileResolver(FebeLibrary library) : IMediaFileResolver
{
public string? Resolve(Account account, Media media)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(media);
if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State))
{
return null;
}
try
{
var path = library.Layout.FullPath(account, media.RelativePath);
return File.Exists(path) ? path : null;
}
catch (ArgumentException)
{
return null;
}
}
}
/// Something changed in the library: the open pages reload what they show.
/// When.
/// The account concerned, when there is only one.
/// Short machine reason: "stored", "deleted", "account", "import".
public sealed record LibraryChange(DateTimeOffset At, long? AccountId, string Reason);
///
/// Library notifications for the server-sent events (/api/eventi, event libreria). Publishers: the web
/// layer itself (deletions, account changes), the download queue () and the import (M7).
/// Slow subscribers lose the oldest notifications.
///
public sealed class LibraryChanges
{
private readonly Lock _gate = new();
private readonly List> _subscribers = [];
public void Publish(LibraryChange change)
{
Channel[] subscribers;
lock (_gate)
{
subscribers = [.. _subscribers];
}
foreach (var subscriber in subscribers)
{
subscriber.Writer.TryWrite(change);
}
}
/// Publishes a change for every file the download queue stores.
public IDisposable Attach(DownloadQueue queue, IClock clock)
{
ArgumentNullException.ThrowIfNull(queue);
ArgumentNullException.ThrowIfNull(clock);
void Handler(object? sender, DownloadProgress progress)
{
if (progress.Step == DownloadStep.Stored)
{
Publish(new LibraryChange(clock.Now, progress.AccountId, "stored"));
}
}
queue.Progress += Handler;
return new Detach(() => queue.Progress -= Handler);
}
public async IAsyncEnumerable SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
var channel = Channel.CreateBounded(new BoundedChannelOptions(256) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
lock (_gate)
{
_subscribers.Add(channel);
}
try
{
while (await channel.Reader.WaitToReadAsync(ct).ConfigureAwait(false))
{
while (channel.Reader.TryRead(out var change))
{
yield return change;
}
}
}
finally
{
lock (_gate)
{
_subscribers.Remove(channel);
}
}
}
private sealed class Detach(Action action) : IDisposable
{
public void Dispose() => action();
}
}