Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
1043 lines
54 KiB
C#
1043 lines
54 KiB
C#
using System.Globalization;
|
|
using System.Security.Cryptography;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Storage;
|
|
|
|
namespace Febe.Web.Demo;
|
|
|
|
/// <summary>A session of the demo day (strip of the day, budgets).</summary>
|
|
public sealed record DemoSession(DateTimeOffset Start, DateTimeOffset End, int ProfilesOpened, int StoriesViewed, int HistoryPages, long Bytes, int NewEntries);
|
|
|
|
/// <summary>A line of «Appena fatto».</summary>
|
|
public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge);
|
|
|
|
/// <summary>Everything the demo engine needs to tell a coherent day (spec §10.6: «i conteggi tornano, gli orari sono plausibili»).</summary>
|
|
public sealed class DemoWorld
|
|
{
|
|
public required DateTimeOffset SeededAt { get; init; }
|
|
|
|
public required TimeZoneInfo Zone { get; init; }
|
|
|
|
/// <summary>Sample picture files by SHA-256 (the demo library shares them between entries).</summary>
|
|
public required IReadOnlyDictionary<string, string> Pictures { get; init; }
|
|
|
|
public required DateTimeOffset WindowStart { get; init; }
|
|
|
|
public required DateTimeOffset WindowEnd { get; init; }
|
|
|
|
public required DateTimeOffset NextWindowStart { get; init; }
|
|
|
|
/// <summary>Today's sessions, all ended before <see cref="SeededAt"/>.</summary>
|
|
public required IReadOnlyList<DemoSession> Today { get; init; }
|
|
|
|
/// <summary>Indicative start of the next session (null outside the window).</summary>
|
|
public DateTimeOffset? NextSession { get; init; }
|
|
|
|
public required int HomeToday { get; init; }
|
|
|
|
public required int ProfilesToday { get; init; }
|
|
|
|
public required int StoriesToday { get; init; }
|
|
|
|
public required int HistoryPagesToday { get; init; }
|
|
|
|
public required int SinglePostsToday { get; init; }
|
|
|
|
public required long BytesToday { get; init; }
|
|
|
|
/// <summary>Entries discovered today (as <c>CountDiscoveredAsync</c> counts them for the strip).</summary>
|
|
public required int DiscoveredToday { get; init; }
|
|
|
|
public required IReadOnlyList<DemoAction> Recent { get; init; }
|
|
|
|
public required int Accounts { get; init; }
|
|
|
|
public required int Entries { get; init; }
|
|
|
|
public required long MineId { get; init; }
|
|
|
|
public required string MineUsername { get; init; }
|
|
|
|
/// <summary>Sample pictures in the proportions of a story (the browser preview of the demo).</summary>
|
|
public IReadOnlyList<string> StoryPictures { get; init; } = [];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fills a temporary library with coherent demo data (spec §10.6): 38 accounts ending in «.demo» («@tuo.profilo» is
|
|
/// «Tu»), every account state, thousands of entries over many days, flat generated pictures in several proportions,
|
|
/// series of files, videos (cover only), stories, highlights, tagged posts, imported entries, the list of followed
|
|
/// profiles, two weeks of check history aligned with the sessions. Every count derives from the same data: an entry
|
|
/// exists only if a check of its account came after its publication.
|
|
/// </summary>
|
|
public static class DemoSeeder
|
|
{
|
|
/// <summary>Posts per page of history, as the engine estimates them (decisions: H3).</summary>
|
|
private const int PostsPerPage = 12;
|
|
|
|
private static readonly string[] Captions =
|
|
[
|
|
"Ultima luce sulle colline prima di cena. La luce delle sei di sera qui non ha bisogno di filtri, e nemmeno di tante parole.",
|
|
"Pranzo della domenica, come sempre troppo.",
|
|
"Il mare d'ottobre ha un altro colore.",
|
|
"Prove generali per sabato: venite presto.",
|
|
"Nuova pagina del quaderno.",
|
|
"Si riparte, zaino leggero.",
|
|
"Fiori dall'orto di casa, gli ultimi della stagione.",
|
|
"Una finestra, una pianta, un caffè.",
|
|
"La città quando si spegne il traffico.",
|
|
"In cima, finalmente. Il vento non perdona.",
|
|
"Tramonto dal molo, ancora una volta.",
|
|
"Ricetta della nonna, versione veloce.",
|
|
"Allenamento delle sette: fatto.",
|
|
"Le case colorate del porto.",
|
|
"Luci, musica e amici.",
|
|
"Il sentiero era più lungo di come ricordavo.",
|
|
"Ritratto di famiglia, quasi tutti fermi.",
|
|
"Pane appena sfornato, si scotta chi aspetta.",
|
|
"Piccole cose belle di questa settimana.",
|
|
"Il primo freddo e la prima zuppa.",
|
|
"Una passeggiata senza meta.",
|
|
"Il salotto rifatto, finalmente.",
|
|
];
|
|
|
|
private static readonly string[] Tags =
|
|
[
|
|
"#sera #colline #luce", "#ricette #pranzo", "#mare #ottobre", "#viaggio #zaino", "#montagna #cima", "#fiori #orto",
|
|
"#casa #piante", "#città #notte", "#amici #musica", "#corsa #mattina", "", "", "",
|
|
];
|
|
|
|
private static readonly string[] CollectionTitles =
|
|
["Estate 2025", "Viaggi", "Ricette", "Montagna", "Amici", "Mare", "Casa", "Concerti", "Corse", "Orto", "Natale", "Lavori", "Famiglia", "Weekend"];
|
|
|
|
/// <summary>The demo accounts. Counts are entries in the library (profile pictures apart).</summary>
|
|
private static readonly AccountSpec[] Specs =
|
|
[
|
|
new("tuo.profilo", "Il tuo profilo", false, false, AccountState.UpToDate, 420, 980, 140, 5, 402, 4, [DemoSubject.Hills, DemoSubject.Sea, DemoSubject.Food, DemoSubject.Portrait, DemoSubject.Room, DemoSubject.Sunset, DemoSubject.CityNight]) { Mine = true },
|
|
new("marta.demo", "Marta B.", true, true, AccountState.UpToDate, 810, 312, 92, 6, 40, 4, [DemoSubject.Portrait, DemoSubject.Flowers, DemoSubject.Food, DemoSubject.Room, DemoSubject.Sunset, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Houses, DemoSubject.Hills]) { Imported = 30, Tagging = true },
|
|
new("studio.lumen.demo", "Studio Lumen", false, false, AccountState.Backfilling, 340, 8, 4, 4, 0, 3, [DemoSubject.Room, DemoSubject.Portrait, DemoSubject.Bokeh, DemoSubject.Leaves]) { PostCount = 1280, BackfillToday = 300 },
|
|
new("luca.viaggi.demo", "Luca in viaggio", false, true, AccountState.UpToDate, 1900, 1000, 208, 8, 0, 4, [DemoSubject.Mountains, DemoSubject.Sea, DemoSubject.Road, DemoSubject.Hills, DemoSubject.Houses, DemoSubject.Sunset]) { Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories, ProfilePictures = 2 },
|
|
new("nonna.pina.demo", "Pina", true, true, AccountState.UpToDate, 150, 50, 14, 2, 0, 3, [DemoSubject.Food, DemoSubject.Flowers, DemoSubject.Room, DemoSubject.Portrait]) { Types = ContentTypes.PostPhotos | ContentTypes.Stories | ContentTypes.Highlights },
|
|
new("circolo.foto.demo", "Circolo fotografico", false, true, AccountState.Backfilling, 2060, 0, 11, 3, 0, 4, [DemoSubject.Mountains, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Hills, DemoSubject.Bokeh, DemoSubject.Houses, DemoSubject.Road]) { PostCount = 2410, BackfillToday = 150, Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Highlights | ContentTypes.Tagged | ContentTypes.ProfilePicture },
|
|
new("giulia.corre.demo", "Giulia", false, true, AccountState.UpToDate, 600, 230, 46, 3, 0, 3, [DemoSubject.Road, DemoSubject.Hills, DemoSubject.Mountains, DemoSubject.Portrait, DemoSubject.Sea]) { ProfilePictures = 3, Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories | ContentTypes.Highlights },
|
|
new("trattoria.demo", "Trattoria del ponte", false, false, AccountState.Paused, 100, 20, 9, 2, 0, 2, [DemoSubject.Food, DemoSubject.Room]) { PausedDaysAgo = 11, Types = ContentTypes.PostPhotos | ContentTypes.Stories },
|
|
new("chiuso.demo", "Profilo privato", true, false, AccountState.Unreachable, 0, 0, 0, 0, 0, 1, [DemoSubject.Portrait]) { Types = ContentTypes.All & ~ContentTypes.Tagged },
|
|
new("estate.2019.demo", "Importato da cartella", false, false, AccountState.ArchiveOnly, 0, 0, 0, 0, 0, 1, [DemoSubject.Sea, DemoSubject.Sunset, DemoSubject.Hills, DemoSubject.Food, DemoSubject.Portrait]) { Imported = 1127, ImportedYear = 2019 },
|
|
new("anna.orto.demo", "Anna", true, true, AccountState.UpToDate, 210, 80, 18, 2, 0, 3, [DemoSubject.Flowers, DemoSubject.Leaves, DemoSubject.Food]),
|
|
new("bici.e.sale.demo", "Bici e sale", false, true, AccountState.UpToDate, 180, 40, 0, 0, 0, 2, [DemoSubject.Road, DemoSubject.Sea, DemoSubject.Hills]),
|
|
new("carla.legno.demo", "Carla, falegname", false, true, AccountState.UpToDate, 260, 60, 12, 2, 0, 3, [DemoSubject.Room, DemoSubject.Leaves]),
|
|
new("elena.acquerelli.demo", "Elena", true, true, AccountState.UpToDate, 320, 90, 24, 3, 0, 3, [DemoSubject.Flowers, DemoSubject.Sunset, DemoSubject.Houses]),
|
|
new("forno.demo", "Forno di quartiere", false, true, AccountState.UpToDate, 230, 110, 10, 2, 0, 2, [DemoSubject.Food, DemoSubject.Room]),
|
|
new("giardino.alto.demo", "Giardino alto", false, true, AccountState.UpToDate, 140, 30, 0, 0, 0, 2, [DemoSubject.Flowers, DemoSubject.Leaves, DemoSubject.Hills]),
|
|
new("il.porto.demo", "Il porto", false, false, AccountState.UpToDate, 120, 25, 6, 1, 0, 2, [DemoSubject.Sea, DemoSubject.Houses, DemoSubject.Sunset]) { ProfilePictures = 1, Frequency = Frequency.Low },
|
|
new("lago.blu.demo", "Lago blu", false, true, AccountState.UpToDate, 90, 20, 0, 0, 0, 2, [DemoSubject.Sea, DemoSubject.Mountains]),
|
|
new("marco.scatti.demo", "Marco", false, true, AccountState.UpToDate, 480, 120, 30, 3, 0, 4, [DemoSubject.CityNight, DemoSubject.Bokeh, DemoSubject.Portrait, DemoSubject.Houses]),
|
|
new("montagna.viva.demo", "Montagna viva", false, true, AccountState.UpToDate, 350, 70, 20, 2, 0, 4, [DemoSubject.Mountains, DemoSubject.Hills, DemoSubject.Road]),
|
|
new("nina.balla.demo", "Nina", true, true, AccountState.UpToDate, 160, 140, 22, 2, 0, 2, [DemoSubject.Concert, DemoSubject.Portrait, DemoSubject.Bokeh]),
|
|
new("orto.botanico.demo", "Orto botanico", false, false, AccountState.UpToDate, 200, 15, 8, 1, 0, 3, [DemoSubject.Leaves, DemoSubject.Flowers]) { Frequency = Frequency.Low },
|
|
new("paolo.cucina.demo", "Paolo in cucina", false, true, AccountState.UpToDate, 300, 150, 36, 4, 0, 3, [DemoSubject.Food]),
|
|
new("pietro.bici.demo", "Pietro", false, true, AccountState.Paused, 75, 10, 0, 0, 0, 2, [DemoSubject.Road, DemoSubject.Hills]) { PausedDaysAgo = 30 },
|
|
new("rosa.ricama.demo", "Rosa", true, true, AccountState.UpToDate, 110, 20, 6, 1, 0, 3, [DemoSubject.Flowers, DemoSubject.Room]),
|
|
new("sara.disegna.demo", "Sara", false, true, AccountState.UpToDate, 280, 95, 15, 2, 0, 3, [DemoSubject.Portrait, DemoSubject.Houses, DemoSubject.Sunset]),
|
|
new("teatro.piccolo.demo", "Teatro piccolo", false, true, AccountState.UpToDate, 130, 60, 12, 2, 0, 3, [DemoSubject.Concert, DemoSubject.Bokeh, DemoSubject.Room]),
|
|
new("tommaso.demo", "Tommaso", true, true, AccountState.UpToDate, 95, 45, 0, 0, 0, 2, [DemoSubject.Portrait, DemoSubject.CityNight]),
|
|
new("vela.club.demo", "Vela club", false, true, AccountState.UpToDate, 170, 35, 10, 2, 0, 3, [DemoSubject.Sea, DemoSubject.Sunset]) { Frequency = Frequency.High },
|
|
new("zia.lu.demo", "Zia Lu", true, true, AccountState.UpToDate, 60, 25, 0, 0, 0, 2, [DemoSubject.Food, DemoSubject.Flowers, DemoSubject.Portrait]),
|
|
new("bar.centrale.demo", "Bar centrale", false, false, AccountState.UpToDate, 70, 30, 0, 0, 0, 2, [DemoSubject.Food, DemoSubject.CityNight]) { Types = ContentTypes.PostPhotos | ContentTypes.Stories, Frequency = Frequency.Low },
|
|
new("coro.valle.demo", "Coro della valle", false, true, AccountState.UpToDate, 85, 10, 5, 1, 0, 3, [DemoSubject.Concert, DemoSubject.Hills]) { Frequency = Frequency.Low },
|
|
new("dario.foto.demo", "Dario", false, true, AccountState.UpToDate, 420, 60, 18, 2, 0, 4, [DemoSubject.Mountains, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Leaves]),
|
|
new("festa.paese.demo", "Festa del paese", false, true, AccountState.UpToDate, 55, 25, 8, 1, 0, 2, [DemoSubject.Concert, DemoSubject.Bokeh, DemoSubject.Food]) { Frequency = Frequency.Low },
|
|
new("libreria.sotto.demo", "Libreria di sotto", false, true, AccountState.UpToDate, 150, 40, 6, 1, 0, 3, [DemoSubject.Room, DemoSubject.Houses]),
|
|
new("matteo.corre.demo", "Matteo", false, true, AccountState.UpToDate, 125, 55, 0, 0, 0, 2, [DemoSubject.Road, DemoSubject.Hills, DemoSubject.Mountains]),
|
|
new("quaderni.demo", "Quaderni", false, true, AccountState.UpToDate, 140, 30, 8, 1, 0, 2, [DemoSubject.Room, DemoSubject.Leaves, DemoSubject.Flowers]),
|
|
new("vecchie.foto.demo", "Vecchie foto di famiglia", false, false, AccountState.ArchiveOnly, 0, 0, 0, 0, 0, 1, [DemoSubject.Portrait, DemoSubject.Sea, DemoSubject.Hills, DemoSubject.Houses]) { Imported = 412, ImportedYear = 2016 },
|
|
];
|
|
|
|
private static readonly string[] ExtraFollowedFirst =
|
|
["bianca", "carlo", "davide", "eva", "franco", "gaia", "ivo", "lia", "mirko", "noemi", "olga", "piero", "rita", "sergio", "tina", "ugo", "vera", "walter", "alba", "bruno"];
|
|
|
|
private static readonly string[] ExtraFollowedSecond = ["vola", "pesca", "scrive", "cucina", "suona", "dipinge", "viaggia", "nuota", "pedala", "legge"];
|
|
|
|
/// <summary>Fills the database and the sample pictures. Nothing is written outside the given folders.</summary>
|
|
public static async Task<DemoWorld> SeedAsync(IFebeStorage storage, DataFolderLayout data, LibraryLayout layout, IClock clock, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(storage);
|
|
ArgumentNullException.ThrowIfNull(data);
|
|
ArgumentNullException.ThrowIfNull(layout);
|
|
ArgumentNullException.ThrowIfNull(clock);
|
|
var now = clock.Now;
|
|
var zone = clock.LocalZone;
|
|
var random = new Random(2026);
|
|
var thumbnails = new ThumbnailStore(data.Thumbnails);
|
|
var pictures = Path.Combine(data.Root, "campioni");
|
|
var pool = await Task.Run(() => DemoPictures.Create(pictures, thumbnails), ct).ConfigureAwait(false);
|
|
|
|
// Days, active windows and sessions of the last two weeks (today up to now).
|
|
var today = LocalCalendar.Today(now, zone);
|
|
var days = new Dictionary<DateOnly, (DateTimeOffset Start, DateTimeOffset End, List<(DateTimeOffset Start, DateTimeOffset End)> Sessions)>();
|
|
for (var back = 14; back >= -1; back--)
|
|
{
|
|
var day = today.AddDays(-back);
|
|
var dayStart = LocalCalendar.StartOfDay(day, zone);
|
|
var windowStart = dayStart + TimeSpan.FromMinutes((7 * 60) + 30 + random.Next(-25, 26));
|
|
var windowEnd = dayStart + TimeSpan.FromMinutes((23 * 60) + 30 + random.Next(-25, 26));
|
|
var sessions = new List<(DateTimeOffset, DateTimeOffset)>();
|
|
var t = windowStart + TimeSpan.FromMinutes(random.Next(2, 11));
|
|
while (t < windowEnd)
|
|
{
|
|
var length = TimeSpan.FromMinutes(LogUniform(random, 2, 10));
|
|
if (back == 0 && t + length > now - TimeSpan.FromMinutes(3))
|
|
{
|
|
break;
|
|
}
|
|
|
|
if (back >= 0)
|
|
{
|
|
sessions.Add((t, t + length));
|
|
}
|
|
|
|
t += length + TimeSpan.FromMinutes(LogUniform(random, 20, 90));
|
|
}
|
|
|
|
days[day] = (windowStart, windowEnd, sessions);
|
|
}
|
|
|
|
var allSessions = days.Where(d => d.Key <= today).SelectMany(d => d.Value.Sessions).OrderBy(s => s.Start).ToList();
|
|
var todaySessions = days[today].Sessions;
|
|
var lastSessionEnd = allSessions.Count > 0 ? allSessions[^1].End : now - TimeSpan.FromHours(10);
|
|
var windowToday = days[today];
|
|
DateTimeOffset? nextSession = null;
|
|
var nextCandidate = lastSessionEnd + TimeSpan.FromMinutes(LogUniform(random, 20, 90));
|
|
if (nextCandidate < now + TimeSpan.FromMinutes(4))
|
|
{
|
|
nextCandidate = now + TimeSpan.FromMinutes(random.Next(12, 35));
|
|
}
|
|
|
|
if (now >= windowToday.Start && nextCandidate < windowToday.End)
|
|
{
|
|
nextSession = nextCandidate;
|
|
}
|
|
else if (now < windowToday.Start)
|
|
{
|
|
nextSession = windowToday.Start + TimeSpan.FromMinutes(random.Next(2, 11));
|
|
}
|
|
|
|
var nextWindow = now < windowToday.Start ? windowToday.Start : days[today.AddDays(1)].Start;
|
|
|
|
// The gradual start of the demo engine ended long ago (the panel «Con queste impostazioni» says so).
|
|
await storage.Settings.SetAsync(Febe.Core.Engine.EngineSettingKeys.RampStart, (now - TimeSpan.FromDays(60)).ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
|
|
|
|
// Accounts.
|
|
var accounts = new List<(AccountSpec Spec, Account Account)>();
|
|
foreach (var spec in Specs)
|
|
{
|
|
var account = Build(spec, now, zone);
|
|
account = await storage.Accounts.AddAsync(account, ct).ConfigureAwait(false);
|
|
accounts.Add((spec, account));
|
|
}
|
|
|
|
// Checks of the last two weeks. Followed profiles are seen at every session by the «Giro dei profili che
|
|
// segui»; their profile page opens only to reconcile, now and then. Profiles not followed are visited, two to
|
|
// four per session. Only visits count as «profili aperti».
|
|
var checks = new Dictionary<long, List<DateTimeOffset>>();
|
|
var visits = new Dictionary<long, List<DateTimeOffset>>();
|
|
foreach (var (_, account) in accounts)
|
|
{
|
|
checks[account.Id] = [];
|
|
visits[account.Id] = [];
|
|
}
|
|
|
|
var active = accounts.Where(a => a.Spec.State is AccountState.UpToDate or AccountState.Backfilling).ToList();
|
|
var swept = active.Where(a => a.Spec.Followed).ToList();
|
|
var visited = active.Where(a => !a.Spec.Followed).ToList();
|
|
foreach (var session in allSessions)
|
|
{
|
|
var length = Math.Max(30, (session.End - session.Start).TotalSeconds);
|
|
foreach (var (_, account) in swept)
|
|
{
|
|
checks[account.Id].Add(session.Start + TimeSpan.FromSeconds(15 + random.Next(0, 40)));
|
|
}
|
|
|
|
var picks = new List<Account>();
|
|
foreach (var (spec, account) in visited.OrderBy(_ => random.Next()))
|
|
{
|
|
var weight = spec.Frequency switch { Frequency.High => 0.55, Frequency.Low => 0.08, _ => 0.25 } * (spec.Mine ? 1.6 : 1);
|
|
if (picks.Count < 4 && random.NextDouble() < weight)
|
|
{
|
|
picks.Add(account);
|
|
}
|
|
}
|
|
|
|
foreach (var (spec, account) in swept.OrderBy(_ => random.Next()))
|
|
{
|
|
if (picks.Count < 6 && random.NextDouble() < 0.05)
|
|
{
|
|
picks.Add(account);
|
|
}
|
|
}
|
|
|
|
foreach (var account in picks)
|
|
{
|
|
var at = session.Start + TimeSpan.FromSeconds(60 + (random.NextDouble() * (length - 60)));
|
|
visits[account.Id].Add(at);
|
|
if (!account.IsFollowed)
|
|
{
|
|
checks[account.Id].Add(at);
|
|
}
|
|
}
|
|
}
|
|
|
|
// The last session looked at a few well-known accounts (mockup 03: «8 min fa», «12 min fa»).
|
|
if (todaySessions.Count > 0)
|
|
{
|
|
var last = todaySessions[^1];
|
|
foreach (var (spec, account) in active.Where(a => a.Spec.Mine || a.Spec.User is "studio.lumen.demo"))
|
|
{
|
|
var at = last.Start + ((last.End - last.Start) * (0.3 + (0.6 * random.NextDouble())));
|
|
visits[account.Id].Add(at);
|
|
checks[account.Id].Add(at);
|
|
}
|
|
}
|
|
|
|
foreach (var (spec, account) in accounts)
|
|
{
|
|
if (spec.State == AccountState.Paused)
|
|
{
|
|
var at = now - TimeSpan.FromDays(spec.PausedDaysAgo) - TimeSpan.FromHours(random.Next(1, 6));
|
|
visits[account.Id].Add(at);
|
|
checks[account.Id].Add(at);
|
|
}
|
|
else if (spec.State == AccountState.Unreachable)
|
|
{
|
|
var at = LocalCalendar.StartOfDay(today.AddDays(-1), zone) + TimeSpan.FromHours(18.4);
|
|
visits[account.Id].Add(at);
|
|
checks[account.Id].Add(at);
|
|
}
|
|
|
|
checks[account.Id].Sort();
|
|
visits[account.Id].Sort();
|
|
}
|
|
|
|
// Entries.
|
|
var pending = new List<NewEntry>();
|
|
var highlightPlans = new List<(long AccountId, string Title, int Position, List<int> Indexes)>();
|
|
var created = new List<(long AccountId, EntryKind Kind, DateTimeOffset Discovered, long Bytes, int Files, bool Backfill)>();
|
|
var entriesCount = 0;
|
|
foreach (var (spec, account) in accounts)
|
|
{
|
|
var folder = layout.AccountFolder(account);
|
|
var accountChecks = checks[account.Id];
|
|
var made = Publications(spec, account, now, zone, today, random, accountChecks);
|
|
var collections = Math.Min(spec.Collections, CollectionTitles.Length);
|
|
var plans = Enumerable.Range(0, collections)
|
|
.Select(i => (account.Id, CollectionTitles[(i + Math.Abs(account.Username.GetHashCode(StringComparison.Ordinal) % 5)) % CollectionTitles.Length], i, new List<int>()))
|
|
.ToList();
|
|
var highlightIndex = 0;
|
|
foreach (var item in made)
|
|
{
|
|
string? collectionTitle = null;
|
|
if (item.Kind == EntryKind.Highlight && plans.Count > 0)
|
|
{
|
|
var plan = plans[highlightIndex++ % plans.Count];
|
|
collectionTitle = plan.Item2;
|
|
plan.Item4.Add(pending.Count);
|
|
}
|
|
|
|
var entry = new Entry
|
|
{
|
|
AccountId = account.Id,
|
|
Kind = item.Kind,
|
|
InstagramId = item.Imported ? null : NumericId(random),
|
|
Code = item.Kind is EntryKind.Post or EntryKind.Tagged && !item.Imported ? Code(random) : null,
|
|
PublishedAt = item.Published,
|
|
Caption = item.Kind is EntryKind.Post or EntryKind.Tagged && !item.Imported && random.NextDouble() < 0.85 ? Caption(random) : null,
|
|
AuthorUsername = item.Kind == EntryKind.Tagged ? Specs[random.Next(1, Specs.Length - 2)].User : null,
|
|
Provenance = item.Imported ? Provenance.Imported : Provenance.Downloaded,
|
|
State = item.Imported ? EntryState.Imported : EntryState.Downloaded,
|
|
DiscoveredAt = item.Discovered,
|
|
DownloadedAt = item.Discovered + TimeSpan.FromSeconds(random.Next(20, 400)),
|
|
ExpiresAt = item.Kind == EntryKind.Story ? item.Published + TimeSpan.FromHours(24) : null,
|
|
};
|
|
var media = Media(item, entry, spec, account, folder, collectionTitle, layout, zone, pool, random);
|
|
pending.Add(new NewEntry(entry, media));
|
|
created.Add((account.Id, item.Kind, item.Discovered, media.Sum(m => m.Bytes ?? 0), media.Count, item.Backfill));
|
|
entriesCount += item.Kind == EntryKind.ProfilePicture ? 0 : 1;
|
|
}
|
|
|
|
highlightPlans.AddRange(plans);
|
|
}
|
|
|
|
// Insert in batches, then the highlight collections with their items.
|
|
var ids = new List<long>(pending.Count);
|
|
foreach (var batch in pending.Chunk(2500))
|
|
{
|
|
var results = await storage.Entries.AddManyAsync(batch, ct).ConfigureAwait(false);
|
|
ids.AddRange(results.Select(r => r.Stored.Entry.Id));
|
|
}
|
|
|
|
foreach (var (accountId, title, position, indexes) in highlightPlans)
|
|
{
|
|
var highlight = await storage.Highlights.UpsertAsync(
|
|
new Highlight { AccountId = accountId, InstagramId = NumericId(random), Title = title, Position = position, DiscoveredAt = now - TimeSpan.FromDays(200), LastCheckedAt = now - TimeSpan.FromHours(5) },
|
|
ct).ConfigureAwait(false);
|
|
await storage.Highlights.SetItemsAsync(highlight.Id, indexes.Select(i => ids[i]).ToList(), ct).ConfigureAwait(false);
|
|
}
|
|
|
|
// Check times and history, aligned with the entries.
|
|
var events = new List<EventRecord>();
|
|
foreach (var (spec, account) in accounts)
|
|
{
|
|
var seen = checks[account.Id];
|
|
var opened = visits[account.Id];
|
|
if (seen.Count == 0 && opened.Count == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var own = created.Where(c => c.AccountId == account.Id && !c.Backfill && c.Kind != EntryKind.ProfilePicture).ToList();
|
|
DateTimeOffset? lastProfile = opened.Count > 0 ? opened[^1] : null;
|
|
DateTimeOffset? lastStories = spec.Followed
|
|
? own.Where(c => c.Kind == EntryKind.Story).Select(c => (DateTimeOffset?)c.Discovered).DefaultIfEmpty(null).Max()
|
|
: lastProfile;
|
|
DateTimeOffset? next = null;
|
|
if (spec.State is AccountState.UpToDate or AccountState.Backfilling)
|
|
{
|
|
next = spec.Followed && nextSession is { } ns
|
|
? ns + TimeSpan.FromMinutes(random.Next(1, 6))
|
|
: (lastProfile ?? now) + TimeSpan.FromMinutes(random.Next(60, 200));
|
|
if (next < now)
|
|
{
|
|
next = now + TimeSpan.FromMinutes(random.Next(10, 50));
|
|
}
|
|
|
|
if (next > windowToday.End || now < windowToday.Start)
|
|
{
|
|
next = nextWindow + TimeSpan.FromMinutes(random.Next(5, 60));
|
|
}
|
|
}
|
|
|
|
var wantsStories = (spec.Types ?? DefaultTypes(spec)).HasFlag(ContentTypes.Stories);
|
|
await storage.Accounts.UpdateChecksAsync(
|
|
account.Id,
|
|
new AccountCheckTimes
|
|
{
|
|
LastProfileCheckAt = lastProfile,
|
|
NextProfileCheckAt = next,
|
|
LastStoriesCheckAt = wantsStories ? lastStories : null,
|
|
NextStoriesCheckAt = wantsStories ? next : null,
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
|
|
var handle = "@" + account.Username;
|
|
if (spec.State == AccountState.Unreachable)
|
|
{
|
|
events.Add(Event(opened[^1], EventSeverity.Warning, "ricetta.ProfileCheck", $"{handle}: profilo privato che non segui. Febe non lo apre più finché non lo verifichi.", account.Id));
|
|
continue;
|
|
}
|
|
|
|
DateTimeOffset? previous = null;
|
|
foreach (var at in seen)
|
|
{
|
|
var found = own.Where(c => c.Discovered > (previous ?? DateTimeOffset.MinValue) && c.Discovered <= at + TimeSpan.FromMinutes(5)).ToList();
|
|
previous = at;
|
|
if (at < now - TimeSpan.FromDays(15) || (spec.Followed && found.Count == 0))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var posts = found.Count(f => f.Kind is EntryKind.Post or EntryKind.Tagged);
|
|
var stories = found.Count(f => f.Kind is EntryKind.Story or EntryKind.Highlight);
|
|
var detail = posts == 0 && stories == 0
|
|
? "nessuna novità"
|
|
: string.Join(", ", new[]
|
|
{
|
|
posts == 0 ? null : posts == 1 ? "1 post nuovo" : $"{posts} post nuovi",
|
|
stories == 0 ? null : stories == 1 ? "1 storia nuova" : $"{stories} storie nuove",
|
|
}.Where(s => s is not null));
|
|
var code = spec.Followed ? (posts == 0 ? "ricetta.AccountStories" : "ricetta.FollowingSweep") : "ricetta.ProfileCheck";
|
|
events.Add(Event(at, posts + stories > 0 ? EventSeverity.Success : EventSeverity.Info, code, $"{handle}: {detail}", account.Id));
|
|
}
|
|
|
|
if (spec.Followed)
|
|
{
|
|
foreach (var at in opened.Where(o => o >= now - TimeSpan.FromDays(15)))
|
|
{
|
|
events.Add(Event(at, EventSeverity.Info, "ricetta.ProfileCheck", $"{handle}: riconciliazione del profilo, nessuna novità", account.Id));
|
|
}
|
|
}
|
|
|
|
if (spec.BackfillToday > 0)
|
|
{
|
|
var portions = todaySessions.TakeLast(Math.Max(1, (int)Math.Ceiling(spec.BackfillToday / 120.0))).ToList();
|
|
var left = spec.BackfillToday;
|
|
foreach (var session in portions)
|
|
{
|
|
var amount = Math.Min(left, (int)Math.Ceiling(spec.BackfillToday / (double)portions.Count));
|
|
left -= amount;
|
|
events.Add(Event(session.End - TimeSpan.FromSeconds(30), EventSeverity.Success, "ricetta.Backfill", $"{handle}: storico, {amount} post", account.Id));
|
|
}
|
|
}
|
|
|
|
if (spec.State == AccountState.Paused)
|
|
{
|
|
events.Add(Event(now - TimeSpan.FromDays(spec.PausedDaysAgo), EventSeverity.Info, "account.pausa", $"{handle}: messo in pausa da te", account.Id));
|
|
}
|
|
}
|
|
|
|
foreach (var session in allSessions.Where(s => s.Start > now - TimeSpan.FromDays(3)))
|
|
{
|
|
var withNews = created.Count(c => c.Discovered >= session.Start && c.Discovered <= session.End + TimeSpan.FromMinutes(5) && !c.Backfill);
|
|
events.Add(Event(session.Start + TimeSpan.FromSeconds(15), EventSeverity.Info, "ricetta.FollowingSweep",
|
|
withNews == 0 ? "Giro dei profili che segui: nessuna novità" : $"Giro dei profili che segui: {withNews} contenuti nuovi", null));
|
|
}
|
|
|
|
// The alerts of the last days (Attività, «Avvisi»): the throttle of three days ago (as DemoIncidentHistory) and
|
|
// its end, and the backfills completed in the last two weeks.
|
|
var throttle = LocalCalendar.StartOfDay(today.AddDays(-3), zone) + TimeSpan.FromHours(18.4);
|
|
var throttleEnd = throttle + TimeSpan.FromHours(1);
|
|
events.Add(Event(throttle, EventSeverity.Warning, Core.Engine.EngineEventCodes.ThrottleStop,
|
|
$"Instagram ha chiesto di rallentare (segnale http-429). Ho chiuso la sessione e mi fermo per 1 ora, fino {Core.Engine.ItalianText.AtDay(throttleEnd, throttle, zone)}. Poi i tetti restano dimezzati per 48 ore.", null));
|
|
events.Add(Event(throttleEnd, EventSeverity.Info, Core.Engine.EngineEventCodes.ThrottleEnd,
|
|
$"Fine del fermo per rallentamento. Riprendo con i tetti dimezzati fino {Core.Engine.ItalianText.AtDay(throttleEnd + TimeSpan.FromHours(48), throttleEnd, zone)}.", null));
|
|
foreach (var (spec, account) in accounts.Where(a => a.Account.BackfillCompletedAt is { } done && done > now - TimeSpan.FromDays(14) && done < now))
|
|
{
|
|
events.Add(Event(account.BackfillCompletedAt!.Value, EventSeverity.Success, Core.Engine.EngineEventCodes.BackfillCompleted,
|
|
$"Storico di @{account.Username} completato: {Core.Engine.ItalianText.Count(spec.Posts, "post", "post")} in libreria. Da ora lo tengo aggiornato.", account.Id));
|
|
}
|
|
|
|
foreach (var e in events.OrderBy(e => e.At))
|
|
{
|
|
await storage.Events.AppendAsync(e, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
// The list of followed profiles, read two days ago.
|
|
var following = new List<FollowingRecord>();
|
|
var readAt = LocalCalendar.StartOfDay(today.AddDays(-2), zone) + TimeSpan.FromHours(21.25);
|
|
foreach (var (spec, account) in accounts.Where(a => a.Spec.Followed))
|
|
{
|
|
following.Add(new FollowingRecord { InstagramId = account.InstagramId, Username = account.Username, DisplayName = account.DisplayName, IsPrivate = account.IsPrivate, ReadAt = readAt });
|
|
}
|
|
|
|
foreach (var first in ExtraFollowedFirst)
|
|
{
|
|
foreach (var second in ExtraFollowedSecond.Where((_, i) => (i + first.Length) % 3 == 0))
|
|
{
|
|
following.Add(new FollowingRecord
|
|
{
|
|
InstagramId = NumericId(random),
|
|
Username = $"{first}.{second}.demo",
|
|
DisplayName = char.ToUpperInvariant(first[0]) + first[1..],
|
|
IsPrivate = random.NextDouble() < 0.3,
|
|
ReadAt = readAt,
|
|
});
|
|
}
|
|
}
|
|
|
|
var shuffled = following.OrderBy(_ => random.Next()).Select((f, i) => f with { Position = i }).ToList();
|
|
await storage.Following.UpsertAsync(shuffled, ct).ConfigureAwait(false);
|
|
|
|
// What the day looks like for the engine.
|
|
var todayStart = LocalCalendar.StartOfDay(today, zone);
|
|
var todayCreated = created.Where(c => c.Discovered >= todayStart && c.Discovered <= now).ToList();
|
|
var demoSessions = new List<DemoSession>();
|
|
var checksBySession = visits.Values.SelectMany(v => v).Where(t => t >= todayStart).ToList();
|
|
foreach (var session in todaySessions)
|
|
{
|
|
var inSession = todayCreated.Where(c => c.Discovered >= session.Start && c.Discovered <= session.End + TimeSpan.FromMinutes(5)).ToList();
|
|
demoSessions.Add(new DemoSession(
|
|
session.Start,
|
|
session.End,
|
|
checksBySession.Count(t => t >= session.Start && t <= session.End),
|
|
inSession.Count(c => c.Kind is EntryKind.Story or EntryKind.Highlight) + random.Next(2, 9),
|
|
(int)Math.Ceiling(inSession.Count(c => c.Backfill) / (double)PostsPerPage),
|
|
inSession.Sum(c => c.Bytes),
|
|
inSession.Count));
|
|
}
|
|
|
|
var recent = events.Where(e => e.At <= now && e.At >= now - TimeSpan.FromHours(6) && e.Code.StartsWith("ricetta.", StringComparison.Ordinal))
|
|
.OrderByDescending(e => e.At)
|
|
.Take(10)
|
|
.Select(e =>
|
|
{
|
|
var split = e.Message.IndexOf(": ", StringComparison.Ordinal);
|
|
var title = split > 0 ? e.Message[..split] : e.Message;
|
|
var detail = split > 0 ? e.Message[(split + 2)..] : string.Empty;
|
|
return new DemoAction(e.At, title, Capitalize(detail), e.Severity == EventSeverity.Success ? "Scaricato" : null);
|
|
})
|
|
.ToList();
|
|
|
|
var mine = accounts.First(a => a.Spec.Mine).Account;
|
|
var variants = await DemoDuplicates.SeedAsync(storage, thumbnails, pictures, now, ct).ConfigureAwait(false);
|
|
return new DemoWorld
|
|
{
|
|
SeededAt = now,
|
|
Zone = zone,
|
|
Pictures = pool.Files.Concat(variants).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal),
|
|
StoryPictures = [.. pool.All.Where(p => p.Shape == PictureShape.Story).Select(p => p.Path)],
|
|
WindowStart = windowToday.Start,
|
|
WindowEnd = windowToday.End,
|
|
NextWindowStart = nextWindow,
|
|
Today = demoSessions,
|
|
NextSession = nextSession,
|
|
HomeToday = demoSessions.Count,
|
|
ProfilesToday = demoSessions.Sum(s => s.ProfilesOpened),
|
|
StoriesToday = demoSessions.Sum(s => s.StoriesViewed),
|
|
HistoryPagesToday = demoSessions.Sum(s => s.HistoryPages),
|
|
SinglePostsToday = Math.Min(3, demoSessions.Count),
|
|
BytesToday = todayCreated.Sum(c => c.Bytes),
|
|
DiscoveredToday = todayCreated.Count(c => c.Kind != EntryKind.ProfilePicture),
|
|
Recent = recent,
|
|
Accounts = accounts.Count,
|
|
Entries = entriesCount,
|
|
MineId = mine.Id,
|
|
MineUsername = mine.Username,
|
|
};
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------ accounts
|
|
|
|
private sealed record AccountSpec(
|
|
string User,
|
|
string Display,
|
|
bool Private,
|
|
bool Followed,
|
|
AccountState State,
|
|
int Posts,
|
|
int Stories,
|
|
int Highlights,
|
|
int Collections,
|
|
int Tagged,
|
|
double Years,
|
|
DemoSubject[] Themes)
|
|
{
|
|
public bool Mine { get; init; }
|
|
|
|
public bool Tagging { get; init; }
|
|
|
|
public int Imported { get; init; }
|
|
|
|
public int ImportedYear { get; init; }
|
|
|
|
public int? PostCount { get; init; }
|
|
|
|
public int BackfillToday { get; init; }
|
|
|
|
public int PausedDaysAgo { get; init; }
|
|
|
|
public int ProfilePictures { get; init; }
|
|
|
|
public ContentTypes? Types { get; init; }
|
|
|
|
public Frequency Frequency { get; init; } = Frequency.Normal;
|
|
}
|
|
|
|
private static ContentTypes DefaultTypes(AccountSpec spec) =>
|
|
ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories | ContentTypes.Highlights | ContentTypes.ProfilePicture
|
|
| (spec.Mine || spec.Tagging ? ContentTypes.Tagged : ContentTypes.None);
|
|
|
|
private static Account Build(AccountSpec spec, DateTimeOffset now, TimeZoneInfo zone)
|
|
{
|
|
var added = spec.State == AccountState.ArchiveOnly
|
|
? now - TimeSpan.FromDays(95)
|
|
: now - TimeSpan.FromDays(spec.State == AccountState.Backfilling ? (spec.BackfillToday >= 300 ? 1.2 : 9) : 60 + (spec.User.Length * 3));
|
|
var stateChanged = spec.State switch
|
|
{
|
|
AccountState.Paused => now - TimeSpan.FromDays(spec.PausedDaysAgo),
|
|
AccountState.Unreachable => LocalCalendar.StartOfDay(LocalCalendar.Today(now, zone).AddDays(-1), zone) + TimeSpan.FromHours(18.4),
|
|
_ => added,
|
|
};
|
|
return new Account
|
|
{
|
|
InstagramId = spec.State == AccountState.ArchiveOnly ? null : (1_000_000_000L + (Math.Abs(spec.User.GetHashCode(StringComparison.Ordinal)) % 8_000_000_000L)).ToString(CultureInfo.InvariantCulture),
|
|
Username = spec.User,
|
|
DisplayName = spec.Display,
|
|
IsPrivate = spec.Private,
|
|
IsFollowed = spec.Followed,
|
|
IsMine = spec.Mine,
|
|
State = spec.State,
|
|
StateChangedAt = stateChanged,
|
|
UnreachableReason = spec.State == AccountState.Unreachable ? UnreachableReason.PrivateNotFollowed : null,
|
|
KeepUpdated = spec.State is AccountState.UpToDate or AccountState.Backfilling,
|
|
Frequency = spec.Frequency,
|
|
ContentTypes = spec.State == AccountState.ArchiveOnly ? ContentTypes.None : spec.Types ?? DefaultTypes(spec),
|
|
PostCount = spec.PostCount ?? (spec.State == AccountState.ArchiveOnly ? null : spec.Posts),
|
|
BackfillCompletedAt = spec.State == AccountState.Backfilling || spec.State == AccountState.ArchiveOnly ? null : added + TimeSpan.FromDays(4),
|
|
AddedAt = added,
|
|
};
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------ entries
|
|
|
|
private sealed record Item(EntryKind Kind, DateTimeOffset Published, DateTimeOffset Discovered, bool Imported, bool Backfill);
|
|
|
|
private static List<Item> Publications(AccountSpec spec, Account account, DateTimeOffset now, TimeZoneInfo zone, DateOnly today, Random random, List<DateTimeOffset> checks)
|
|
{
|
|
var items = new List<Item>();
|
|
var span = TimeSpan.FromDays(365 * spec.Years);
|
|
var recentLimit = now - TimeSpan.FromDays(14);
|
|
var stop = spec.State switch
|
|
{
|
|
AccountState.Paused => now - TimeSpan.FromDays(spec.PausedDaysAgo),
|
|
_ => now,
|
|
};
|
|
|
|
DateTimeOffset? Discover(DateTimeOffset published)
|
|
{
|
|
if (published >= recentLimit && spec.State is AccountState.UpToDate or AccountState.Backfilling)
|
|
{
|
|
foreach (var check in checks)
|
|
{
|
|
if (check > published + TimeSpan.FromMinutes(1))
|
|
{
|
|
return check + TimeSpan.FromSeconds(random.Next(5, 120));
|
|
}
|
|
}
|
|
|
|
return null; // published after the last check: Febe has not seen it yet
|
|
}
|
|
|
|
var discovered = published + TimeSpan.FromMinutes(random.Next(20, 95));
|
|
return discovered < stop ? discovered : null;
|
|
}
|
|
|
|
// Posts. Backfilling accounts hold the newest posts of a longer history, read newest first: the last
|
|
// «BackfillToday» of them arrived today, the others on the days since the account was added.
|
|
if (spec.Posts > 0)
|
|
{
|
|
var total = spec.PostCount ?? spec.Posts;
|
|
var times = DaytimeSeries(random, total, now - span, stop, zone, recentWeight: 1.6);
|
|
times.Sort((a, b) => b.CompareTo(a));
|
|
var kept = times.Take(spec.Posts).ToList();
|
|
if (spec.State == AccountState.Backfilling && spec.BackfillToday > 0)
|
|
{
|
|
var todayChecks = checks.Where(c => LocalCalendar.Today(c, zone) == today).ToList();
|
|
var firstDay = LocalCalendar.Today(account.AddedAt, zone);
|
|
var earlierDays = Math.Max(1, today.DayNumber - firstDay.DayNumber);
|
|
var earlier = kept.Count - spec.BackfillToday;
|
|
for (var i = 0; i < kept.Count; i++)
|
|
{
|
|
DateTimeOffset discovered;
|
|
if (i >= earlier)
|
|
{
|
|
discovered = todayChecks.Count > 0 ? todayChecks[random.Next(todayChecks.Count)] : now - TimeSpan.FromMinutes(30);
|
|
}
|
|
else
|
|
{
|
|
var day = firstDay.AddDays(Math.Min(earlierDays - 1, i * earlierDays / Math.Max(1, earlier)));
|
|
var dayChecks = checks.Where(c => LocalCalendar.Today(c, zone) == day).ToList();
|
|
discovered = dayChecks.Count > 0
|
|
? dayChecks[random.Next(dayChecks.Count)]
|
|
: LocalCalendar.StartOfDay(day, zone) + TimeSpan.FromMinutes(random.Next(20 * 60, 23 * 60));
|
|
if (discovered < account.AddedAt)
|
|
{
|
|
discovered = account.AddedAt + TimeSpan.FromMinutes(random.Next(5, 60));
|
|
}
|
|
}
|
|
|
|
items.Add(new Item(EntryKind.Post, kept[i], discovered < kept[i] ? kept[i] + TimeSpan.FromMinutes(2) : discovered, false, true));
|
|
}
|
|
}
|
|
else
|
|
{
|
|
foreach (var published in kept)
|
|
{
|
|
if (Discover(published) is { } d)
|
|
{
|
|
items.Add(new Item(EntryKind.Post, published, d, false, false));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Stories: a few on many days, each day in a short burst.
|
|
if (spec.Stories > 0)
|
|
{
|
|
var made = 0;
|
|
var daysBack = (int)Math.Min(span.TotalDays, Math.Max(20, spec.Stories / 1.5));
|
|
for (var guard = 0; made < spec.Stories && guard < spec.Stories * 20; guard++)
|
|
{
|
|
var day = today.AddDays(-random.Next(0, daysBack));
|
|
var start = LocalCalendar.StartOfDay(day, zone) + TimeSpan.FromMinutes(random.Next(8 * 60, 22 * 60));
|
|
var burst = Math.Min(spec.Stories - made, random.Next(1, 6));
|
|
for (var b = 0; b < burst; b++)
|
|
{
|
|
var published = start + TimeSpan.FromMinutes(b * random.Next(1, 7));
|
|
if (published < stop && Discover(published) is { } d)
|
|
{
|
|
items.Add(new Item(EntryKind.Story, published, d, false, false));
|
|
made++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Highlight items: stories of the past kept in collections.
|
|
foreach (var published in DaytimeSeries(random, spec.Highlights, now - span, now - TimeSpan.FromDays(20), zone, recentWeight: 1))
|
|
{
|
|
items.Add(new Item(EntryKind.Highlight, published, published + TimeSpan.FromMinutes(random.Next(20, 95)), false, false));
|
|
}
|
|
|
|
// Tagged posts.
|
|
foreach (var published in DaytimeSeries(random, spec.Tagged, now - span, stop, zone, recentWeight: 1.3))
|
|
{
|
|
if (Discover(published) is { } d)
|
|
{
|
|
items.Add(new Item(EntryKind.Tagged, published, d, false, false));
|
|
}
|
|
}
|
|
|
|
// Imported: an old folder (whole account) or a handful of older posts.
|
|
if (spec.Imported > 0)
|
|
{
|
|
var year = spec.ImportedYear > 0 ? spec.ImportedYear : LocalCalendar.Today(now, zone).Year - 6;
|
|
var from = LocalCalendar.StartOfDay(new DateOnly(year, 5, 20), zone);
|
|
var to = spec.ImportedYear > 0 && spec.State == AccountState.ArchiveOnly && spec.User.StartsWith("vecchie", StringComparison.Ordinal)
|
|
? LocalCalendar.StartOfDay(new DateOnly(year + 2, 12, 20), zone)
|
|
: LocalCalendar.StartOfDay(new DateOnly(year, 9, 25), zone);
|
|
var importedAt = now - TimeSpan.FromDays(94) + TimeSpan.FromHours(random.Next(0, 6));
|
|
foreach (var published in DaytimeSeries(random, spec.Imported, from, to, zone, recentWeight: 1))
|
|
{
|
|
items.Add(new Item(EntryKind.Post, published, importedAt, true, false));
|
|
}
|
|
}
|
|
|
|
// Profile pictures, one per change.
|
|
for (var p = 0; p < spec.ProfilePictures; p++)
|
|
{
|
|
var published = now - TimeSpan.FromDays(40 + (p * 170) + random.Next(0, 30));
|
|
items.Add(new Item(EntryKind.ProfilePicture, published, published + TimeSpan.FromHours(3), false, false));
|
|
}
|
|
|
|
return items;
|
|
}
|
|
|
|
private static List<Media> Media(Item item, Entry entry, AccountSpec spec, Account account, string folder, string? collection, LibraryLayout layout, TimeZoneInfo zone, DemoPictures pool, Random random)
|
|
{
|
|
var list = new List<Media>();
|
|
var subject = spec.Themes[random.Next(spec.Themes.Length)];
|
|
int count;
|
|
var video = false;
|
|
switch (item.Kind)
|
|
{
|
|
case EntryKind.Story or EntryKind.Highlight:
|
|
count = 1;
|
|
video = random.NextDouble() < 0.28;
|
|
break;
|
|
case EntryKind.ProfilePicture:
|
|
count = 1;
|
|
subject = DemoSubject.Portrait;
|
|
break;
|
|
default:
|
|
var roll = random.NextDouble();
|
|
count = item.Imported ? 1 : roll < 0.74 ? 1 : random.Next(2, 9);
|
|
video = !item.Imported && count == 1 && random.NextDouble() < 0.12 && (spec.Types ?? DefaultTypes(spec)).HasFlag(ContentTypes.PostVideos);
|
|
break;
|
|
}
|
|
|
|
var shape = item.Kind switch
|
|
{
|
|
EntryKind.Story or EntryKind.Highlight => PictureShape.Story,
|
|
EntryKind.ProfilePicture => PictureShape.Square,
|
|
_ => video ? (random.NextDouble() < 0.7 ? PictureShape.Story : PictureShape.Portrait) : PickShape(random),
|
|
};
|
|
|
|
for (var n = 1; n <= count; n++)
|
|
{
|
|
var isVideo = video && n == 1;
|
|
var picture = pool.Pick(n == 1 ? subject : spec.Themes[random.Next(spec.Themes.Length)], n == 1 || !video ? shape : PickShape(random), random);
|
|
var extension = isVideo ? ".mp4" : ".jpg";
|
|
var relative = layout.RelativePathFor(folder, LibraryNaming.Default.For(entry.Kind), NamingValues.For(account.Username, entry, n, extension, collection, picture.Sha256), zone);
|
|
list.Add(new Media
|
|
{
|
|
Position = n,
|
|
Kind = isVideo ? MediaKind.Video : MediaKind.Photo,
|
|
Width = picture.Width,
|
|
Height = picture.Height,
|
|
Duration = isVideo ? TimeSpan.FromSeconds(item.Kind is EntryKind.Story or EntryKind.Highlight ? random.Next(5, 16) : random.Next(8, 95)) : null,
|
|
State = item.Imported ? MediaState.Imported : MediaState.Downloaded,
|
|
RelativePath = relative,
|
|
Bytes = isVideo ? random.Next(2_000_000, 38_000_000) : picture.Bytes,
|
|
Sha256 = picture.Sha256,
|
|
PerceptualHash = isVideo ? null : picture.PerceptualHash,
|
|
HasThumbnail = true,
|
|
DownloadedAt = entry.DownloadedAt,
|
|
});
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
private static PictureShape PickShape(Random random)
|
|
{
|
|
var roll = random.NextDouble();
|
|
return roll switch
|
|
{
|
|
< 0.34 => PictureShape.Square,
|
|
< 0.68 => PictureShape.Portrait,
|
|
< 0.82 => PictureShape.Landscape,
|
|
< 0.92 => PictureShape.Tall,
|
|
_ => PictureShape.Wide,
|
|
};
|
|
}
|
|
|
|
/// <summary>Times spread over [from, to), more of them toward the recent end, in plausible hours of the day.</summary>
|
|
private static List<DateTimeOffset> DaytimeSeries(Random random, int count, DateTimeOffset from, DateTimeOffset to, TimeZoneInfo zone, double recentWeight)
|
|
{
|
|
var list = new List<DateTimeOffset>(Math.Max(0, count));
|
|
if (count <= 0 || to <= from)
|
|
{
|
|
return list;
|
|
}
|
|
|
|
var span = (to - from).TotalSeconds;
|
|
for (var i = 0; i < count; i++)
|
|
{
|
|
var u = Math.Pow(random.NextDouble(), 1 / recentWeight);
|
|
var instant = from + TimeSpan.FromSeconds(span * u);
|
|
var day = LocalCalendar.Today(instant, zone);
|
|
var minutes = 7 * 60 + (int)(random.NextDouble() * 16 * 60);
|
|
var time = LocalCalendar.StartOfDay(day, zone) + TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(random.Next(0, 60));
|
|
if (time >= to)
|
|
{
|
|
time = to - TimeSpan.FromMinutes(random.Next(5, 600));
|
|
}
|
|
|
|
if (time < from)
|
|
{
|
|
time = from + TimeSpan.FromMinutes(random.Next(1, 600));
|
|
}
|
|
|
|
list.Add(time);
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
private static EventRecord Event(DateTimeOffset at, EventSeverity severity, string code, string message, long? accountId) =>
|
|
new() { At = at, Severity = severity, Code = code, Message = message, AccountId = accountId };
|
|
|
|
private static string Caption(Random random)
|
|
{
|
|
var text = Captions[random.Next(Captions.Length)];
|
|
var tags = Tags[random.Next(Tags.Length)];
|
|
return tags.Length == 0 ? text : text + "\n\n" + tags;
|
|
}
|
|
|
|
private static string Code(Random random)
|
|
{
|
|
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
Span<char> code = stackalloc char[11];
|
|
code[0] = 'D';
|
|
for (var i = 1; i < code.Length; i++)
|
|
{
|
|
code[i] = alphabet[random.Next(alphabet.Length)];
|
|
}
|
|
|
|
return new string(code);
|
|
}
|
|
|
|
private static string NumericId(Random random) =>
|
|
(3_000_000_000_000_000_000L + (long)(random.NextDouble() * 1_000_000_000_000_000_000L)).ToString(CultureInfo.InvariantCulture);
|
|
|
|
private static double LogUniform(Random random, double min, double max) =>
|
|
Math.Exp(Math.Log(min) + (random.NextDouble() * (Math.Log(max) - Math.Log(min))));
|
|
|
|
private static string Capitalize(string text) => string.IsNullOrEmpty(text) ? text : char.ToUpperInvariant(text[0]) + text[1..];
|
|
}
|
|
|
|
/// <summary>Proportions of the sample pictures.</summary>
|
|
public enum PictureShape
|
|
{
|
|
Square,
|
|
Portrait,
|
|
Tall,
|
|
Landscape,
|
|
Wide,
|
|
Story,
|
|
}
|
|
|
|
/// <summary>A sample picture on disk.</summary>
|
|
public sealed record DemoPicture(DemoSubject Subject, PictureShape Shape, string Path, string Sha256, int Width, int Height, long Bytes, ulong? PerceptualHash = null);
|
|
|
|
/// <summary>The shared sample pictures of the demo, with their thumbnails.</summary>
|
|
public sealed class DemoPictures
|
|
{
|
|
private readonly Dictionary<(DemoSubject, PictureShape), List<DemoPicture>> _byKind;
|
|
|
|
private DemoPictures(IReadOnlyList<DemoPicture> all)
|
|
{
|
|
All = all;
|
|
Files = all.GroupBy(p => p.Sha256, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Path, StringComparer.Ordinal);
|
|
_byKind = all.GroupBy(p => (p.Subject, p.Shape)).ToDictionary(g => g.Key, g => g.ToList());
|
|
}
|
|
|
|
public IReadOnlyList<DemoPicture> All { get; }
|
|
|
|
public IReadOnlyDictionary<string, string> Files { get; }
|
|
|
|
public static (int Width, int Height) Size(PictureShape shape) => shape switch
|
|
{
|
|
PictureShape.Square => (1080, 1080),
|
|
PictureShape.Portrait => (1080, 1350),
|
|
PictureShape.Tall => (1080, 1440),
|
|
PictureShape.Landscape => (1080, 720),
|
|
PictureShape.Wide => (1080, 608),
|
|
_ => (720, 1280),
|
|
};
|
|
|
|
/// <summary>Draws the pictures (two variants per subject and shape) and their thumbnails, in parallel.</summary>
|
|
public static DemoPictures Create(string folder, ThumbnailStore thumbnails)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(thumbnails);
|
|
Directory.CreateDirectory(folder);
|
|
var jobs = new List<(DemoSubject Subject, PictureShape Shape, int Seed)>();
|
|
foreach (var subject in DemoImages.Subjects)
|
|
{
|
|
foreach (var shape in Enum.GetValues<PictureShape>())
|
|
{
|
|
var variants = shape is PictureShape.Square or PictureShape.Portrait or PictureShape.Story ? 2 : 1;
|
|
for (var v = 0; v < variants; v++)
|
|
{
|
|
jobs.Add((subject, shape, v + 1));
|
|
}
|
|
}
|
|
}
|
|
|
|
var results = new DemoPicture[jobs.Count];
|
|
Parallel.For(0, jobs.Count, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, Math.Min(4, Environment.ProcessorCount)) }, i =>
|
|
{
|
|
var (subject, shape, seed) = jobs[i];
|
|
var (width, height) = Size(shape);
|
|
var bytes = DemoImages.Render(subject, seed + (i * 31), width, height);
|
|
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
|
var path = System.IO.Path.Combine(folder, sha + ".jpg");
|
|
File.WriteAllBytes(path, bytes);
|
|
using (var stream = new MemoryStream(bytes))
|
|
{
|
|
thumbnails.Create(sha, stream);
|
|
}
|
|
|
|
ulong? hash;
|
|
using (var stream = new MemoryStream(bytes))
|
|
{
|
|
hash = Febe.Core.Library.PerceptualHash.Compute(stream);
|
|
}
|
|
|
|
results[i] = new DemoPicture(subject, shape, path, sha, width, height, bytes.Length, hash);
|
|
});
|
|
return new DemoPictures(results);
|
|
}
|
|
|
|
public DemoPicture Pick(DemoSubject subject, PictureShape shape, Random random)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(random);
|
|
if (_byKind.TryGetValue((subject, shape), out var list))
|
|
{
|
|
return list[random.Next(list.Count)];
|
|
}
|
|
|
|
return All[random.Next(All.Count)];
|
|
}
|
|
}
|