using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Library; namespace Febe.Web.Api; /// The settings of an account (spec §4.4, mockup 05) between the domain and the form of the page. public static class AccountSettingsMapper { public const double MinCustomPostHours = 1; public const double MaxCustomPostHours = 48; public const double MinCustomStoryHours = 1; public const double MaxCustomStoryHours = 24; /// Largest «Storico, massimo al giorno» the form accepts: twice the «Rapido» value (spec §7.5). public static int MaxBackfillPerDay => CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2; /// The form of an account. /// The stored account. /// /// Alberto's zone: «Da una data» is stored as the first instant of a local day (), /// so it is shown as that local day, which turns back into the same instant. /// public static AccountSettingsDto ToDto(Account account, TimeZoneInfo zone) { ArgumentNullException.ThrowIfNull(account); ArgumentNullException.ThrowIfNull(zone); var reference = account with { IsFollowed = false, Frequency = account.Frequency == Frequency.Custom ? Frequency.Custom : account.Frequency }; return new AccountSettingsDto( account.KeepUpdated, ApiMapping.Frequency(account.Frequency), Math.Round((account.CustomPostInterval ?? CheckPolicy.ProfileCheckInterval(reference)).TotalHours, 2), Math.Round((account.CustomStoryInterval ?? CheckPolicy.StoryMaxInterval(reference)).TotalHours, 2), ApiMapping.Types(account.ContentTypes), ApiMapping.Depth(account.Limits.Depth), account.Limits.LastPosts, account.Limits.FromDate is { } from ? ApiMapping.Day(LocalCalendar.Today(from, zone)) : null, account.Limits.BackfillPostsPerDay, account.Limits.MaxVideoBytes is { } bytes ? Math.Round(bytes / 1024d / 1024d, 1) : null, account.Limits.StoryVideos, account.Folder, account.DownloadOrder is { } own ? DownloadOrder.Parse(own).ToNames() : null); } /// /// Applies the form to an account, with Italian errors for values out of range. «Tieni aggiornato» moves the state: /// off on an up-to-date account pauses it (the single download is done), on reactivates a paused one. /// /// The stored account. /// The form. /// Alberto's zone (dates of «Da una data»). /// Now (state change time). /// The folder value already resolved by the caller (null: default). public static Account Apply(Account account, AccountSettingsDto dto, TimeZoneInfo zone, DateTimeOffset now, string? folder) { ArgumentNullException.ThrowIfNull(account); ArgumentNullException.ThrowIfNull(dto); ArgumentNullException.ThrowIfNull(zone); var frequency = ApiMapping.ParseFrequency(dto.Frequency) ?? throw new BadRequestException("Frequenza sconosciuta."); TimeSpan? customPost = account.CustomPostInterval; TimeSpan? customStory = account.CustomStoryInterval; if (frequency == Frequency.Custom) { if (dto.CustomPostHours is not { } postHours || double.IsNaN(postHours) || postHours < MinCustomPostHours || postHours > MaxCustomPostHours) { throw new BadRequestException($"Su misura: i post si controllano fra ogni {Number(MinCustomPostHours)} e ogni {Number(MaxCustomPostHours)} ore."); } if (dto.CustomStoryHours is not { } storyHours || double.IsNaN(storyHours) || storyHours < MinCustomStoryHours || storyHours > MaxCustomStoryHours) { throw new BadRequestException($"Su misura: fra due controlli delle storie passano da {Number(MinCustomStoryHours)} a {Number(MaxCustomStoryHours)} ore."); } customPost = TimeSpan.FromMinutes(Math.Round(postHours * 60)); customStory = TimeSpan.FromMinutes(Math.Round(storyHours * 60)); } var types = ApiMapping.Types(dto.Types ?? throw new BadRequestException("Manca «Cosa scaricare».")); var depth = ApiMapping.ParseDepth(dto.Depth) ?? throw new BadRequestException("«Quanto indietro nel tempo» non valido."); int? lastPosts = null; DateTimeOffset? fromDate = null; if (depth == HistoryDepth.LastPosts) { if (dto.LastPosts is not { } n || n < 1 || n > 1_000_000) { throw new BadRequestException("Indica quanti post tenere: almeno 1."); } lastPosts = n; } else if (depth == HistoryDepth.FromDate) { var day = ApiMapping.ParseDay(dto.FromDate) ?? throw new BadRequestException("Indica la data da cui partire."); if (day > LocalCalendar.Today(now, zone)) { throw new BadRequestException("La data da cui partire non può essere nel futuro."); } fromDate = LocalCalendar.StartOfDay(day, zone); } if (dto.BackfillPerDay < 1 || dto.BackfillPerDay > MaxBackfillPerDay) { throw new BadRequestException($"Storico, massimo al giorno: fra 1 e {ItalianText.Number(MaxBackfillPerDay)} post."); } long? maxVideo = null; if (dto.MaxVideoMb is { } mb) { if (double.IsNaN(mb) || mb < 1 || mb > 100_000) { throw new BadRequestException("Salta i video oltre: un numero di MB da 1 in su, oppure vuoto per nessun limite."); } maxVideo = (long)Math.Round(mb * 1024 * 1024); } var state = account.State; var changedAt = account.StateChangedAt; if (account.KeepUpdated && !dto.KeepUpdated && state == AccountState.UpToDate) { state = AccountState.Paused; changedAt = now; } else if (!account.KeepUpdated && dto.KeepUpdated && state == AccountState.Paused) { state = ReactivatedState(account, depth); changedAt = now; } return account with { KeepUpdated = dto.KeepUpdated, Frequency = frequency, CustomPostInterval = customPost, CustomStoryInterval = customStory, ContentTypes = types, Limits = account.Limits with { Depth = depth, LastPosts = lastPosts, FromDate = fromDate, BackfillPostsPerDay = dto.BackfillPerDay, MaxVideoBytes = maxVideo, StoryVideos = dto.StoryVideos, }, Folder = folder, DownloadOrder = dto.DownloadOrder is { Count: > 0 } names ? DownloadOrder.From(names).ToString() : null, State = state, StateChangedAt = changedAt, }; } /// State of a paused account that comes back: backfilling while its history is not complete. public static AccountState ReactivatedState(Account account, HistoryDepth? depth = null) { ArgumentNullException.ThrowIfNull(account); var d = depth ?? account.Limits.Depth; return account.BackfillCompletedAt is null && d != HistoryDepth.FromDate && CheckPolicy.WantsProfileChecks(account) ? AccountState.Backfilling : AccountState.UpToDate; } /// «Nuovi post ogni 3 ore circa, storie almeno ogni 6 ore» beside the frequency buttons. public static string FrequencyHint(Account account) { ArgumentNullException.ThrowIfNull(account); var parts = new List(); if (CheckPolicy.WantsProfileChecks(account)) { parts.Add(account.IsFollowed ? "nuovi post dal giro dei profili che segui, profilo riaperto " + ItalianText.Every(CheckPolicy.ProfileCheckInterval(account)) : "nuovi post " + ItalianText.Every(CheckPolicy.ProfileCheckInterval(account)) + " circa"); } if (CheckPolicy.WantsStories(account)) { parts.Add("storie almeno " + ItalianText.Every(CheckPolicy.StoryMaxInterval(account))); } return parts.Count == 0 ? "Niente da controllare con queste scelte." : ItalianText.Capitalize(string.Join(", ", parts)); } /// The note under the panel: what being followed or not means for this account. public static string? Note(Account account) { ArgumentNullException.ThrowIfNull(account); if (account.State == AccountState.ArchiveOnly || account.IsMine) { return null; } if (!account.IsFollowed && !account.IsPrivate) { return "È un profilo pubblico che non segui: per vedere le novità Febe deve aprire la sua pagina. Se diventa privato, Febe si ferma e ti avvisa."; } if (account.IsFollowed) { return "Lo segui: le novità arrivano dal giro dei profili che segui, senza aprire ogni volta la sua pagina."; } return null; } private static string Number(double value) => ItalianText.Decimal(value, 1); }