using System.Globalization;
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
namespace Febe.Web.Api;
///
/// The library (spec §4.6): days and windows of the mosaic with keyset paging (fluid with 200,000 entries), thumbnails
/// generated once and served from the Data folder, the files themselves, the viewer data, deletion, CSV export.
///
public static class LibraryApi
{
/// Largest window a page can ask for.
public const int MaxWindow = 600;
private static readonly FileExtensionContentTypeProvider ContentTypes = new();
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/library/days", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var zone = clock.LocalZone;
var now = clock.Now;
var filter = ApiMapping.Filter(context.Request.Query, zone);
var mode = ApiMapping.Mode(context.Request.Query["mode"]);
var totals = await storage.Entries.GetLibraryTotalsAsync(filter, ct).ConfigureAwait(false);
var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, mode, ct).ConfigureAwait(false);
// The files of «Tutte le foto» are the sum of their days: one pass over the media table per request.
int? files = mode == MosaicMode.Files ? days.Sum(d => d.Count) : null;
var list = days.Select(d =>
{
var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone);
return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode));
}).ToList();
var hasDestinations = await HasDestinationsAsync(storage, ct).ConfigureAwait(false);
return ApiHttp.Json(
new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files, hasDestinations),
FebeJsonContext.Default.LibraryDaysDto);
});
endpoints.MapGet("/api/library", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var query = context.Request.Query;
var zone = clock.LocalZone;
var limit = int.TryParse(query["limit"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var l) ? Math.Clamp(l, 1, MaxWindow) : 200;
var direction = string.Equals(query["direction"], "newer", StringComparison.OrdinalIgnoreCase) ? LibraryDirection.Newer : LibraryDirection.Older;
var mode = ApiMapping.Mode(query["mode"]);
var page = await storage.Entries.QueryLibraryAsync(
new LibraryQuery
{
Filter = ApiMapping.Filter(query, zone),
Cursor = ApiMapping.ParseCursor(query["cursor"]),
Direction = direction,
Mode = mode,
Limit = limit,
},
ct).ConfigureAwait(false);
return ApiHttp.Json(
new LibraryPageDto(
await TilesAsync(storage, page.Tiles, zone, ct).ConfigureAwait(false),
page.Older is { } older ? ApiMapping.Cursor(older, mode) : null,
page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null),
FebeJsonContext.Default.LibraryPageDto);
});
// Tiles of given entries in the given order (the items of a highlight collection).
endpoints.MapGet("/api/library/tiles", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var ids = ParseIds(context.Request.Query["ids"].ToString());
var tiles = await storage.Entries.GetTilesAsync(ids, ct).ConfigureAwait(false);
return ApiHttp.Json(new LibraryPageDto(await TilesAsync(storage, tiles, clock.LocalZone, ct).ConfigureAwait(false), null, null), FebeJsonContext.Default.LibraryPageDto);
});
endpoints.MapGet("/api/thumbnails/{key}", (string key, HttpContext context, FebeLibrary library) =>
{
string path;
if (string.Equals(key, "video", StringComparison.Ordinal))
{
path = library.Thumbnails.NeutralVideoTile();
}
else
{
if (key.Length != 64 || !key.All(Uri.IsHexDigit))
{
throw new BadRequestException("Chiave di miniatura non valida.");
}
path = library.Thumbnails.PathFor(key);
if (!File.Exists(path))
{
throw new NotFoundException("Miniatura non trovata.");
}
}
// Content-addressed: the same key always has the same picture.
context.Response.Headers.CacheControl = "private, max-age=31536000, immutable";
return Results.File(path, "image/jpeg");
});
endpoints.MapGet("/api/media/{id:long}/file", async (long id, HttpContext context, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) =>
{
var (account, media) = await MediaAsync(storage, id, ct).ConfigureAwait(false);
var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco.");
if (!ContentTypes.TryGetContentType(path, out var type))
{
type = "application/octet-stream";
}
var download = context.Request.Query["download"].ToString() is "1" or "true";
context.Response.Headers.CacheControl = "private, no-cache";
return download
? Results.File(path, type, Path.GetFileName(path), enableRangeProcessing: true)
: Results.File(path, type, enableRangeProcessing: true);
});
endpoints.MapPost("/api/media/show-in-folder", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, INativeShell shell, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.MediaActionRequest).ConfigureAwait(false);
var (account, media) = await MediaAsync(storage, body.MediaId, ct).ConfigureAwait(false);
var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco: forse è stato spostato o cancellato fuori da Febe.");
if (!await shell.ShowInFolderAsync(path, ct).ConfigureAwait(false))
{
throw new BadRequestException("Qui non si può aprire la cartella: usa «Scarica».");
}
return ApiHttp.Message("Cartella aperta.");
});
endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EntryDto));
endpoints.MapPost("/api/entries/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, IClock clock, CancellationToken ct) =>
{
var entry = await storage.Entries.GetAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
var highlight = entry.Kind == EntryKind.Highlight ? (await storage.Highlights.ListForEntryAsync(id, ct).ConfigureAwait(false)).FirstOrDefault()?.InstagramId : null;
var address = new Uri(InstagramLinks.For(account, entry, clock.Now, highlight));
if (!InstagramLinks.IsSiteAddress(address) || !await shell.OpenUrlAsync(address, ct).ConfigureAwait(false))
{
throw new BadRequestException("Qui il collegamento si apre direttamente dalla pagina.");
}
return ApiHttp.Message("Aperto nel tuo browser.");
});
endpoints.MapPost("/api/entries/delete", async (HttpContext context, IFebeStorage storage, FebeLibrary library, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.EntryIdsRequest).ConfigureAwait(false);
if (body.Ids.Count == 0)
{
throw new BadRequestException("Nessun elemento scelto.");
}
var mode = string.Equals(body.Mode, "allowReturn", StringComparison.OrdinalIgnoreCase) ? DeletionMode.AllowReturn : DeletionMode.Remember;
var results = await library.Deletion.DeleteManyAsync(body.Ids, mode, ct).ConfigureAwait(false);
var deleted = results.Count(r => r.Found);
var removed = results.Sum(r => r.DeletedFiles.Count);
var problems = results.SelectMany(r => r.FailedFiles).ToList();
changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
var message = (deleted == 1 ? "Elemento eliminato dalla libreria" : $"{Core.Engine.ItalianText.Number(deleted)} elementi eliminati dalla libreria")
+ (mode == DeletionMode.Remember ? ": Febe non li scarica di nuovo." : ": se ricompaiono, Febe li scarica di nuovo.")
+ (problems.Count > 0 ? $" {Core.Engine.ItalianText.Count(problems.Count, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: chiudi i programmi che li usano e riprova." : string.Empty);
return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message), FebeJsonContext.Default.DeleteResultDto);
});
endpoints.MapPost("/api/entries/export", async (HttpContext context, IFebeStorage storage, IClock clock) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportRequest).ConfigureAwait(false);
var zone = clock.LocalZone;
LibraryFilter? filter = null;
if (body.Ids is not { Count: > 0 })
{
filter = ApiMapping.Filter(new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(body.Query ?? string.Empty)), zone);
}
var day = LocalCalendar.Today(clock.Now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
context.Response.ContentType = "text/csv; charset=utf-8";
context.Response.Headers.ContentDisposition = $"attachment; filename=\"febe-elementi-{day}.csv\"";
var rows = filter is null
? RowsAsync(storage, body.Ids!, clock.Now, context.RequestAborted)
: RowsAsync(storage, IdsAsync(storage, filter, context.RequestAborted), clock.Now, context.RequestAborted);
await CsvExport.WriteAsync(context.Response.Body, rows, zone, context.RequestAborted).ConfigureAwait(false);
});
}
public static TileDto Tile(LibraryTile tile, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(tile);
var local = LocalCalendar.ToLocal(tile.PublishedAt, zone);
return new TileDto(
tile.EntryId,
tile.AccountId,
tile.Username,
ApiMapping.Kind(tile.Kind),
tile.PublishedAt.ToUnixTimeMilliseconds(),
ApiMapping.Day(DateOnly.FromDateTime(local)),
local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture),
ApiMapping.Provenance(tile.Provenance),
ApiMapping.State(tile.State),
tile.MediaCount,
tile.CoverMediaId is { } mediaId
? new CoverDto(
mediaId,
ApiMapping.Media(tile.CoverKind ?? MediaKind.Photo),
tile.CoverWidth,
tile.CoverHeight,
tile.CoverDuration?.TotalSeconds,
tile.CoverHasThumbnail && tile.CoverSha256 is not null ? tile.CoverSha256 : tile.CoverKind == MediaKind.Video ? "video" : null)
: null,
tile.FilePosition);
}
public static async Task EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(files);
ArgumentNullException.ThrowIfNull(library);
ArgumentNullException.ThrowIfNull(clock);
var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato: forse è stato eliminato.");
var entry = stored.Entry;
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
var highlights = await storage.Highlights.ListForEntryAsync(id, ct).ConfigureAwait(false);
var zone = clock.LocalZone;
var now = clock.Now;
var local = LocalCalendar.ToLocal(entry.PublishedAt, zone);
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false);
var media = new List(stored.Media.Count);
foreach (var m in stored.Media)
{
var relative = m.RelativePath;
string? folder = null;
if (relative is not null)
{
var directory = Path.GetDirectoryName(LibraryLayout.ToPlatform(relative));
folder = string.IsNullOrEmpty(directory) ? accountFolder : Path.Combine(accountFolder, directory);
}
var path = files.Resolve(account, m);
var damaged = await IsDamagedAsync(m, path, ct).ConfigureAwait(false);
media.Add(new MediaDto(
m.Id,
m.Position,
ApiMapping.Media(m.Kind),
m.Width,
m.Height,
m.Duration?.TotalSeconds,
m.Bytes,
relative is null ? null : Path.GetFileName(LibraryLayout.ToPlatform(relative)),
folder,
m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
path is not null,
ApiMapping.State(m.State),
damaged,
copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false)));
}
return new EntryDto(
entry.Id,
ApiMapping.Kind(entry.Kind),
ApiMapping.Brief(account, avatar),
entry.PublishedAt.ToUnixTimeMilliseconds(),
ApiMapping.Day(DateOnly.FromDateTime(local)),
ApiMapping.Clock(entry.PublishedAt, zone),
entry.Code,
entry.InstagramId,
entry.Caption,
entry.AuthorUsername,
ApiMapping.Provenance(entry.Provenance),
ApiMapping.State(entry.State),
ApiMapping.Local(entry.DiscoveredAt, now, zone),
entry.DownloadedAt is { } d ? ApiMapping.Local(d, now, zone) : null,
highlights.Select(h => h.Title).ToList(),
entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, entry, now, highlights.FirstOrDefault()?.InstagramId),
media,
copies is { Effective: not null, Enabled: true });
}
///
/// The tiles of a page with the mark of the copies to external folders (spec §4.6, tappa E2): an entry tile
/// «Copiato» or «Copiato in parte 1/3», a file tile of «Tutte le foto» «Copiato». Only due files count (decision
/// D3), and without a destination in use nothing more is asked to the database.
///
public static async Task> TilesAsync(IFebeStorage storage, IReadOnlyList tiles, TimeZoneInfo zone, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(tiles);
var list = tiles.Select(t => Tile(t, zone)).ToList();
if (list.Count == 0 || !await HasDestinationsAsync(storage, ct).ConfigureAwait(false))
{
return list;
}
var fileIds = tiles.Where(t => t.FilePosition is not null && t.CoverMediaId is not null).Select(t => t.CoverMediaId!.Value).Distinct().ToList();
var entryIds = tiles.Where(t => t.FilePosition is null).Select(t => t.EntryId).Distinct().ToList();
var fileMarks = fileIds.Count == 0 ? null : await storage.Exports.GetFileMarksAsync(fileIds, ct).ConfigureAwait(false);
var entryCopies = entryIds.Count == 0 ? null : await storage.Exports.GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false);
for (var i = 0; i < list.Count; i++)
{
var tile = tiles[i];
if (tile.FilePosition is not null)
{
if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied)
{
list[i] = list[i] with { Copies = "copied" };
}
}
else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies))
{
list[i] = copies.Mark switch
{
ExportMark.Copied => list[i] with { Copies = "copied" },
ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due },
_ => list[i],
};
}
}
return list;
}
/// Whether any destination of the copies is in use (the marks and the «Copie» filter make sense).
public static async Task HasDestinationsAsync(IFebeStorage storage, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
return (await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false)).Count > 0;
}
///
/// What the viewer needs to list the copies of the files of one entry (spec §4.6, §4.10): every destination, retired
/// ones too (an old copy keeps its name), the effective destination of the account and its switch, and «Lo stesso
/// post in due account». Null when no destination was ever added.
///
private sealed record EntryCopiesContext(
Account Account,
IReadOnlyDictionary Destinations,
ExportDestination? Effective,
bool Enabled,
SamePostCopies SamePost,
IReadOnlyDictionary Usernames)
{
/// Copies shown for one file, newest first.
public const int MaxShown = 6;
public static async Task LoadAsync(IFebeStorage storage, Account account, CancellationToken ct)
{
var exports = storage.Exports;
var destinations = await exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false);
if (destinations.Count == 0)
{
return null;
}
var effective = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false)
?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false));
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var usernames = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
return new EntryCopiesContext(account, destinations.ToDictionary(d => d.Id), effective, enabled, settings.SamePost, usernames);
}
public async Task> CopiesAsync(IFebeStorage storage, Media media, DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct)
{
if (media.Sha256 is not { Length: > 0 } sha)
{
return [];
}
var present = EntryStateRules.IsPresent(media.State);
var rows = await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false);
var shown = new List();
foreach (var copy in rows.OrderByDescending(c => c.StateChangedAt ?? c.CopiedAt).ThenByDescending(c => c.Id))
{
if (!Destinations.TryGetValue(copy.DestinationId, out var destination))
{
continue;
}
// The copies made for this account; with «Una copia sola», also the ones made for another account still
// in Febe in a folder still in use (that is why this file is «Già copiato»; a copy whose account was
// removed does not count, as in the plan).
var own = copy.AccountId == Account.Id;
if (!own && !(SamePost == SamePostCopies.OneOnly && copy.AccountId is not null && copy.State == ExportCopyState.Copied && !destination.IsRetired))
{
continue;
}
var canCopyAgain = own
&& copy.State is ExportCopyState.Removed or ExportCopyState.Superseded
&& present
&& !destination.IsRetired
&& Enabled
&& Effective?.Id == destination.Id
&& !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant);
shown.Add(new MediaCopyDto(
copy.Id,
ExportDestinations.Label(destination),
destination.IsRetired,
ExportApi.CopyState(copy.State),
copy.Variant switch
{
ExportVariant.Whole => "whole",
ExportVariant.Converted => "converted",
_ => "frame",
},
copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(),
copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null,
ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone),
own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null,
canCopyAgain));
if (shown.Count == MaxShown)
{
break;
}
}
return shown;
}
}
///
/// «File danneggiato o incompleto» (spec §4.6, §8.4): a photo on disk with no thumbnail whose bytes are damaged or
/// truncated. A photo with a thumbnail was decoded when it was stored, so only those without one are looked at,
/// one file each time the viewer opens it, with asynchronous reads and the answer kept for the same file; a format
/// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole.
/// The file is only read, never touched (rule 12).
///
private static async Task IsDamagedAsync(Media media, string? path, CancellationToken ct) =>
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false);
private static async Task<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct)
{
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
return (account, media);
}
private static List ParseIds(string text)
{
var ids = new List();
foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!long.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
{
throw new BadRequestException("Elenco di elementi non valido.");
}
ids.Add(id);
}
if (ids.Count > 5000)
{
throw new BadRequestException("Troppi elementi in una richiesta.");
}
return ids;
}
private static async IAsyncEnumerable IdsAsync(IFebeStorage storage, LibraryFilter filter, [EnumeratorCancellation] CancellationToken ct)
{
LibraryCursor? cursor = null;
while (true)
{
var page = await storage.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Cursor = cursor, Limit = 1000 }, ct).ConfigureAwait(false);
foreach (var tile in page.Tiles)
{
yield return tile.EntryId;
}
if (page.Older is null)
{
yield break;
}
cursor = page.Older;
}
}
private static async IAsyncEnumerable Enumerate(IReadOnlyList ids)
{
foreach (var id in ids)
{
yield return id;
}
await Task.CompletedTask.ConfigureAwait(false);
}
private static IAsyncEnumerable RowsAsync(IFebeStorage storage, IReadOnlyList ids, DateTimeOffset now, CancellationToken ct) =>
RowsAsync(storage, Enumerate(ids), now, ct);
private static async IAsyncEnumerable RowsAsync(IFebeStorage storage, IAsyncEnumerable ids, DateTimeOffset now, [EnumeratorCancellation] CancellationToken ct)
{
var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
await foreach (var id in ids.WithCancellation(ct).ConfigureAwait(false))
{
var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false);
if (stored is null || !accounts.TryGetValue(stored.Entry.AccountId, out var account))
{
continue;
}
var highlights = await storage.Highlights.ListForEntryAsync(id, ct).ConfigureAwait(false);
yield return new CsvEntry(
account,
stored.Entry,
stored.Media,
highlights.Select(h => h.Title).ToList(),
stored.Entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, stored.Entry, now, highlights.FirstOrDefault()?.InstagramId));
}
}
}