Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account
Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
76 files changed
+12503
-17
No files matched your search
@@ -0,0 +1,122 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Web.Library;
|
||||
|
||||
/// <summary>One line of the exported list: an entry with its account and files.</summary>
|
||||
public sealed record CsvEntry(Account Account, Entry Entry, IReadOnlyList<Media> Media, IReadOnlyList<string> Highlights, string? Address);
|
||||
|
||||
/// <summary>
|
||||
/// «Esporta l'elenco» (spec §4.8): CSV with <c>;</c> as separator and UTF-8 with BOM, so that it opens well in Excel
|
||||
/// with Italian settings. Fields with a separator, quotes, line breaks or edge spaces are quoted with doubled quotes;
|
||||
/// fields that Excel would read as a formula (starting with = + - @ or a tab) get a leading apostrophe.
|
||||
/// Dates and times are local (Alberto's zone), as in the file names.
|
||||
/// </summary>
|
||||
public static class CsvExport
|
||||
{
|
||||
public const char Separator = ';';
|
||||
|
||||
public static readonly IReadOnlyList<string> Header =
|
||||
[
|
||||
"Account", "Tipo", "Data", "Ora", "Codice", "Identificativo", "Didascalia", "Autore", "Raccolte",
|
||||
"Provenienza", "Stato", "File", "Nomi dei file", "Indirizzo",
|
||||
];
|
||||
|
||||
/// <summary>Writes the BOM, the header and one line per entry.</summary>
|
||||
public static async Task WriteAsync(Stream output, IAsyncEnumerable<CsvEntry> entries, TimeZoneInfo zone, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var writer = new StreamWriter(output, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), 16 * 1024, leaveOpen: true) { NewLine = "\r\n" };
|
||||
await using (writer.ConfigureAwait(false))
|
||||
{
|
||||
await writer.WriteLineAsync(Line(Header)).ConfigureAwait(false);
|
||||
await foreach (var entry in entries.WithCancellation(ct).ConfigureAwait(false))
|
||||
{
|
||||
await writer.WriteLineAsync(Line(Fields(entry, zone))).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await writer.FlushAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The fields of one entry, in the order of <see cref="Header"/>.</summary>
|
||||
public static IReadOnlyList<string?> Fields(CsvEntry row, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
var local = LocalCalendar.ToLocal(row.Entry.PublishedAt, zone);
|
||||
var present = row.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
|
||||
return
|
||||
[
|
||||
row.Account.Username,
|
||||
KindName(row.Entry.Kind),
|
||||
local.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
||||
local.ToString("HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
row.Entry.Code,
|
||||
row.Entry.InstagramId,
|
||||
row.Entry.Caption,
|
||||
row.Entry.AuthorUsername,
|
||||
string.Join(", ", row.Highlights),
|
||||
row.Entry.Provenance == Provenance.Imported ? "Importato" : "Scaricato da Instagram",
|
||||
StateName(row.Entry.State),
|
||||
row.Media.Count.ToString(CultureInfo.InvariantCulture),
|
||||
string.Join(" | ", present.Select(m => m.RelativePath)),
|
||||
row.Address,
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>One CSV line (without the line break).</summary>
|
||||
public static string Line(IEnumerable<string?> fields)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fields);
|
||||
return string.Join(Separator, fields.Select(Field));
|
||||
}
|
||||
|
||||
/// <summary>Escapes one field.</summary>
|
||||
public static string Field(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var text = value;
|
||||
if (text[0] is '=' or '+' or '-' or '@' or '\t' or '\r')
|
||||
{
|
||||
text = "'" + text;
|
||||
}
|
||||
|
||||
var quote = text.Contains(Separator, StringComparison.Ordinal)
|
||||
|| text.Contains('"', StringComparison.Ordinal)
|
||||
|| text.Contains('\n', StringComparison.Ordinal)
|
||||
|| text.Contains('\r', StringComparison.Ordinal)
|
||||
|| text[0] == ' '
|
||||
|| text[^1] == ' '
|
||||
|| text[0] == '\'';
|
||||
return quote ? "\"" + text.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : text;
|
||||
}
|
||||
|
||||
public static string KindName(EntryKind kind) => kind switch
|
||||
{
|
||||
EntryKind.Post => "Post",
|
||||
EntryKind.Story => "Storia",
|
||||
EntryKind.Highlight => "In evidenza",
|
||||
EntryKind.Tagged => "Taggato",
|
||||
EntryKind.ProfilePicture => "Foto del profilo",
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
public static string StateName(EntryState state) => state switch
|
||||
{
|
||||
EntryState.ToDownload => "Da scaricare",
|
||||
EntryState.Downloaded => "Scaricato",
|
||||
EntryState.Partial => "Parziale",
|
||||
EntryState.Failed => "Fallito",
|
||||
EntryState.Skipped => "Saltato",
|
||||
EntryState.Imported => "Importato",
|
||||
EntryState.Deleted => "Eliminato",
|
||||
_ => state.ToString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Web.Library;
|
||||
|
||||
/// <summary>
|
||||
/// The library as the web layer uses it: Data folder, library folder, thumbnails, journal and deletion. The library
|
||||
/// folder can change at run time (Impostazioni, Generali): <see cref="UseLibraryRoot"/> swaps the layout.
|
||||
/// </summary>
|
||||
public sealed class FebeLibrary
|
||||
{
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly IClock _clock;
|
||||
private readonly PerceptualHashIndex? _index;
|
||||
private volatile LibraryLayout _layout;
|
||||
|
||||
public FebeLibrary(IFebeStorage storage, DataFolderLayout data, LibraryLayout layout, IClock clock, PerceptualHashIndex? index = null)
|
||||
{
|
||||
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
||||
Data = data ?? throw new ArgumentNullException(nameof(data));
|
||||
_layout = layout ?? throw new ArgumentNullException(nameof(layout));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_index = index;
|
||||
Thumbnails = new ThumbnailStore(data.Thumbnails);
|
||||
Journal = new AccountJournal(clock);
|
||||
}
|
||||
|
||||
public DataFolderLayout Data { get; }
|
||||
|
||||
public LibraryLayout Layout => _layout;
|
||||
|
||||
public ThumbnailStore Thumbnails { get; }
|
||||
|
||||
public AccountJournal Journal { get; }
|
||||
|
||||
/// <summary>«Elimina dalla libreria», on Alberto's explicit choice only (rule 12).</summary>
|
||||
public LibraryDeletion Deletion => new(_storage, _layout, Journal, _clock, Thumbnails, _index);
|
||||
|
||||
/// <summary>The library folder changed: new files go there; existing accounts keep their stored folders.</summary>
|
||||
public void UseLibraryRoot(string root) => _layout = new LibraryLayout(root, _layout.MaxPathLength);
|
||||
}
|
||||
|
||||
/// <summary>Where the file of a media record is on disk. The demo maps its shared sample files; the real one uses the layout.</summary>
|
||||
public interface IMediaFileResolver
|
||||
{
|
||||
/// <summary>Full path of an existing file, or null when the file is not on disk.</summary>
|
||||
string? Resolve(Account account, Media media);
|
||||
}
|
||||
|
||||
/// <summary>Files under the account folders of the library (spec §4.7).</summary>
|
||||
public sealed class LibraryFileResolver(FebeLibrary library) : IMediaFileResolver
|
||||
{
|
||||
public string? Resolve(Account account, Media media)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(media);
|
||||
if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var path = library.Layout.FullPath(account, media.RelativePath);
|
||||
return File.Exists(path) ? path : null;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Something changed in the library: the open pages reload what they show.</summary>
|
||||
/// <param name="At">When.</param>
|
||||
/// <param name="AccountId">The account concerned, when there is only one.</param>
|
||||
/// <param name="Reason">Short machine reason: "stored", "deleted", "account", "import".</param>
|
||||
public sealed record LibraryChange(DateTimeOffset At, long? AccountId, string Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Library notifications for the server-sent events (<c>/api/eventi</c>, event <c>libreria</c>). Publishers: the web
|
||||
/// layer itself (deletions, account changes), the download queue (<see cref="Attach"/>) and the import (M7).
|
||||
/// Slow subscribers lose the oldest notifications.
|
||||
/// </summary>
|
||||
public sealed class LibraryChanges
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<Channel<LibraryChange>> _subscribers = [];
|
||||
|
||||
public void Publish(LibraryChange change)
|
||||
{
|
||||
Channel<LibraryChange>[] subscribers;
|
||||
lock (_gate)
|
||||
{
|
||||
subscribers = [.. _subscribers];
|
||||
}
|
||||
|
||||
foreach (var subscriber in subscribers)
|
||||
{
|
||||
subscriber.Writer.TryWrite(change);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Publishes a change for every file the download queue stores.</summary>
|
||||
public IDisposable Attach(DownloadQueue queue, IClock clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(queue);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
void Handler(object? sender, DownloadProgress progress)
|
||||
{
|
||||
if (progress.Step == DownloadStep.Stored)
|
||||
{
|
||||
Publish(new LibraryChange(clock.Now, progress.AccountId, "stored"));
|
||||
}
|
||||
}
|
||||
|
||||
queue.Progress += Handler;
|
||||
return new Detach(() => queue.Progress -= Handler);
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<LibraryChange> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
var channel = Channel.CreateBounded<LibraryChange>(new BoundedChannelOptions(256) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
|
||||
lock (_gate)
|
||||
{
|
||||
_subscribers.Add(channel);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
while (await channel.Reader.WaitToReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
while (channel.Reader.TryRead(out var change))
|
||||
{
|
||||
yield return change;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_subscribers.Remove(channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Detach(Action action) : IDisposable
|
||||
{
|
||||
public void Dispose() => action();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Web.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Addresses for «Apri su Instagram»: they open in Alberto's own browser (a link, or the default browser on Windows),
|
||||
/// never in Febe's and never from the server. They use the public forms anyone sees in the address bar; a story
|
||||
/// older than a day opens the profile, because the story is no longer there.
|
||||
/// </summary>
|
||||
public static class InstagramLinks
|
||||
{
|
||||
public const string Site = "https://www.instagram.com/";
|
||||
|
||||
public static string Profile(string username) => Site + Uri.EscapeDataString(username.Trim().TrimStart('@')) + "/";
|
||||
|
||||
/// <summary>The page of an entry, or the profile when the entry has no page of its own any more.</summary>
|
||||
public static string For(Account account, Entry entry, DateTimeOffset now, string? highlightInstagramId = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
switch (entry.Kind)
|
||||
{
|
||||
case EntryKind.Post or EntryKind.Tagged when !string.IsNullOrWhiteSpace(entry.Code):
|
||||
return Site + "p/" + Uri.EscapeDataString(entry.Code) + "/";
|
||||
case EntryKind.Story when !string.IsNullOrWhiteSpace(entry.InstagramId) && now - entry.PublishedAt < TimeSpan.FromHours(24):
|
||||
return Site + "stories/" + Uri.EscapeDataString(account.Username) + "/" + Uri.EscapeDataString(entry.InstagramId) + "/";
|
||||
case EntryKind.Highlight when !string.IsNullOrWhiteSpace(highlightInstagramId):
|
||||
return Site + "stories/highlights/" + Uri.EscapeDataString(highlightInstagramId) + "/";
|
||||
default:
|
||||
return Profile(account.Username);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for addresses of the site that the shell may open in the default browser.</summary>
|
||||
public static bool IsSiteAddress(Uri address) =>
|
||||
address is not null && address.Scheme == Uri.UriSchemeHttps && string.Equals(address.Host, "www.instagram.com", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Web.Library;
|
||||
|
||||
/// <summary>A user name read from a line of the «Per nome utente» text area.</summary>
|
||||
public sealed record ParsedUsername(int Line, string Username);
|
||||
|
||||
/// <summary>A line that is not a user name, with the reason in Italian.</summary>
|
||||
public sealed record UsernameProblem(int Line, string Text, string Reason);
|
||||
|
||||
/// <summary>
|
||||
/// «Per nome utente» (spec §4.2, mockup 04): one user name or profile address per line. Accepts «marta.demo»,
|
||||
/// «@marta.demo», «instagram.com/marta.demo», «https://www.instagram.com/marta.demo/?hl=it». Refuses addresses of
|
||||
/// posts, reels and other pages, and names Instagram would not accept. Names are compared and stored in lowercase.
|
||||
/// </summary>
|
||||
public static partial class UsernameParser
|
||||
{
|
||||
/// <summary>First path segments of the site that are pages, not profiles.</summary>
|
||||
public static readonly IReadOnlySet<string> ReservedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"p", "reel", "reels", "tv", "stories", "explore", "accounts", "direct", "about", "legal", "developer", "web", "challenge", "emails", "session",
|
||||
};
|
||||
|
||||
public static (IReadOnlyList<ParsedUsername> Names, IReadOnlyList<UsernameProblem> Problems) Parse(string? text)
|
||||
{
|
||||
var names = new List<ParsedUsername>();
|
||||
var problems = new List<UsernameProblem>();
|
||||
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return (names, problems);
|
||||
}
|
||||
|
||||
var lines = text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
|
||||
for (var i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var number = i + 1;
|
||||
var line = lines[i].Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.Length > 300)
|
||||
{
|
||||
problems.Add(new UsernameProblem(number, line[..60] + "…", "Riga troppo lunga per essere un nome utente."));
|
||||
continue;
|
||||
}
|
||||
|
||||
var (candidate, reason) = Extract(line);
|
||||
if (candidate is null)
|
||||
{
|
||||
problems.Add(new UsernameProblem(number, line, reason!));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seen.TryGetValue(candidate, out var first))
|
||||
{
|
||||
problems.Add(new UsernameProblem(number, line, $"Già scritto alla riga {first}."));
|
||||
continue;
|
||||
}
|
||||
|
||||
seen[candidate] = number;
|
||||
names.Add(new ParsedUsername(number, candidate));
|
||||
}
|
||||
|
||||
return (names, problems);
|
||||
}
|
||||
|
||||
/// <summary>True for a valid user name (already lowercase, without @).</summary>
|
||||
public static bool IsValid(string username) =>
|
||||
Valid().IsMatch(username) && !username.StartsWith('.') && !username.EndsWith('.') && !username.Contains("..", StringComparison.Ordinal);
|
||||
|
||||
private static (string? Username, string? Reason) Extract(string line)
|
||||
{
|
||||
var text = line;
|
||||
if (text.Contains("instagram.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!text.Contains("://", StringComparison.Ordinal))
|
||||
{
|
||||
text = "https://" + text;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri)
|
||||
|| !(uri.Host.Equals("instagram.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".instagram.com", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return (null, "Indirizzo non riconosciuto: serve quello del profilo, per esempio instagram.com/nome.utente.");
|
||||
}
|
||||
|
||||
var segments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments.Length == 0)
|
||||
{
|
||||
return (null, "L'indirizzo non contiene il nome del profilo.");
|
||||
}
|
||||
|
||||
if (ReservedPaths.Contains(segments[0]))
|
||||
{
|
||||
return (null, "È l'indirizzo di un post o di un'altra pagina, non di un profilo.");
|
||||
}
|
||||
|
||||
text = Uri.UnescapeDataString(segments[0]);
|
||||
}
|
||||
|
||||
text = text.Trim().TrimStart('@').ToLowerInvariant();
|
||||
if (text.Contains(' ', StringComparison.Ordinal))
|
||||
{
|
||||
return (null, "Un nome utente non contiene spazi: uno per riga.");
|
||||
}
|
||||
|
||||
return IsValid(text)
|
||||
? (text, null)
|
||||
: (null, "Non è un nome utente valido: lettere, numeri, punti e trattini bassi, al massimo 30.");
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[a-z0-9._]{1,30}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Valid();
|
||||
}
|
||||
Reference in new issue
Block a user