diff --git a/src/Febe.Core/Storage/LibraryQueries.cs b/src/Febe.Core/Storage/LibraryQueries.cs index f78171e..31737aa 100644 --- a/src/Febe.Core/Storage/LibraryQueries.cs +++ b/src/Febe.Core/Storage/LibraryQueries.cs @@ -28,6 +28,14 @@ public enum LibraryKindFilter /// Posts of any media (the «Post» tab of an account). Posts, + + /// + /// «Video fermi» (tappa E4, answer 40 of Alberto, 29 November 2026; in the library only, not in the account tabs): + /// posts, stories, highlights and tagged posts with at least one video in the library whose latest analysis + /// (the highest algorithm in video_analysis) says «Fermo». A video never analysed is not in it: analysis is on + /// request only. In «Tutte le foto» only those videos. + /// + StillVideos, } /// diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index 76e92f9..51c3972 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -527,6 +527,10 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore { LibraryKindFilter.Photos => " AND m.kind = 'Photo'", LibraryKindFilter.Videos => " AND m.kind = 'Video'", + // Over every file (bulk) SQLite goes from the still SHA-256 to their files on ix_media_sha256; for the files + // of a few entries the unary + keeps it on the key of the entry: on the SHA-256 index each entry would walk + // every still video (in a correlated count, 20 ms per entry with 10,000 of them). + LibraryKindFilter.StillVideos => $" AND m.kind = 'Video' AND {(bulk ? string.Empty : "+")}m.sha256 IN ({StillShas})", _ => string.Empty, } + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty); @@ -562,8 +566,38 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore /// the files already decides (a post without videos adds 0) and the EXISTS per post of the grouped filter would cost /// a second over 200,000 entries. /// - private static LibraryFilter EntriesOfFiles(LibraryFilter filter) => - filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter; + private static LibraryFilter EntriesOfFiles(LibraryFilter filter) => filter.Kind switch + { + LibraryKindFilter.Photos or LibraryKindFilter.Videos => filter with { Kind = LibraryKindFilter.Posts }, + // «Video fermi» is of every kind of entry of «Tutto»: an entry without still videos adds 0 the same way. + LibraryKindFilter.StillVideos => filter with { Kind = LibraryKindFilter.All }, + _ => filter, + }; + + /// + /// «Video fermi»: the SHA-256 of the videos whose latest analysis (the highest algorithm, D4 of tappa E4) says + /// «Fermo», read once on ix_video_analysis_still; an «In movimento» of a newer algorithm takes the video out. The + /// primary key (sha256, algorithm) answers the NOT EXISTS of each. + /// + private const string StillShas = + "SELECT vs.sha256 FROM video_analysis vs WHERE vs.outcome = 'Still' " + + "AND NOT EXISTS (SELECT 1 FROM video_analysis vn WHERE vn.sha256 = vs.sha256 AND vn.algorithm > vs.algorithm)"; + + /// + /// «Video fermi» on entry e: the entries with a still video in the library, one list read once per statement, + /// then each entry of the publication index tested by key against it. Analysis is on request, so the still videos + /// are few and the list is short; an EXISTS per entry would walk the whole index (each entry a lookup of its files and + /// their table rows, over a second) whenever the filter matches few entries. + /// The list goes from the still outcomes (ix_video_analysis_still) to their files (ix_media_sha256_entry) and checks + /// that the file is a video in the library on ix_media_entry_files, all on covering indexes: 44 ms for 10,000 still + /// videos, 55 ms reading the table row of each file. CROSS JOIN keeps that order (started from the files, SQLite + /// scans all of them on ix_media_state, 90 ms); the unary + on the key keeps the check on the covering index. + /// + private const string StillVideoEntries = + "SELECT ms.entry_id FROM video_analysis vs CROSS JOIN media ms ON ms.sha256 = vs.sha256 WHERE vs.outcome = 'Still' " + + "AND NOT EXISTS (SELECT 1 FROM video_analysis vn WHERE vn.sha256 = vs.sha256 AND vn.algorithm > vs.algorithm) " + + "AND EXISTS (SELECT 1 FROM media mf WHERE mf.entry_id = ms.entry_id AND mf.state IN ('Downloaded', 'Imported') " + + "AND mf.kind = 'Video' AND +mf.id = ms.id)"; /// A correlated count of the files of «Tutte le foto» of the entry e. private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) => @@ -884,6 +918,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))", LibraryKindFilter.Tagged => "e.kind = 'Tagged'", LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'", + // The unary + on the key, as for the list of «Foto» and «Video»: the entries stay in the order of the + // publication index (a window stops after its first rows), each tested against the list on its key. + LibraryKindFilter.StillVideos => $"+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged') AND +e.id IN ({StillVideoEntries})", _ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null), }); diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs index 854375b..25df9d8 100644 --- a/src/Febe.Web/Api/ApiMapping.cs +++ b/src/Febe.Web/Api/ApiMapping.cs @@ -172,7 +172,7 @@ public static class ApiMapping /// /// The library filter from the query string: kind (all, photos, videos, stories, highlights, tagged, posts, - /// profile), accounts (comma-separated keys), from/to (local days, inclusive), + /// profile, stillvideos), accounts (comma-separated keys), from/to (local days, inclusive), /// provenance (downloaded, imported), q (account name or caption). /// public static LibraryFilter Filter(IQueryCollection query, TimeZoneInfo zone) @@ -189,6 +189,7 @@ public static class ApiMapping "tagged" => LibraryKindFilter.Tagged, "posts" => LibraryKindFilter.Posts, "profile" => LibraryKindFilter.ProfilePictures, + "stillvideos" => LibraryKindFilter.StillVideos, _ => throw new BadRequestException("Tipo di contenuto sconosciuto."), }; diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 02a1c90..d645a92 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -114,7 +114,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser | | `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s), commento ogni 25 s | | `GET /api/library/days?mode=grouped\|files` | Totali (sempre elementi: `entries`, `accounts`) e giorni con conteggio e cursore (per la finestra del mosaico); con `mode=files` («Tutte le foto») i giorni contano i file presenti in libreria e `files` è la loro somma (altrimenti `null`). Un altro valore di `mode` dà 400. Stessi filtri di `/api/library` | -| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`, `copies=notCopied\|copied\|removedOrSuperseded` (solo i file dovuti; un altro valore 400). Con una cartella delle copie in uso le tessere hanno `copies` (`copied`, `partly` con `copiesDone`/`copiesDue`) e `/days` ha `hasDestinations`; il visualizzatore dà le copie di ogni file (`copies`, al più 6) e `canCopy`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | +| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind` (con `kind=stillvideos`, «Video fermi» della tappa E4: gli elementi con un video in libreria la cui ultima analisi dice «Fermo», e con `mode=files` solo quei video), `accounts`, `from`, `to`, `provenance`, `q`, `copies=notCopied\|copied\|removedOrSuperseded` (solo i file dovuti; un altro valore 400). Con una cartella delle copie in uso le tessere hanno `copies` (`copied`, `partly` con `copiesDone`/`copiesDue`) e `/days` ha `hasDestinations`; il visualizzatore dà le copie di ogni file (`copies`, al più 6) e `canCopy`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | | `GET /api/library/tiles?ids=` | Tessere per chiave | | `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) | | `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) | diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index 621b7e7..e3f8b0e 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -81,17 +81,20 @@ public sealed class LibraryScaleTests } var copies = await FillCopiesAsync(db, temp, accountIds, ct); + var still = await FillStillVideosAsync(db, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare"); + TestContext.WriteLine($"Video fermi: {still.Analyses:N0} analisi, {still.Still:N0} «Fermo» (di cui {still.Overruled:N0} superati da un algoritmo più nuovo), {still.Entries:N0} elementi e {still.Files:N0} file nel filtro"); Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill"); Assert.IsGreaterThan(0, copies.Frames, "frames in the fill"); + Assert.IsGreaterThan(0, still.Overruled, "still videos overruled by a newer algorithm in the fill"); // Plans differ with and without ANALYZE statistics: both must be fast. // The fill stays outside the timings. - await MeasureAll(db, accountIds, copies, "senza statistiche", ct); + await MeasureAll(db, accountIds, copies, still, "senza statistiche", ct); await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct); - await MeasureAll(db, accountIds, copies, "con ANALYZE", ct); + await MeasureAll(db, accountIds, copies, still, "con ANALYZE", ct); } /// @@ -103,8 +106,6 @@ public sealed class LibraryScaleTests /// private static async Task FillCopiesAsync(FebeDatabase db, TempFolder temp, List accountIds, CancellationToken ct) { - const string Hash = "((m.id * 2654435761) % 1000003)"; - const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)"; var general = await db.Exports.AddDestinationAsync( new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct); var own = await db.Exports.AddDestinationAsync( @@ -148,6 +149,55 @@ public sealed class LibraryScaleTests ct); } + // A hash of the media id that mixes the ids (see FillCopiesAsync). + private const string Hash = "((m.id * 2654435761) % 1000003)"; + private const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)"; + + /// + /// Tappa E4, the filter «Video fermi»: seven videos in ten analysed (about 20,000 of the 28,600 videos), half of them + /// «Fermo» (about 10,000, frame at 1 s) and half «In movimento»; one «Fermo» in ten has a newer algorithm that says + /// «In movimento», so it is out of the filter. The expected entries and files are counted here with a join on the + /// highest algorithm, another form than the filter's own. + /// + private static Task FillStillVideosAsync(FebeDatabase db, List accountIds, CancellationToken ct) => + db.WriteAsync( + w => + { + var videos = $"FROM media m WHERE m.kind = 'Video' AND m.sha256 IS NOT NULL AND {Spread} % 10 < 7"; + var analyses = w.Command($""" + INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note) + SELECT m.sha256, 1, CASE WHEN {Spread} % 2 = 0 THEN 'Still' ELSE 'Moving' END, 1767225600000, + CASE WHEN {Spread} % 2 = 0 THEN 1000 END, NULL + {videos} + """).ExecuteNonQuery(); + var overruled = w.Command($""" + INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note) + SELECT m.sha256, 2, 'Moving', 1767225600000, NULL, NULL + {videos} AND {Spread} % 2 = 0 AND {Spread} % 20 < 2 + """).ExecuteNonQuery(); + var still = (int)w.Command("SELECT COUNT(*) FROM video_analysis WHERE outcome = 'Still'").ScalarInt64(); + const string Latest = """ + FROM media m JOIN video_analysis va ON va.sha256 = m.sha256 + WHERE m.kind = 'Video' AND m.state IN ('Downloaded', 'Imported') AND va.outcome = 'Still' + AND va.algorithm = (SELECT MAX(x.algorithm) FROM video_analysis x WHERE x.sha256 = va.sha256) + """; + var entries = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest}").ScalarInt64(); + var files = (int)w.Command($"SELECT COUNT(*) {Latest}").ScalarInt64(); + var account = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)") + .With("@a", accountIds[3]).ScalarInt64(); + var accountFiles = (int)w.Command($"SELECT COUNT(*) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)") + .With("@a", accountIds[3]).ScalarInt64(); + return new StillWorld(analyses + overruled, still, overruled, entries, files, account, accountFiles); + }, + ct); + + /// + /// What the fill of the analyses wrote: rows, «Fermo» rows, those overruled by a newer algorithm, and the entries + /// and files the filter must find ( and : those of + /// account 3). + /// + private sealed record StillWorld(int Analyses, int Still, int Overruled, int Entries, int Files, int AccountEntries, int AccountFiles); + /// The form of the copies an insert writes: variant, format and instant (SQL), name suffix, copy SHA (SQL). private sealed record Form(string Variant, string Format, string FrameAt, string Suffix, string? CopySha) { @@ -162,7 +212,7 @@ public sealed class LibraryScaleTests _ => 1 + (n % 5 == 0 ? 1 : 0), }); - private async Task MeasureAll(FebeDatabase db, List accountIds, CopiesWorld copies, string label, CancellationToken ct) + private async Task MeasureAll(FebeDatabase db, List accountIds, CopiesWorld copies, StillWorld still, string label, CancellationToken ct) { var times = new List<(string Name, double Bound, Timing Timing)>(); async Task Measure(string name, double bound, Func> query) @@ -232,6 +282,31 @@ public sealed class LibraryScaleTests await Measure("scheda account: Post, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } })); await Measure("scheda account: conteggi dei Post", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts }, TestZones.Rome)); await Measure("tutte le foto: conteggi del filtro Video", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files)); + // «Video fermi» (tappa E4): the windows at the bound of the windows, totals and days at those of «Foto» and «Video». + var stillFilter = new LibraryFilter { Kind = LibraryKindFilter.StillVideos }; + var stillWindow = await Measure("filtro Video fermi", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillFilter })); + Assert.HasCount(200, stillWindow.Tiles); + var stillMiddle = await Measure("Video fermi: finestra a metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillFilter, Cursor = middleCursor })); + Assert.HasCount(200, stillMiddle.Tiles); + var stillFiles = await Measure("Video fermi: tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = stillFilter })); + Assert.HasCount(200, stillFiles.Tiles); + Assert.IsTrue(stillFiles.Tiles.All(t => t.CoverKind == MediaKind.Video)); + var stillAccount = stillFilter with { AccountIds = [accountIds[3]] }; + var stillOwn = await Measure("Video fermi: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillAccount })); + Assert.HasCount(Math.Min(200, still.AccountEntries), stillOwn.Tiles); + await Measure("Video fermi: un account, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = stillAccount })); + var stillTotals = await Measure("totali del filtro Video fermi", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(stillFilter)); + Assert.AreEqual(still.Entries, stillTotals.Entries); + var stillDays = await Measure("conteggi per giorno del filtro Video fermi", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillFilter, TestZones.Rome)); + Assert.AreEqual(still.Entries, stillDays.Sum(d => d.Count)); + var stillFileDays = await Measure("Video fermi: conteggi, tutte le foto", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillFilter, TestZones.Rome, MosaicMode.Files)); + Assert.AreEqual(still.Files, stillFileDays.Sum(d => d.Count)); + var stillAccountDays = await Measure("Video fermi: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillAccount, TestZones.Rome)); + Assert.AreEqual(still.AccountEntries, stillAccountDays.Sum(d => d.Count)); + // With accounts «Tutte le foto» counts each entry apart: a count that went from the SHA-256 index would walk + // every still video for each entry (107 s for one account in the first version). + var stillAccountFiles = await Measure("Video fermi: conteggi di un account, tutte le foto", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillAccount, TestZones.Rome, MosaicMode.Files)); + Assert.AreEqual(still.AccountFiles, stillAccountFiles.Sum(d => d.Count)); await Measure("è già noto? (pagina di 12)", IndexBoundMs, async () => await db.Entries.GetKnownInstagramIdsAsync(accountIds[5], EntryKind.Post, Enumerable.Range(0, 12).Select(i => $"id{5 + (i * 40)}").ToList())); await Measure("SHA-256 in tutta la libreria", IndexBoundMs, () => db.Media.FindBySha256Async(Make.Sha(150_001))); var summaries = await Measure("elenco account con conteggi", AggregateBoundMs, () => db.Accounts.ListSummariesAsync(new DateTimeOffset(2026, 10, 1, 0, 0, 0, TimeSpan.Zero))); diff --git a/tests/Febe.Tests/Data/StillVideoFilterTests.cs b/tests/Febe.Tests/Data/StillVideoFilterTests.cs new file mode 100644 index 0000000..1b20dd0 --- /dev/null +++ b/tests/Febe.Tests/Data/StillVideoFilterTests.cs @@ -0,0 +1,205 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Data; + +/// +/// The library filter «Video fermi» (tappa E4, answer 40 of Alberto): the entries of every kind of «Tutto» with a video +/// in the library whose latest analysis says «Fermo»; in «Tutte le foto» only those videos. Analysis is on request, so +/// a video never analysed is not in it. +/// +[TestClass] +public sealed class StillVideoFilterTests +{ + private static readonly LibraryFilter Still = new() { Kind = LibraryKindFilter.StillVideos }; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task GroupedTheEntriesWithAStillVideoOfEveryKindAndNoOther() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await FillAsync(db, ct); + + var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = Still }, ct); + CollectionAssert.AreEqual( + new[] { w.Story, w.Carousel, w.Newer, w.Copy, w.Tagged }, + page.Tiles.Select(t => t.EntryId).ToArray(), + "newest first: the story, the carousel, the video still under a newer algorithm, the same file in another post, the tagged post"); + Assert.IsNull(page.Older); + Assert.AreEqual(new LibraryTotals(5, 2), await db.Entries.GetLibraryTotalsAsync(Still, ct)); + Assert.AreEqual(5, (await db.Entries.CountLibraryByDayAsync(Still, TestZones.Rome, ct: ct)).Sum(d => d.Count)); + + // Windows of one walk the same entries, both ways. + var walked = new List(); + LibraryCursor? cursor = null; + do + { + var window = await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = Still, Limit = 1, Cursor = cursor }, ct); + walked.AddRange(window.Tiles.Select(t => t.EntryId)); + cursor = window.Older; + } + while (cursor is not null); + + CollectionAssert.AreEqual(page.Tiles.Select(t => t.EntryId).ToArray(), walked.ToArray()); + var last = page.Tiles[^1]; + var newer = await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = Still, Limit = 10, Cursor = new LibraryCursor(last.PublishedAt, last.EntryId), Direction = LibraryDirection.Newer }, ct); + CollectionAssert.AreEqual(page.Tiles.Take(4).Select(t => t.EntryId).ToArray(), newer.Tiles.Select(t => t.EntryId).ToArray()); + + // An account: the same rules (the list read once is the same with or without accounts). + var mine = Still with { AccountIds = [w.Marta] }; + CollectionAssert.AreEqual( + new[] { w.Story, w.Carousel, w.Newer, w.Tagged }, + (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = mine }, ct)).Tiles.Select(t => t.EntryId).ToArray()); + Assert.AreEqual(new LibraryTotals(4, 1), await db.Entries.GetLibraryTotalsAsync(mine, ct)); + Assert.AreEqual(4, (await db.Entries.CountLibraryByDayAsync(mine, TestZones.Rome, ct: ct)).Sum(d => d.Count)); + + // With the other filters. + Assert.AreEqual(new LibraryTotals(1, 1), await db.Entries.GetLibraryTotalsAsync(Still with { Search = "molo" }, ct)); + Assert.AreEqual(new LibraryTotals(1, 1), await db.Entries.GetLibraryTotalsAsync(Still with { Provenance = Provenance.Imported }, ct)); + } + + [TestMethod] + public async Task AllThePhotosShowOnlyTheStillVideos() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await FillAsync(db, ct); + var files = new LibraryQuery { Filter = Still, Mode = MosaicMode.Files }; + + var page = await db.Entries.QueryLibraryAsync(files, ct); + CollectionAssert.AreEqual( + new[] { $"{w.Story}.1", $"{w.Carousel}.2", $"{w.Newer}.1", $"{w.Copy}.1", $"{w.Tagged}.2" }, + page.Tiles.Select(Key).ToArray(), + "only the still video of the carousel, not its photo nor its moving video"); + Assert.IsTrue(page.Tiles.All(t => t.CoverKind == MediaKind.Video)); + Assert.AreEqual(5, await FileTotalAsync(db, Still, ct)); + Assert.AreEqual(4, await FileTotalAsync(db, Still with { AccountIds = [w.Marta] }, ct), "counted entry by entry: the same files"); + + // Windows of one file, from the top and back. + var walked = new List(); + LibraryCursor? cursor = null; + do + { + var window = await db.Entries.QueryLibraryAsync(files with { Limit = 1, Cursor = cursor }, ct); + walked.AddRange(window.Tiles.Select(Key)); + cursor = window.Older; + } + while (cursor is not null); + + CollectionAssert.AreEqual(page.Tiles.Select(Key).ToArray(), walked.ToArray()); + + // «Copia in…» and «Cerca i video fermi» on the filter: the files the mosaic shows, or the whole entries. + var candidates = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(Still, MosaicMode.Files), 0, 100, ct); + CollectionAssert.AreEquivalent(page.Tiles.Select(t => t.CoverMediaId).ToArray(), candidates.Select(c => (long?)c.MediaId).ToArray()); + var grouped = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(Still, MosaicMode.Grouped), 0, 100, ct); + Assert.HasCount(8, grouped, "grouped: every file of the five entries (three of the carousel, two of the tagged post)"); + } + + [TestMethod] + public async Task ANewerAnalysisOrAChangedFileTakesTheVideoOut() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await FillAsync(db, ct); + + // «Analizza di nuovo» with a newer algorithm says «In movimento»: the story goes, in both modes. + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(4), 2, VideoAnalysisOutcome.Moving, Make.T0), ct); + Assert.IsFalse((await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = Still }, ct)).Tiles.Any(t => t.EntryId == w.Story)); + Assert.AreEqual(4, await FileTotalAsync(db, Still, ct)); + + // The file of the carousel is replaced by another (a rebuild, «Tieni il più grande»): its analysis was of the + // old file, so the carousel goes; the post with the same old file stays. + var video = (await db.Media.ListByEntryAsync(w.Carousel, ct)).Single(m => m.Position == 2); + await db.Media.UpdateAsync(video with { Sha256 = Make.Sha(99) }, ct); + CollectionAssert.AreEqual( + new[] { w.Newer, w.Copy, w.Tagged }, + (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = Still }, ct)).Tiles.Select(t => t.EntryId).ToArray()); + Assert.AreEqual(new LibraryTotals(3, 2), await db.Entries.GetLibraryTotalsAsync(Still, ct)); + + // The file leaves the library (deleted): the entry goes too, though the analysis stays. + var tagged = (await db.Media.ListByEntryAsync(w.Tagged, ct)).Single(m => m.Kind == MediaKind.Video); + await db.Media.UpdateAsync(tagged with { State = MediaState.Deleted }, ct); + Assert.AreEqual(new LibraryTotals(2, 2), await db.Entries.GetLibraryTotalsAsync(Still, ct)); + Assert.AreEqual(2, await FileTotalAsync(db, Still, ct)); + Assert.IsNotNull(await db.VideoAnalyses.GetAsync(Make.Sha(9), ct)); + } + + private static string Key(LibraryTile tile) => $"{tile.EntryId}.{tile.FilePosition}"; + + private static async Task FileTotalAsync(FebeDatabase db, LibraryFilter filter, CancellationToken ct) => + (await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count); + + /// + /// Two accounts and their entries, newest first (13 Oct, local time), with the analyses of their videos: + /// + /// 12:00 a story of marta, video 4 «Fermo»; + /// 11:00 a post of marta, video 5 never analysed; + /// 10:00 a carousel of marta: photo 1, video 2 «Fermo», video 3 «In movimento»; + /// 9:00 a post of marta, video 6 «Fermo» under algorithm 1 but «In movimento» under algorithm 2; + /// 8:00 a post of marta, video 7 «In movimento» under algorithm 1 but «Fermo» under algorithm 2; + /// 7:00 an imported post of luca with the same video 2 as the carousel, caption «Il molo»; + /// 6:00 a post of luca, video 8 «Non analizzabile»; + /// 5:00 a tagged post of marta: a photo and video 9 «Fermo»; + /// 4:00 a post of marta with a photo and video 10 «Fermo» that is no longer in the library (deleted). + /// + /// + private static async Task FillAsync(FebeDatabase db, CancellationToken ct) + { + var marta = await db.Accounts.AddAsync(Make.Account("marta.demo"), ct); + var luca = await db.Accounts.AddAsync(Make.Account("luca.demo"), ct); + var day = new DateTimeOffset(2026, 10, 13, 0, 0, 0, TimeSpan.FromHours(2)); + async Task Add(long account, string id, int hour, EntryKind kind, params Media[] media) => + (await db.Entries.AddAsync(Make.Entry(account, id, day.AddHours(hour), kind), media, ct)).Stored.Entry.Id; + Media Video(int sha, int position = 1) => Make.Stored(Make.Video(position), Make.Sha(sha), $"v/{sha}-{position}.mp4"); + Media Photo(int sha, int position = 1) => Make.Stored(Make.Photo(position), Make.Sha(sha), $"p/{sha}-{position}.jpg"); + + var story = await Add(marta.Id, "st", 12, EntryKind.Story, Video(4)); + await Add(marta.Id, "never", 11, EntryKind.Post, Video(5)); + var carousel = await Add(marta.Id, "c", 10, EntryKind.Post, Photo(1), Video(2, 2), Video(3, 3)); + await Add(marta.Id, "older", 9, EntryKind.Post, Video(6)); + var newer = await Add(marta.Id, "newer", 8, EntryKind.Post, Video(7)); + var copy = (await db.Entries.AddAsync( + Make.Entry(luca.Id, "copy", day.AddHours(7), EntryKind.Post, "Il molo") with { Provenance = Provenance.Imported }, + [Video(2) with { State = MediaState.Imported }], + ct)).Stored.Entry.Id; + await Add(luca.Id, "na", 6, EntryKind.Post, Video(8)); + var tagged = await Add(marta.Id, "tg", 5, EntryKind.Tagged, Photo(11), Video(9, 2)); + await Add(marta.Id, "gone", 4, EntryKind.Post, Photo(12), Video(10, 2) with { State = MediaState.Deleted }); + + VideoAnalysis Of(int sha, int algorithm, VideoAnalysisOutcome outcome) => new( + Make.Sha(sha), + algorithm, + outcome, + Make.T0, + outcome == VideoAnalysisOutcome.Still ? TimeSpan.FromMilliseconds(500) : null, + outcome == VideoAnalysisOutcome.NotAnalyzable ? VideoAnalysisNotes.FrameNotAvailable : null); + foreach (var analysis in new[] + { + Of(4, 1, VideoAnalysisOutcome.Still), + Of(2, 1, VideoAnalysisOutcome.Still), + Of(3, 1, VideoAnalysisOutcome.Moving), + Of(6, 1, VideoAnalysisOutcome.Still), + Of(6, 2, VideoAnalysisOutcome.Moving), + Of(7, 1, VideoAnalysisOutcome.Moving), + Of(7, 2, VideoAnalysisOutcome.Still), + Of(8, 1, VideoAnalysisOutcome.NotAnalyzable), + Of(9, 1, VideoAnalysisOutcome.Still), + Of(10, 1, VideoAnalysisOutcome.Still), + }) + { + await db.VideoAnalyses.SetAsync(analysis, ct); + } + + return new World(marta.Id, story, carousel, newer, copy, tagged); + } + + private sealed record World(long Marta, long Story, long Carousel, long Newer, long Copy, long Tagged); +} diff --git a/tests/Febe.Tests/Web/StillVideosApiTests.cs b/tests/Febe.Tests/Web/StillVideosApiTests.cs index 3f7d257..67aeed5 100644 --- a/tests/Febe.Tests/Web/StillVideosApiTests.cs +++ b/tests/Febe.Tests/Web/StillVideosApiTests.cs @@ -293,6 +293,32 @@ public sealed class StillVideosApiTests } } + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheLibraryFilterVideoFermiShowsWhatTheAnalysisFound() + { + // Answer 40: «Video fermi» among the kinds of the library, kind=stillvideos; only what was analysed and is still. + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Photo(4), WebLibrary.Video(Still(3)), WebLibrary.Video(Moving())); + var other = await WebLibrary.AddPostAsync(server, marta, "mosso", Make.T0.AddDays(-2), WebLibrary.Video(PcmVideos.Mp4(12, i => PcmVideos.Photo(200 + i)))); + Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days?kind=stillvideos")).Int("entries"), "nothing analysed yet: analysis is on request"); + + foreach (var media in new[] { post.Media[1], post.Media[2], other.Media[0] }) + { + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{media.Id}/still")).Status); + } + + var grouped = await server.GetJsonAsync("/api/library?kind=stillvideos&limit=50"); + CollectionAssert.AreEqual(new[] { post.Entry.Id }, grouped.Items("tiles").Select(t => t.Long("id")).ToArray()); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?kind=stillvideos")).Int("entries")); + var files = await server.GetJsonAsync("/api/library?mode=files&kind=StillVideos&limit=50"); + CollectionAssert.AreEqual(new[] { post.Media[1].Id }, files.Items("tiles").Select(t => t.GetProperty("cover").Long("mediaId")).ToArray(), "only the still video, not the photo nor the moving video of the post"); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?mode=files&kind=stillvideos")).Int("files")); + Assert.AreEqual(1, (await server.GetJsonAsync($"/api/library/days?kind=stillvideos&accounts={marta.Id}")).Int("entries")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?kind=fermi")).Status); + } + [TestMethod] public async Task CommandsOfStillVideosComeOnlyFromFebesPages() {