Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
74 files changed
+12689
-13
No files matched your search
@@ -0,0 +1,323 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>
|
||||
/// The JSON the pages fetch, in the site's own synthetic format (LEGGIMI.md). It is what the response tap captures
|
||||
/// and what the readers of <c>lettori.prova.json</c> read. Keys are Italian and the shape is ours: it does not
|
||||
/// imitate Instagram.
|
||||
/// </summary>
|
||||
public sealed class DataApi(World world, CdnSigner signer, SiteControl control, Func<string> cdnBase, TimeProvider time)
|
||||
{
|
||||
public const int FeedPageSize = 6;
|
||||
public const int GridPageSize = 12;
|
||||
public const int FollowingPageSize = 10;
|
||||
|
||||
private DateTimeOffset Now => time.GetUtcNow();
|
||||
|
||||
/// <summary>Home: the connected account, the stories bar and the first page of the feed.</summary>
|
||||
public JsonObject Home()
|
||||
{
|
||||
var feed = world.Feed();
|
||||
return new JsonObject
|
||||
{
|
||||
["io"] = ProfileLite(world.Viewer),
|
||||
["barra"] = new JsonArray([.. world.StoryBar(Now).Select(a => (JsonNode)Profile(a))]),
|
||||
["contenuti"] = new JsonArray([.. feed.Take(FeedPageSize).Select(p => (JsonNode)Post(p, inFeed: true))]),
|
||||
["pagina"] = Page(feed.Count, 0, FeedPageSize),
|
||||
};
|
||||
}
|
||||
|
||||
public JsonObject HomeMore(string? after)
|
||||
{
|
||||
var feed = world.Feed();
|
||||
var offset = ParseCursor(after);
|
||||
return new JsonObject
|
||||
{
|
||||
["contenuti"] = new JsonArray([.. feed.Skip(offset).Take(FeedPageSize).Select(p => (JsonNode)Post(p, inFeed: true))]),
|
||||
["pagina"] = Page(feed.Count, offset, FeedPageSize),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A profile page: profile, highlights (first page only) and a page of the tab. Null when it does not exist.</summary>
|
||||
public JsonObject? Profile(string username, ProfileTab tab, string? after)
|
||||
{
|
||||
var account = world.FindByUsername(username);
|
||||
if (account is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = new JsonObject { ["profilo"] = Profile(account) };
|
||||
if (account.IsPrivate && !account.FollowedByViewer)
|
||||
{
|
||||
result["contenuti"] = new JsonArray();
|
||||
result["pagina"] = new JsonObject { ["altro"] = false, ["dopo"] = null };
|
||||
return result;
|
||||
}
|
||||
|
||||
var offset = ParseCursor(after);
|
||||
if (tab == ProfileTab.Posts && offset == 0)
|
||||
{
|
||||
result["raccolte"] = new JsonArray([.. account.Highlights.Select(h => (JsonNode)Highlight(h, withItems: false))]);
|
||||
}
|
||||
|
||||
var grid = world.Grid(account, tab);
|
||||
result["contenuti"] = new JsonArray([.. grid.Skip(offset).Take(GridPageSize).Select(p => (JsonNode)Post(p, inFeed: false))]);
|
||||
result["pagina"] = Page(grid.Count, offset, GridPageSize);
|
||||
return result;
|
||||
}
|
||||
|
||||
public JsonObject? ProfileMore(string username, ProfileTab tab, string? after)
|
||||
{
|
||||
var account = world.FindByUsername(username);
|
||||
if (account is null || (account.IsPrivate && !account.FollowedByViewer))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var grid = world.Grid(account, tab);
|
||||
var offset = ParseCursor(after);
|
||||
return new JsonObject
|
||||
{
|
||||
["contenuti"] = new JsonArray([.. grid.Skip(offset).Take(GridPageSize).Select(p => (JsonNode)Post(p, inFeed: false))]),
|
||||
["pagina"] = Page(grid.Count, offset, GridPageSize),
|
||||
};
|
||||
}
|
||||
|
||||
public JsonObject? SinglePost(string code)
|
||||
{
|
||||
var post = world.FindPost(code);
|
||||
if (post is null || (post.Owner.IsPrivate && !post.Owner.FollowedByViewer))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new JsonObject { ["contenuto"] = Post(post, inFeed: false) };
|
||||
}
|
||||
|
||||
/// <summary>All the active stories of an account (the page receives the whole list in advance), and who comes next.</summary>
|
||||
public JsonObject? Stories(string username)
|
||||
{
|
||||
var account = world.FindByUsername(username);
|
||||
if (account is null || (account.IsPrivate && !account.FollowedByViewer))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bar = world.StoryBar(Now);
|
||||
var index = bar.ToList().IndexOf(account);
|
||||
var next = index >= 0 && index + 1 < bar.Count ? bar[index + 1].Username : null;
|
||||
return new JsonObject
|
||||
{
|
||||
["autore"] = ProfileLite(account),
|
||||
["storie"] = new JsonArray([.. account.Stories.Where(s => s.ExpiresAt > Now).Select(s => (JsonNode)Story(s))]),
|
||||
["successivo"] = next,
|
||||
};
|
||||
}
|
||||
|
||||
public JsonObject? HighlightItems(string id)
|
||||
{
|
||||
var highlight = world.FindHighlight(id);
|
||||
if (highlight is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var siblings = highlight.Owner.Highlights;
|
||||
var index = siblings.IndexOf(highlight);
|
||||
return new JsonObject
|
||||
{
|
||||
["raccolta"] = Highlight(highlight, withItems: true),
|
||||
["successiva"] = index + 1 < siblings.Count ? siblings[index + 1].Id : null,
|
||||
};
|
||||
}
|
||||
|
||||
public JsonObject Following(string? after)
|
||||
{
|
||||
var list = world.Following;
|
||||
var offset = ParseCursor(after);
|
||||
return new JsonObject
|
||||
{
|
||||
["seguiti"] = new JsonArray([.. list.Skip(offset).Take(FollowingPageSize).Select(a => (JsonNode)Profile(a))]),
|
||||
["pagina"] = Page(list.Count, offset, FollowingPageSize),
|
||||
};
|
||||
}
|
||||
|
||||
public static JsonObject EmptyPage() => new()
|
||||
{
|
||||
["contenuti"] = new JsonArray(),
|
||||
["pagina"] = new JsonObject { ["altro"] = false, ["dopo"] = null },
|
||||
};
|
||||
|
||||
/// <summary>A response in a shape the readers do not know: what a site that changed its format would send.</summary>
|
||||
public static JsonObject UnknownShape() => new()
|
||||
{
|
||||
["risposta"] = new JsonObject
|
||||
{
|
||||
["voci"] = new JsonArray(
|
||||
new JsonObject { ["chiave"] = "A1", ["valore"] = "un formato nuovo", ["dettagli"] = new JsonObject { ["x"] = 1 } },
|
||||
new JsonObject { ["chiave"] = "B2", ["valore"] = "che nessun lettore conosce", ["dettagli"] = new JsonObject { ["x"] = 2 } }),
|
||||
},
|
||||
["versione"] = 2,
|
||||
};
|
||||
|
||||
public static int ParseCursor(string? cursor) =>
|
||||
cursor is { Length: > 1 } && cursor[0] == 'c' && int.TryParse(cursor.AsSpan(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) && n >= 0 ? n : 0;
|
||||
|
||||
public static string Cursor(int offset) => "c" + offset.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static JsonObject Page(int total, int offset, int size)
|
||||
{
|
||||
var more = offset + size < total;
|
||||
return new JsonObject { ["altro"] = more, ["dopo"] = more ? Cursor(offset + size) : null };
|
||||
}
|
||||
|
||||
private JsonObject ProfileLite(SiteAccount account) => new()
|
||||
{
|
||||
["numero"] = account.Id,
|
||||
["nome"] = account.Username,
|
||||
};
|
||||
|
||||
private JsonObject Profile(SiteAccount account)
|
||||
{
|
||||
var node = new JsonObject
|
||||
{
|
||||
["numero"] = account.Id,
|
||||
["nome"] = account.Username,
|
||||
["nome_visibile"] = account.DisplayName,
|
||||
["riservato"] = account.IsPrivate,
|
||||
["seguito"] = account.FollowedByViewer,
|
||||
["pubblicazioni"] = account.Posts.Count,
|
||||
["ritratto"] = new JsonArray(
|
||||
Version(account.PictureKey, 160, 160, video: false),
|
||||
Version(account.PictureKey, 320, 320, video: false)),
|
||||
};
|
||||
if (account.LatestStoryAt(Now) is { } latest && (!account.IsPrivate || account.FollowedByViewer))
|
||||
{
|
||||
node["ultima_storia"] = Date(latest);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private JsonObject Post(SitePost post, bool inFeed)
|
||||
{
|
||||
var node = new JsonObject
|
||||
{
|
||||
["numero"] = post.Id,
|
||||
["sigla"] = post.Code,
|
||||
["pubblicato"] = Date(post.PublishedAt),
|
||||
["testo"] = post.Caption,
|
||||
["fissato"] = post.Pinned && !inFeed,
|
||||
["autore"] = ProfileLite(post.Owner),
|
||||
};
|
||||
if (post.Files.Count == 1)
|
||||
{
|
||||
AddFile(node, post.Files[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// The feed carries only the first file of a series, with the declared count: the post is incomplete there
|
||||
// and «Post singolo» completes it. Profile grids and post pages carry the whole series.
|
||||
var parts = inFeed ? post.Files.Take(1) : post.Files;
|
||||
node["parti"] = new JsonArray([.. parts.Select(f =>
|
||||
{
|
||||
var part = new JsonObject { ["numero"] = f.Id };
|
||||
AddFile(part, f);
|
||||
return (JsonNode)part;
|
||||
})]);
|
||||
node["parti_totali"] = post.Files.Count;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private JsonObject Story(SiteStory story)
|
||||
{
|
||||
var node = new JsonObject
|
||||
{
|
||||
["numero"] = story.Id,
|
||||
["pubblicato"] = Date(story.PublishedAt),
|
||||
["scade"] = Date(story.ExpiresAt),
|
||||
["autore"] = ProfileLite(story.Owner),
|
||||
};
|
||||
AddFile(node, story.File);
|
||||
return node;
|
||||
}
|
||||
|
||||
private JsonObject Highlight(SiteHighlight highlight, bool withItems)
|
||||
{
|
||||
var node = new JsonObject
|
||||
{
|
||||
["numero"] = highlight.Id,
|
||||
["titolo"] = highlight.Title,
|
||||
["autore"] = ProfileLite(highlight.Owner),
|
||||
["copertina"] = highlight.Items.Count > 0 ? Version(highlight.Items[0].File.MediaKey, 160, 284, video: false) : null,
|
||||
};
|
||||
if (withItems)
|
||||
{
|
||||
node["contenuti"] = new JsonArray([.. highlight.Items.Select(i =>
|
||||
{
|
||||
var item = new JsonObject
|
||||
{
|
||||
["numero"] = i.Id,
|
||||
["pubblicato"] = Date(i.PublishedAt),
|
||||
["autore"] = ProfileLite(i.Owner),
|
||||
};
|
||||
AddFile(item, i.File);
|
||||
return (JsonNode)item;
|
||||
})]);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The versions of a file. Images: a medium, the largest and a small one (in this order: the largest is not the
|
||||
/// first). Videos: two renditions with audio and a larger one without audio (the reader must not pick it), plus
|
||||
/// cover images.
|
||||
/// </summary>
|
||||
private void AddFile(JsonObject node, SiteFile file)
|
||||
{
|
||||
if (file.IsVideo)
|
||||
{
|
||||
node["filmati"] = new JsonArray(
|
||||
Version(file.MediaKey, file.Width / 2, file.Height / 2, video: true, audio: true),
|
||||
Version(file.MediaKey, file.Width, file.Height, video: true, audio: true),
|
||||
Version(file.MediaKey, file.Width * 3 / 2, file.Height * 3 / 2, video: true, audio: false));
|
||||
node["foto"] = new JsonArray(
|
||||
Version(file.MediaKey, file.Width / 2, file.Height / 2, video: false),
|
||||
Version(file.MediaKey, file.Width, file.Height, video: false));
|
||||
node["durata"] = file.DurationSeconds;
|
||||
}
|
||||
else
|
||||
{
|
||||
node["foto"] = new JsonArray(
|
||||
Version(file.MediaKey, file.Width / 2, file.Height / 2, video: false),
|
||||
Version(file.MediaKey, file.Width, file.Height, video: false),
|
||||
Version(file.MediaKey, file.Width / 4, file.Height / 4, video: false));
|
||||
}
|
||||
}
|
||||
|
||||
private JsonObject Version(string key, int width, int height, bool video, bool audio = true)
|
||||
{
|
||||
var size = $"{width.ToString(CultureInfo.InvariantCulture)}x{height.ToString(CultureInfo.InvariantCulture)}";
|
||||
var path = video ? $"/m/{key}/{size}{(audio ? string.Empty : "-muto")}.mp4" : $"/m/{key}/{size}.jpg";
|
||||
var node = new JsonObject
|
||||
{
|
||||
["indirizzo"] = cdnBase() + signer.Sign(path, Now + control.AddressLifetime),
|
||||
["larghezza"] = width,
|
||||
["altezza"] = height,
|
||||
};
|
||||
if (video)
|
||||
{
|
||||
node["audio"] = audio;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static string Date(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
|
||||
}
|
||||
@@ -1,10 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<!-- Sito locale per le prove senza Instagram (§14.2): pagine spoglie, nessun marchio, nessuna pagina di accesso. -->
|
||||
<!-- Sito locale per le prove senza Instagram (§14.2): pagine spoglie, nessun marchio, nessuna pagina di accesso.
|
||||
Dati sintetici generati da un seme, in un formato JSON nostro (LEGGIMI.md); immagini generate con SkiaSharp. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AssemblyName>febe-sito-di-prova</AssemblyName>
|
||||
<RootNamespace>Febe.SitoDiProva</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SkiaSharp" />
|
||||
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Due filmati minuscoli generati una volta con ffmpeg (con e senza audio): ogni file servito è reso unico
|
||||
aggiungendo in coda un riquadro MP4 «free», che i lettori ignorano. -->
|
||||
<EmbeddedResource Include="Risorse\*.mp4" LogicalName="Febe.SitoDiProva.Risorse.%(Filename)%(Extension)" />
|
||||
<EmbeddedResource Include="Risorse\*.js" LogicalName="Febe.SitoDiProva.Risorse.%(Filename)%(Extension)" />
|
||||
<EmbeddedResource Include="Risorse\*.css" LogicalName="Febe.SitoDiProva.Risorse.%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Febe.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
# Sito di prova di Febe
|
||||
|
||||
Sito locale per far girare ricette, cattura, lettori, scaricamenti e motore con un browser vero **senza toccare
|
||||
Instagram** (specifica §14.2). Pagine spoglie, nessun marchio né grafica di Instagram, **nessuna pagina di accesso**:
|
||||
non deve somigliargli, deve solo comportarsi come un sito che carica i dati in JSON mentre si scorre.
|
||||
|
||||
## Avvio
|
||||
|
||||
```sh
|
||||
dotnet run --project tools/Febe.SitoDiProva -- [--porta 8481] [--porta-cdn 8482] [--indirizzo-cdn 127.0.0.2] [--seme 13]
|
||||
```
|
||||
|
||||
- Il sito ascolta su `127.0.0.1:<porta>`; il «CDN» che serve foto e video su un **secondo indirizzo**
|
||||
(`127.0.0.2:<porta-cdn>`, oppure `127.0.0.1` su un'altra porta dove `127.0.0.2` non si può usare), così i cookie
|
||||
del sito non gli arrivano.
|
||||
- I dati sono **sintetici** e si generano da un seme: stesso seme, stessi account, post, codici e didascalie. Le date
|
||||
sono relative al momento dell'avvio (le storie sono attive per 24 ore da lì).
|
||||
- Le prove automatiche lo avviano dentro il processo con `TestSite.StartAsync(...)` (porte libere scelte da sole).
|
||||
- Campioni grezzi per le prove dei lettori: `dotnet run --project tools/Febe.SitoDiProva -- campioni --cartella <fuori dal repository>`
|
||||
(poi `febe-sonda ripulisci`, vedi `tests/Febe.Tests/campioni/prova/LEGGIMI.md`).
|
||||
|
||||
## Il mondo
|
||||
|
||||
| Account | Che cos'è |
|
||||
|---|---|
|
||||
| `alberto.prova` | l'account collegato («Tu»); da lui si apre l'elenco dei seguiti |
|
||||
| `marta.prova` | pubblico, seguito: 18 post (foto, serie di tre file, video = reel), 2 post fissati, 4 storie (una è un video), raccolte «Estate» e «Viaggi»; compare nei taggati di Luca e di Paolo |
|
||||
| `luca.prova` | pubblico, seguito: 40 post (storico su più pagine), 2 storie, raccolta «Montagna» |
|
||||
| `giulia.prova` | privato, seguito: 6 post, 5 storie |
|
||||
| `nadia.prova` | pubblico, seguito: 3 post, 3 storie |
|
||||
| `paolo.prova` | pubblico, **non** seguito: 8 post, 1 storia |
|
||||
| `riservato.prova` | privato, **non** seguito: non si tocca |
|
||||
| `amico01.prova` … `amico24.prova` | seguiti, uno o due post ciascuno (l'elenco dei seguiti ha 28 profili) |
|
||||
| qualunque altro nome | non esiste: la pagina risponde 404 con il titolo «Profilo non trovato» |
|
||||
|
||||
La barra delle storie elenca i seguiti con storie attive, dalla più recente: Marta, Nadia, Luca, Giulia. Una delle
|
||||
storie attive di Marta è anche nella raccolta «Estate», con lo **stesso identificativo** (ipotesi H9).
|
||||
|
||||
## Pagine
|
||||
|
||||
| Indirizzo | Che cosa fa |
|
||||
|---|---|
|
||||
| `/` | pagina iniziale: barra delle storie (collegamenti «Storie di …») e post recenti dei seguiti; scorrendo carica altre pagine |
|
||||
| `/profilo/{nome}/` | profilo: foto (con «Apri le storie di …» se ci sono storie), raccolte («Raccolta …»), schede `Post`, `Reel`, `Taggati` (ruolo `tab`), griglia che carica altre pagine scorrendo; `?dopo={cursore}` riparte da un punto della griglia |
|
||||
| `/profilo/{nome}/reel/`, `/profilo/{nome}/taggati/` | le altre schede, con lo stesso scorrimento |
|
||||
| `/profilo/alberto.prova/seguiti/` | elenco dei profili seguiti, a pagine, scorrendo; accetta `?dopo=` |
|
||||
| `/storie/{nome}/` | visualizzatore: una storia alla volta, barra di avanzamento, zona «Storia successiva», pulsante «Chiudi». L'indirizzo diventa `/storie/{nome}/{id}/` per la storia mostrata. **Come i siti veri, dopo l'ultima storia passa da solo all'account successivo della barra**: chi lo usa deve chiuderlo prima |
|
||||
| `/evidenza/{id}/` | visualizzatore di una raccolta, come sopra (`/evidenza/{id}/{contenuto}/`); dopo l'ultimo contenuto passa alla raccolta successiva dello stesso account |
|
||||
| `/post/{codice}/` | pagina di un post, con tutti i file |
|
||||
| `/verifica` | pagina di verifica, semplice testo |
|
||||
| `/sessione-scaduta` | pagina di sessione terminata, semplice testo (non è un modulo di accesso) |
|
||||
|
||||
La mappa dei bersagli di queste pagine è `src/Febe.Core/Config/bersagli.prova.json` (copiata accanto al programma
|
||||
in `config/`), i segnali di arresto sono in `segnali.prova.json`.
|
||||
|
||||
## Formato dei dati
|
||||
|
||||
Le pagine caricano i dati con `fetch` da `/dati/...` e li leggono davvero (così il browser consegna il corpo alla
|
||||
cattura). Il formato è **nostro**, con chiavi italiane: non imita Instagram e non va usato come indizio sul formato
|
||||
di Instagram (regola 10). Il vocabolario che lo descrive ai lettori è `src/Febe.Core/Config/lettori.prova.json`.
|
||||
|
||||
| Indirizzo dei dati | Risposta |
|
||||
|---|---|
|
||||
| `/dati/inizio` | `{ io, barra: [profilo], contenuti: [contenuto], pagina }` |
|
||||
| `/dati/inizio/altri?dopo=` | `{ contenuti, pagina }` |
|
||||
| `/dati/profilo/{nome}?scheda=post\|reel\|taggati&dopo=` | `{ profilo, raccolte (solo prima pagina dei post), contenuti, pagina }` |
|
||||
| `/dati/profilo/{nome}/altri?scheda=&dopo=` | `{ contenuti, pagina }` |
|
||||
| `/dati/post/{codice}` | `{ contenuto }` |
|
||||
| `/dati/storie/{nome}` | `{ autore, storie: [contenuto], successivo }`: tutte le storie attive arrivano subito |
|
||||
| `/dati/evidenza/{id}` | `{ raccolta: { numero, titolo, autore, contenuti }, successiva }` |
|
||||
| `/dati/seguiti?dopo=` | `{ seguiti: [profilo], pagina }` |
|
||||
|
||||
Oggetti:
|
||||
|
||||
```text
|
||||
profilo { numero, nome, nome_visibile, riservato, seguito, pubblicazioni, ritratto: [versione], ultima_storia? }
|
||||
contenuto { numero, sigla?, pubblicato, testo?, fissato, autore: { numero, nome },
|
||||
foto: [versione] | filmati: [versione] + foto (copertina) + durata | parti: [file] + parti_totali,
|
||||
scade? (storie) }
|
||||
file { numero, foto | filmati + durata }
|
||||
versione { indirizzo, larghezza, altezza, audio? (filmati) }
|
||||
pagina { altro, dopo }
|
||||
```
|
||||
|
||||
- Date in testo ISO 8601, UTC (`2026-10-13T08:00:00Z`); durate in secondi.
|
||||
- Le immagini hanno tre versioni (media, grande, piccola: la più grande **non** è la prima); i video due versioni con
|
||||
audio e una più grande **senza** audio, che i lettori non devono scegliere.
|
||||
- Nei post della pagina iniziale una serie arriva **incompleta**: solo il primo file e `parti_totali`. Profilo e pagina
|
||||
del post la danno intera (è il caso «Post singolo»).
|
||||
- Cursori opachi `c{n}`.
|
||||
- Gli indirizzi dei file sono firmati e scadono: `/m/{chiave}/{L}x{A}.jpg?scad={unix}&firma={hmac}` (durata
|
||||
predefinita 6 ore). Un indirizzo scaduto riceve 403. Le foto sono generate con SkiaSharp dalla chiave (stessa
|
||||
chiave, stessa immagine a ogni dimensione); i video sono due MP4 minuscoli generati una volta con ffmpeg
|
||||
(`Risorse/filmato-con-audio.mp4`, `Risorse/filmato-muto.mp4`), resi unici aggiungendo in coda un riquadro `free`.
|
||||
|
||||
## Casi di arresto e comandi per le prove
|
||||
|
||||
Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...` sul sito.
|
||||
|
||||
| Comando | Effetto |
|
||||
|---|---|
|
||||
| `/_controllo/modo?valore=troppe-richieste[&dopo=N]` | le richieste di dati ricevono 429 (dopo N richieste) |
|
||||
| `/_controllo/modo?valore=verifica` | le pagine rimandano a `/verifica`; i dati rispondono 403 e la pagina ci va da sola |
|
||||
| `/_controllo/modo?valore=sessione-scaduta` | il cookie `sessione_prova` si cancella e le pagine vanno a `/sessione-scaduta` |
|
||||
| `/_controllo/modo?valore=vuoto` | le pagine di dati arrivano vuote |
|
||||
| `/_controllo/modo?valore=formato-sconosciuto` | i dati arrivano in una forma che nessun lettore conosce |
|
||||
| `/_controllo/modo?valore=normale`, `/_controllo/reimposta` | tutto torna normale |
|
||||
| `/_controllo/durata-storie?ms=` | quanto resta a schermo una storia prima che il visualizzatore vada avanti da solo |
|
||||
| `/_controllo/scadenza-indirizzi?secondi=` | durata degli indirizzi firmati consegnati da quel momento |
|
||||
| `/_controllo/rinomina?da=&a=` | un account cambia nome (stesso numero) |
|
||||
| `/_controllo/ritratto?nome=` | nuova foto del profilo |
|
||||
| `/_controllo/pubblica?nome=&tipo=foto\|video\|serie` | nuovo post in cima |
|
||||
| `/_controllo/stato` | modo attuale e numero di richieste di dati |
|
||||
|
||||
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla prima visita di una pagina.
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>
|
||||
/// Generates the files the «CDN» serves: JPEG pictures drawn with SkiaSharp from the media key (same key, same
|
||||
/// picture at every size) and short MP4 videos made unique with a trailing «free» box. Results are cached.
|
||||
/// </summary>
|
||||
public sealed class MediaFactory
|
||||
{
|
||||
private static readonly Lazy<byte[]> VideoWithAudio = new(() => ReadResource("filmato-con-audio.mp4"));
|
||||
private static readonly Lazy<byte[]> VideoWithoutAudio = new(() => ReadResource("filmato-muto.mp4"));
|
||||
|
||||
private readonly ConcurrentDictionary<string, byte[]> _cache = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>A JPEG of <paramref name="width"/>×<paramref name="height"/> for <paramref name="key"/>.</summary>
|
||||
public byte[] Picture(string key, int width, int height) =>
|
||||
_cache.GetOrAdd($"p|{key}|{width}|{height}", _ => DrawPicture(key, Math.Clamp(width, 16, 2048), Math.Clamp(height, 16, 2048)));
|
||||
|
||||
/// <summary>An MP4 for <paramref name="key"/>: with audio (complete) or video only.</summary>
|
||||
public byte[] Video(string key, int width, int height, bool withAudio) =>
|
||||
_cache.GetOrAdd($"v|{key}|{width}|{height}|{withAudio}", _ =>
|
||||
{
|
||||
var template = withAudio ? VideoWithAudio.Value : VideoWithoutAudio.Value;
|
||||
var payload = Encoding.ASCII.GetBytes($"febe-sito-di-prova {key} {width}x{height} {(withAudio ? "audio" : "muto")}");
|
||||
var result = new byte[template.Length + 8 + payload.Length];
|
||||
template.CopyTo(result, 0);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(result.AsSpan(template.Length), (uint)(8 + payload.Length));
|
||||
"free"u8.CopyTo(result.AsSpan(template.Length + 4));
|
||||
payload.CopyTo(result, template.Length + 8);
|
||||
return result;
|
||||
});
|
||||
|
||||
private static byte[] DrawPicture(string key, int width, int height)
|
||||
{
|
||||
var seed = BinaryPrimitives.ReadInt32LittleEndian(SHA256.HashData(Encoding.UTF8.GetBytes(key)));
|
||||
var random = new Random(seed);
|
||||
using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
||||
using (var canvas = new SKCanvas(bitmap))
|
||||
{
|
||||
SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
|
||||
using (var background = new SKPaint())
|
||||
{
|
||||
background.Shader = SKShader.CreateLinearGradient(
|
||||
new SKPoint(0, 0),
|
||||
new SKPoint(width, height),
|
||||
[RandomColor(), RandomColor(), RandomColor()],
|
||||
null,
|
||||
SKShaderTileMode.Clamp);
|
||||
canvas.DrawRect(0, 0, width, height, background);
|
||||
}
|
||||
|
||||
// Shapes in relative coordinates: every size shows the same picture.
|
||||
using var paint = new SKPaint { IsAntialias = true };
|
||||
var shapes = 8 + random.Next(8);
|
||||
for (var i = 0; i < shapes; i++)
|
||||
{
|
||||
paint.Color = RandomColor().WithAlpha((byte)(150 + random.Next(100)));
|
||||
var x = (float)(random.NextDouble() * width);
|
||||
var y = (float)(random.NextDouble() * height);
|
||||
var w = (float)((0.08 + (random.NextDouble() * 0.35)) * width);
|
||||
var h = (float)((0.08 + (random.NextDouble() * 0.35)) * height);
|
||||
if (random.Next(2) == 0)
|
||||
{
|
||||
canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint);
|
||||
}
|
||||
else
|
||||
{
|
||||
canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
using var image = SKImage.FromBitmap(bitmap);
|
||||
using var data = image.Encode(SKEncodedImageFormat.Jpeg, 85);
|
||||
return data.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] ReadResource(string name)
|
||||
{
|
||||
using var stream = typeof(MediaFactory).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}")
|
||||
?? throw new FileNotFoundException($"Risorsa mancante: {name}");
|
||||
using var memory = new MemoryStream();
|
||||
stream.CopyTo(memory);
|
||||
return memory.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signed, expiring CDN addresses (spec §6.5: «gli indirizzi scadono»): <c>/m/{key}/{w}x{h}.jpg?scad=…&firma=…</c>.
|
||||
/// The signature is an HMAC of path and expiry with a key drawn at start-up; an address past its expiry gets 403.
|
||||
/// </summary>
|
||||
public sealed class CdnSigner
|
||||
{
|
||||
private readonly byte[] _key = RandomNumberGenerator.GetBytes(32);
|
||||
|
||||
public string Sign(string path, DateTimeOffset expiresAt)
|
||||
{
|
||||
var expiry = expiresAt.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
return $"{path}?scad={expiry}&firma={Signature(path, expiry)}";
|
||||
}
|
||||
|
||||
/// <summary>Checks an address: <see cref="CdnCheck.Valid"/>, <see cref="CdnCheck.Expired"/> or <see cref="CdnCheck.Invalid"/>.</summary>
|
||||
public CdnCheck Check(string path, string? expiry, string? signature, DateTimeOffset now)
|
||||
{
|
||||
if (string.IsNullOrEmpty(expiry) || string.IsNullOrEmpty(signature)
|
||||
|| !long.TryParse(expiry, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var seconds))
|
||||
{
|
||||
return CdnCheck.Invalid;
|
||||
}
|
||||
|
||||
if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(Signature(path, expiry)), Encoding.ASCII.GetBytes(signature)))
|
||||
{
|
||||
return CdnCheck.Invalid;
|
||||
}
|
||||
|
||||
return DateTimeOffset.FromUnixTimeSeconds(seconds) < now ? CdnCheck.Expired : CdnCheck.Valid;
|
||||
}
|
||||
|
||||
private string Signature(string path, string expiry) =>
|
||||
Convert.ToHexStringLower(HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(path + "|" + expiry)))[..24];
|
||||
}
|
||||
|
||||
public enum CdnCheck
|
||||
{
|
||||
Valid,
|
||||
Expired,
|
||||
Invalid,
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>The HTML of the site: plain pages, no branding, no login form. Data is filled in by <c>sito.js</c>.</summary>
|
||||
internal static class Pages
|
||||
{
|
||||
public static string Home() => Layout("Inizio", "inizio", string.Empty, """
|
||||
<h1>Inizio</h1>
|
||||
<section aria-label="Storie"><div class="barra" id="barra"></div></section>
|
||||
<section class="flusso" id="flusso" aria-label="Post recenti"></section>
|
||||
<div class="sentinella" id="sentinella"></div>
|
||||
""");
|
||||
|
||||
public static string Profile(string username, ProfileTab tab)
|
||||
{
|
||||
var u = Encode(username);
|
||||
var tabName = tab switch { ProfileTab.Reels => "reel", ProfileTab.Tagged => "taggati", _ => "post" };
|
||||
string Tab(string label, string path, ProfileTab which) =>
|
||||
$"""<a role="tab" href="/profilo/{u}/{path}" aria-selected="{(tab == which ? "true" : "false")}">{label}</a>""";
|
||||
return Layout($"Profilo di {username}", "profilo", $"""data-utente="{Html(username)}" data-scheda="{tabName}" """, $"""
|
||||
<div class="testata" id="testata"></div>
|
||||
<div class="raccolte" id="raccolte"></div>
|
||||
<nav class="schede" aria-label="Schede del profilo" role="tablist">
|
||||
{Tab("Post", string.Empty, ProfileTab.Posts)}
|
||||
{Tab("Reel", "reel/", ProfileTab.Reels)}
|
||||
{Tab("Taggati", "taggati/", ProfileTab.Tagged)}
|
||||
</nav>
|
||||
<div id="contenuto"><div class="griglia" id="griglia"></div></div>
|
||||
<div class="sentinella" id="sentinella"></div>
|
||||
""");
|
||||
}
|
||||
|
||||
public static string ProfileNotFound(string username) => Layout("Profilo non trovato", "nessuna", string.Empty, $"""
|
||||
<h1>Profilo non trovato</h1>
|
||||
<p>Il profilo «{Html(username)}» non esiste o non è più disponibile.</p>
|
||||
<p><a href="/">Torna all'inizio</a></p>
|
||||
""");
|
||||
|
||||
public static string Following(string username) => Layout($"Profili seguiti da {username}", "seguiti", $"""data-utente="{Html(username)}" """, """
|
||||
<h1>Profili seguiti</h1>
|
||||
<ul class="elenco" id="elenco"></ul>
|
||||
<div class="sentinella" id="sentinella"></div>
|
||||
""");
|
||||
|
||||
public static string Post(string code) => Layout("Post", "post", $"""data-sigla="{Html(code)}" """, """
|
||||
<div id="contenuto"></div>
|
||||
""");
|
||||
|
||||
public static string Viewer(string kind, TimeSpan storyDuration) =>
|
||||
$"""
|
||||
<!doctype html>
|
||||
<html lang="it">
|
||||
<head><meta charset="utf-8"><title>{(kind == "storie" ? "Storie" : "Raccolta")}</title><link rel="stylesheet" href="/risorse/sito.css"></head>
|
||||
<body class="visualizzatore" data-pagina="{kind}" data-durata="{((int)storyDuration.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)}">
|
||||
<div class="progressi" id="progressi"></div>
|
||||
<div class="chi" id="chi"></div>
|
||||
<div class="palco" id="palco"></div>
|
||||
<button class="zona-avanti" id="avanti" aria-label="Storia successiva"></button>
|
||||
<button class="chiudi" id="chiudi" aria-label="Chiudi">×</button>
|
||||
<script src="/risorse/sito.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
public static string Challenge() => Layout("Verifica", "nessuna", string.Empty, """
|
||||
<h1>Verifica richiesta</h1>
|
||||
<p>Il sito di prova chiede una verifica. Febe deve fermarsi e avvisare: qui non c'è niente da compilare.</p>
|
||||
""");
|
||||
|
||||
public static string SessionEnded() => Layout("Sessione scaduta", "nessuna", string.Empty, """
|
||||
<h1>Sessione scaduta</h1>
|
||||
<p>La sessione del sito di prova è terminata. Febe deve fermarsi e non tentare di rientrare.</p>
|
||||
""");
|
||||
|
||||
public static string NotFound() => Layout("Pagina non trovata", "nessuna", string.Empty, "<h1>Pagina non trovata</h1>");
|
||||
|
||||
private static string Layout(string title, string page, string attributes, string main) => $"""
|
||||
<!doctype html>
|
||||
<html lang="it">
|
||||
<head><meta charset="utf-8"><title>{Html(title)} · Sito di prova</title><link rel="stylesheet" href="/risorse/sito.css"></head>
|
||||
<body data-pagina="{page}" {attributes}>
|
||||
<header class="sito"><strong>Sito di prova di Febe</strong><a href="/">Inizio</a><a href="/profilo/alberto.prova/seguiti/">Seguiti</a></header>
|
||||
<main>
|
||||
{main}
|
||||
</main>
|
||||
<script src="/risorse/sito.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
private static string Html(string text) => WebUtility.HtmlEncode(text);
|
||||
|
||||
private static string Encode(string text) => Uri.EscapeDataString(text);
|
||||
}
|
||||
@@ -1,4 +1,108 @@
|
||||
// Local test site (spec §14.2). Filled in by milestones M0 and M2.
|
||||
var app = WebApplication.CreateBuilder(args).Build();
|
||||
app.MapGet("/", () => "Sito di prova di Febe");
|
||||
app.Run();
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.SitoDiProva;
|
||||
|
||||
// Local test site (spec §14.2).
|
||||
// febe-sito-di-prova [--porta 8481] [--porta-cdn 8482] [--indirizzo-cdn 127.0.0.2] [--seme 13]
|
||||
// febe-sito-di-prova campioni --cartella <cartella fuori dal repository> [--seme 13]
|
||||
if (args.Length > 0 && args[0] == "campioni")
|
||||
{
|
||||
return await DumpSamplesAsync(args[1..]);
|
||||
}
|
||||
|
||||
var options = new TestSiteOptions
|
||||
{
|
||||
Port = IntOption(args, "--porta", 8481),
|
||||
CdnPort = IntOption(args, "--porta-cdn", 8482),
|
||||
CdnAddress = Option(args, "--indirizzo-cdn") ?? "127.0.0.2",
|
||||
Seed = IntOption(args, "--seme", 13),
|
||||
ConsoleLog = true,
|
||||
};
|
||||
await using var site = await TestSite.StartAsync(options);
|
||||
Console.WriteLine($"Sito di prova: {site.SiteUrl}/ · CDN: {site.CdnUrl}/ · seme {options.Seed.ToString(CultureInfo.InvariantCulture)}");
|
||||
Console.WriteLine($"Casi di arresto: {site.SiteUrl}/_controllo/modo?valore=troppe-richieste|verifica|sessione-scaduta|vuoto|normale");
|
||||
Console.WriteLine("Ctrl+C per fermare.");
|
||||
var stop = new TaskCompletionSource();
|
||||
Console.CancelKeyPress += (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
stop.TrySetResult();
|
||||
};
|
||||
await stop.Task;
|
||||
return 0;
|
||||
|
||||
// Writes the JSON responses of the main pages in the raw format of the probe (descriptor + body), to be cleaned with
|
||||
// «febe-sonda ripulisci». The data is synthetic, but the samples follow the same path as real ones (spec §14.5).
|
||||
static async Task<int> DumpSamplesAsync(string[] args)
|
||||
{
|
||||
var folder = Option(args, "--cartella");
|
||||
if (string.IsNullOrWhiteSpace(folder))
|
||||
{
|
||||
Console.Error.WriteLine("Indicare --cartella <cartella fuori dal repository>.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(folder);
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions { Seed = IntOption(args, "--seme", 13) });
|
||||
string marta, luca, code;
|
||||
lock (site.World.Gate)
|
||||
{
|
||||
marta = site.World.FindByUsername("marta.prova")!.Username;
|
||||
luca = site.World.FindByUsername("luca.prova")!.Username;
|
||||
code = site.World.FindByUsername("marta.prova")!.Posts.First(p => p.Files.Count > 1).Code;
|
||||
}
|
||||
|
||||
var samples = new (string Name, string Path)[]
|
||||
{
|
||||
("inizio", "/dati/inizio"),
|
||||
("profilo-pubblico", $"/dati/profilo/{marta}?scheda=post"),
|
||||
("profilo-pagina-successiva", $"/dati/profilo/{luca}/altri?scheda=post&dopo=c12"),
|
||||
("profilo-privato-non-seguito", "/dati/profilo/riservato.prova?scheda=post"),
|
||||
("post-serie", $"/dati/post/{code}"),
|
||||
("storie", $"/dati/storie/{marta}"),
|
||||
("raccolta", $"/dati/evidenza/{site.World.FindByUsername("marta.prova")!.Highlights[0].Id}"),
|
||||
("seguiti", "/dati/seguiti"),
|
||||
("taggati", $"/dati/profilo/{marta}?scheda=taggati"),
|
||||
};
|
||||
|
||||
var number = 0;
|
||||
foreach (var (name, path) in samples)
|
||||
{
|
||||
var body = JsonNode.Parse(await site.GetDataAsync(path));
|
||||
await WriteSampleAsync(folder, ++number, name, site.Url(path), 200, body);
|
||||
}
|
||||
|
||||
site.Control.Set(StopMode.EmptyPages);
|
||||
await WriteSampleAsync(folder, ++number, "pagina-vuota", site.Url($"/dati/profilo/{luca}/altri?scheda=post&dopo=c48"), 200, JsonNode.Parse(await site.GetDataAsync($"/dati/profilo/{luca}/altri?scheda=post&dopo=c48")));
|
||||
Console.WriteLine($"Scritti {number.ToString(CultureInfo.InvariantCulture)} campioni grezzi in {folder}.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static async Task WriteSampleAsync(string folder, int number, string name, string url, int status, JsonNode? body)
|
||||
{
|
||||
var sample = new JsonObject
|
||||
{
|
||||
["descrittore"] = new JsonObject
|
||||
{
|
||||
["indirizzo"] = url.Split('?')[0],
|
||||
["host"] = "sito",
|
||||
["stato"] = status,
|
||||
["tipo"] = "application/json",
|
||||
["risorsa"] = "Fetch",
|
||||
["nome"] = name,
|
||||
},
|
||||
["corpo"] = body,
|
||||
};
|
||||
var file = Path.Combine(folder, $"{number.ToString("000000", CultureInfo.InvariantCulture)}-{name}.json");
|
||||
await File.WriteAllTextAsync(file, sample.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
|
||||
static string? Option(string[] args, string name)
|
||||
{
|
||||
var index = Array.IndexOf(args, name);
|
||||
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
static int IntOption(string[] args, string name, int fallback) =>
|
||||
int.TryParse(Option(args, name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : fallback;
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,39 @@
|
||||
/* Sito di prova di Febe: pagine spoglie, nessun marchio. */
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; font: 15px/1.4 system-ui, sans-serif; background: #f4f4f2; color: #222; }
|
||||
a { color: #1d5c8c; }
|
||||
header.sito { padding: 10px 16px; background: #fff; border-bottom: 1px solid #ddd; display: flex; gap: 16px; align-items: center; }
|
||||
header.sito strong { font-weight: 600; }
|
||||
main { max-width: 980px; margin: 0 auto; padding: 16px; }
|
||||
.avviso { padding: 12px; background: #fff3cd; border: 1px solid #e0c46c; margin: 12px 0; }
|
||||
.barra { display: flex; gap: 12px; overflow-x: auto; padding: 8px 0 16px; }
|
||||
.barra a { display: flex; flex-direction: column; align-items: center; gap: 4px; text-decoration: none; color: #333; font-size: 12px; }
|
||||
.barra img, .anello img { width: 64px; height: 64px; border-radius: 50%; border: 3px solid #c84; display: block; }
|
||||
.flusso article { background: #fff; border: 1px solid #ddd; margin: 0 0 24px; padding: 12px; min-height: 640px; }
|
||||
.flusso article img { width: 480px; height: 600px; object-fit: cover; display: block; background: #ccc; }
|
||||
.testata { display: flex; gap: 24px; align-items: center; padding: 16px 0; }
|
||||
.testata .foto { width: 96px; height: 96px; border-radius: 50%; display: block; }
|
||||
.anello img { width: 96px; height: 96px; }
|
||||
nav.schede { display: flex; gap: 24px; border-top: 1px solid #ccc; padding: 8px 0; margin: 8px 0 16px; }
|
||||
nav.schede a[aria-selected="true"] { font-weight: 700; }
|
||||
.raccolte { display: flex; gap: 16px; padding: 8px 0; }
|
||||
.raccolte a { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: #333; font-size: 12px; }
|
||||
.raccolte img { width: 56px; height: 56px; border-radius: 50%; object-fit: cover; }
|
||||
.griglia { display: grid; grid-template-columns: repeat(3, 300px); gap: 8px; }
|
||||
.griglia a { display: block; width: 300px; height: 375px; background: #ccc; position: relative; }
|
||||
.griglia img { width: 300px; height: 375px; object-fit: cover; display: block; }
|
||||
.griglia .segno { position: absolute; top: 6px; right: 8px; color: #fff; font-size: 12px; text-shadow: 0 0 3px #000; }
|
||||
.elenco { list-style: none; margin: 0; padding: 0; }
|
||||
.elenco li { height: 120px; display: flex; align-items: center; gap: 16px; border-bottom: 1px solid #ddd; background: #fff; padding: 0 16px; }
|
||||
.elenco img { width: 56px; height: 56px; border-radius: 50%; }
|
||||
.sentinella { height: 40px; }
|
||||
.caricamento { color: #888; padding: 12px; }
|
||||
body.visualizzatore { background: #111; color: #eee; overflow: hidden; }
|
||||
.palco { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; }
|
||||
.palco img, .palco video { max-width: 405px; max-height: 720px; width: 405px; height: 720px; object-fit: cover; background: #333; }
|
||||
.progressi { position: fixed; top: 8px; left: 50%; transform: translateX(-50%); width: 405px; display: flex; gap: 4px; z-index: 3; }
|
||||
.progressi span { flex: 1; height: 3px; background: #555; }
|
||||
.progressi span.vista { background: #eee; }
|
||||
.chi { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 3; font-size: 13px; }
|
||||
button.zona-avanti { position: fixed; top: 60px; bottom: 60px; left: 50%; right: 80px; background: transparent; border: 0; z-index: 2; cursor: pointer; }
|
||||
button.chiudi { position: fixed; top: 16px; right: 24px; z-index: 4; background: #333; color: #eee; border: 1px solid #777; width: 44px; height: 44px; font-size: 20px; cursor: pointer; }
|
||||
@@ -0,0 +1,246 @@
|
||||
// Sito di prova di Febe (specifica §14.2). Pagine spoglie che caricano i dati in JSON con fetch, come fa un sito
|
||||
// vero: è ciò che la cattura di Febe riceve. Nessun marchio, nessuna pagina di accesso.
|
||||
'use strict';
|
||||
(() => {
|
||||
const corpo = document.body;
|
||||
const qs = new URLSearchParams(location.search);
|
||||
|
||||
function el(tag, attributi, ...figli) {
|
||||
const nodo = document.createElement(tag);
|
||||
for (const [nome, valore] of Object.entries(attributi || {})) {
|
||||
if (valore === null || valore === undefined || valore === false) continue;
|
||||
if (nome === 'testo') nodo.textContent = valore;
|
||||
else nodo.setAttribute(nome, valore === true ? '' : String(valore));
|
||||
}
|
||||
for (const figlio of figli) if (figlio) nodo.appendChild(figlio);
|
||||
return nodo;
|
||||
}
|
||||
|
||||
function avviso(testo) {
|
||||
const principale = document.querySelector('main') || corpo;
|
||||
principale.appendChild(el('div', { class: 'avviso', role: 'status', testo }));
|
||||
}
|
||||
|
||||
async function carica(indirizzo) {
|
||||
const risposta = await fetch(indirizzo, { credentials: 'same-origin', headers: { Accept: 'application/json' } });
|
||||
let dati = null;
|
||||
try { dati = await risposta.json(); } catch { dati = null; }
|
||||
if (risposta.status === 401) { location.href = '/sessione-scaduta'; throw new Error('sessione'); }
|
||||
if (risposta.status === 403 && dati && dati.errore === 'verifica') { location.href = '/verifica'; throw new Error('verifica'); }
|
||||
if (risposta.status === 429) { avviso('Troppe richieste: riprova più tardi.'); throw new Error('troppe'); }
|
||||
if (!risposta.ok) throw new Error('stato ' + risposta.status);
|
||||
return dati;
|
||||
}
|
||||
|
||||
// La versione più piccola per mostrare, la più grande non serve alla pagina.
|
||||
function piccola(versioni) {
|
||||
if (!versioni || !versioni.length) return null;
|
||||
return versioni.reduce((a, b) => (a.larghezza * a.altezza <= b.larghezza * b.altezza ? a : b)).indirizzo;
|
||||
}
|
||||
|
||||
function copertina(contenuto) {
|
||||
if (contenuto.foto) return piccola(contenuto.foto);
|
||||
if (contenuto.parti && contenuto.parti.length) return piccola(contenuto.parti[0].foto);
|
||||
return null;
|
||||
}
|
||||
|
||||
function percorsoSicuro(p) {
|
||||
return typeof p === 'string' && p.startsWith('/') && !p.startsWith('//') ? p : '/';
|
||||
}
|
||||
|
||||
// Carica altre pagine quando la sentinella si avvicina alla parte visibile, come un sito che scorre all'infinito.
|
||||
function scorrimentoInfinito(sentinella, prossima) {
|
||||
let occupato = false;
|
||||
let finito = false;
|
||||
const osservatore = new IntersectionObserver(async (voci) => {
|
||||
if (!voci.some((v) => v.isIntersecting) || occupato || finito) return;
|
||||
occupato = true;
|
||||
try { finito = !(await prossima()); } catch { finito = true; }
|
||||
occupato = false;
|
||||
if (!finito) { osservatore.unobserve(sentinella); osservatore.observe(sentinella); }
|
||||
}, { rootMargin: '0px 0px 300px 0px' });
|
||||
osservatore.observe(sentinella);
|
||||
}
|
||||
|
||||
function articolo(contenuto) {
|
||||
const autore = contenuto.autore ? contenuto.autore.nome : '';
|
||||
const immagine = copertina(contenuto);
|
||||
return el('article', {},
|
||||
el('header', {}, el('a', { href: '/profilo/' + encodeURIComponent(autore) + '/', testo: autore })),
|
||||
el('a', { href: '/post/' + encodeURIComponent(contenuto.sigla || '') + '/' }, immagine ? el('img', { src: immagine, alt: '' }) : null),
|
||||
el('p', { testo: contenuto.testo || '' }));
|
||||
}
|
||||
|
||||
function tessera(contenuto) {
|
||||
const immagine = copertina(contenuto);
|
||||
const segno = contenuto.fissato ? 'Fissato' : (contenuto.parti ? 'Serie' : (contenuto.filmati ? 'Video' : ''));
|
||||
return el('a', { href: '/post/' + encodeURIComponent(contenuto.sigla || '') + '/' },
|
||||
immagine ? el('img', { src: immagine, alt: '' }) : null,
|
||||
segno ? el('span', { class: 'segno', testo: segno }) : null);
|
||||
}
|
||||
|
||||
async function inizio() {
|
||||
const barra = document.getElementById('barra');
|
||||
const flusso = document.getElementById('flusso');
|
||||
const dati = await carica('/dati/inizio');
|
||||
for (const p of dati.barra || []) {
|
||||
barra.appendChild(el('a', { href: '/storie/' + encodeURIComponent(p.nome) + '/?da=%2F', 'aria-label': 'Storie di ' + p.nome },
|
||||
el('img', { src: piccola(p.ritratto), alt: '' }), el('span', { testo: p.nome })));
|
||||
}
|
||||
for (const c of dati.contenuti || []) flusso.appendChild(articolo(c));
|
||||
let pagina = dati.pagina || {};
|
||||
scorrimentoInfinito(document.getElementById('sentinella'), async () => {
|
||||
if (!pagina.altro) return false;
|
||||
const altri = await carica('/dati/inizio/altri?dopo=' + encodeURIComponent(pagina.dopo));
|
||||
for (const c of altri.contenuti || []) flusso.appendChild(articolo(c));
|
||||
pagina = altri.pagina || {};
|
||||
return !!pagina.altro;
|
||||
});
|
||||
}
|
||||
|
||||
async function profilo() {
|
||||
const utente = corpo.dataset.utente;
|
||||
const scheda = corpo.dataset.scheda;
|
||||
const dopo = qs.get('dopo');
|
||||
const dati = await carica('/dati/profilo/' + encodeURIComponent(utente) + '?scheda=' + scheda + (dopo ? '&dopo=' + encodeURIComponent(dopo) : ''));
|
||||
const p = dati.profilo;
|
||||
const testata = document.getElementById('testata');
|
||||
const ritratto = piccola(p.ritratto);
|
||||
if (p.ultima_storia) {
|
||||
testata.appendChild(el('a', { class: 'anello', href: '/storie/' + encodeURIComponent(p.nome) + '/?da=' + encodeURIComponent(location.pathname), 'aria-label': 'Apri le storie di ' + p.nome },
|
||||
el('img', { src: ritratto, alt: '' })));
|
||||
} else {
|
||||
testata.appendChild(el('img', { class: 'foto', src: ritratto, alt: 'Foto del profilo di ' + p.nome }));
|
||||
}
|
||||
testata.appendChild(el('div', {}, el('h1', { testo: p.nome }), el('p', { testo: p.nome_visibile + ' · ' + p.pubblicazioni + ' post' })));
|
||||
if (p.riservato && !p.seguito) {
|
||||
document.getElementById('contenuto').appendChild(el('p', { class: 'avviso', testo: 'Questo profilo è privato.' }));
|
||||
return;
|
||||
}
|
||||
const raccolte = document.getElementById('raccolte');
|
||||
for (const r of dati.raccolte || []) {
|
||||
raccolte.appendChild(el('a', { href: '/evidenza/' + encodeURIComponent(r.numero) + '/?da=' + encodeURIComponent(location.pathname), 'aria-label': 'Raccolta ' + r.titolo },
|
||||
r.copertina ? el('img', { src: r.copertina.indirizzo, alt: '' }) : null, el('span', { testo: r.titolo })));
|
||||
}
|
||||
const griglia = document.getElementById('griglia');
|
||||
for (const c of dati.contenuti || []) griglia.appendChild(tessera(c));
|
||||
let pagina = dati.pagina || {};
|
||||
scorrimentoInfinito(document.getElementById('sentinella'), async () => {
|
||||
if (!pagina.altro) return false;
|
||||
const altri = await carica('/dati/profilo/' + encodeURIComponent(utente) + '/altri?scheda=' + scheda + '&dopo=' + encodeURIComponent(pagina.dopo));
|
||||
for (const c of altri.contenuti || []) griglia.appendChild(tessera(c));
|
||||
pagina = altri.pagina || {};
|
||||
return !!pagina.altro;
|
||||
});
|
||||
}
|
||||
|
||||
async function seguiti() {
|
||||
const elenco = document.getElementById('elenco');
|
||||
const dopo = qs.get('dopo');
|
||||
const riga = (p) => el('li', {}, el('img', { src: piccola(p.ritratto), alt: '' }),
|
||||
el('a', { href: '/profilo/' + encodeURIComponent(p.nome) + '/', testo: p.nome }), el('span', { testo: p.nome_visibile }));
|
||||
const dati = await carica('/dati/seguiti' + (dopo ? '?dopo=' + encodeURIComponent(dopo) : ''));
|
||||
for (const p of dati.seguiti || []) elenco.appendChild(riga(p));
|
||||
let pagina = dati.pagina || {};
|
||||
scorrimentoInfinito(document.getElementById('sentinella'), async () => {
|
||||
if (!pagina.altro) return false;
|
||||
const altri = await carica('/dati/seguiti?dopo=' + encodeURIComponent(pagina.dopo));
|
||||
for (const p of altri.seguiti || []) elenco.appendChild(riga(p));
|
||||
pagina = altri.pagina || {};
|
||||
return !!pagina.altro;
|
||||
});
|
||||
}
|
||||
|
||||
async function post() {
|
||||
const dati = await carica('/dati/post/' + encodeURIComponent(corpo.dataset.sigla));
|
||||
const c = dati.contenuto;
|
||||
const contenitore = document.getElementById('contenuto');
|
||||
contenitore.appendChild(el('h1', { testo: (c.autore ? c.autore.nome : '') }));
|
||||
for (const parte of c.parti || [c]) {
|
||||
const immagine = piccola(parte.foto);
|
||||
if (immagine) contenitore.appendChild(el('img', { src: immagine, alt: '', width: 480 }));
|
||||
}
|
||||
contenitore.appendChild(el('p', { testo: c.testo || '' }));
|
||||
}
|
||||
|
||||
// Visualizzatore di storie e raccolte: una voce alla volta, avanzamento da solo o con la zona «Storia successiva».
|
||||
// Dopo l'ultima voce passa da solo all'account (o alla raccolta) successivo, come i siti veri: chi lo usa
|
||||
// deve chiuderlo prima, se non vuole andare avanti.
|
||||
async function visualizzatore(tipo) {
|
||||
const parti = location.pathname.split('/').filter(Boolean);
|
||||
let chiave = decodeURIComponent(parti[1] || '');
|
||||
const idIniziale = parti[2] ? decodeURIComponent(parti[2]) : null;
|
||||
const origine = percorsoSicuro(qs.get('da'));
|
||||
const durataFoto = Number(corpo.dataset.durata || 5000);
|
||||
const palco = document.getElementById('palco');
|
||||
const progressi = document.getElementById('progressi');
|
||||
const chi = document.getElementById('chi');
|
||||
let voci = [];
|
||||
let successivo = null;
|
||||
let indice = 0;
|
||||
let timer = null;
|
||||
|
||||
async function apri(k) {
|
||||
chiave = k;
|
||||
if (tipo === 'storie') {
|
||||
const g = await carica('/dati/storie/' + encodeURIComponent(k));
|
||||
voci = g.storie || [];
|
||||
successivo = g.successivo;
|
||||
chi.textContent = g.autore ? g.autore.nome : '';
|
||||
} else {
|
||||
const g = await carica('/dati/evidenza/' + encodeURIComponent(k));
|
||||
voci = (g.raccolta && g.raccolta.contenuti) || [];
|
||||
successivo = g.successiva;
|
||||
chi.textContent = g.raccolta ? g.raccolta.titolo : '';
|
||||
}
|
||||
}
|
||||
|
||||
function chiudi() {
|
||||
clearTimeout(timer);
|
||||
location.href = origine;
|
||||
}
|
||||
|
||||
function mostra() {
|
||||
const voce = voci[indice];
|
||||
history.replaceState(null, '', '/' + tipo + '/' + encodeURIComponent(chiave) + '/' + encodeURIComponent(voce.numero) + '/' + location.search);
|
||||
palco.replaceChildren();
|
||||
if (voce.filmati) {
|
||||
const conAudio = voce.filmati.filter((f) => f.audio !== false);
|
||||
palco.appendChild(el('video', { src: piccola(conAudio.length ? conAudio : voce.filmati), muted: true, autoplay: true, playsinline: true }));
|
||||
} else {
|
||||
palco.appendChild(el('img', { src: piccola(voce.foto), alt: '' }));
|
||||
}
|
||||
progressi.replaceChildren(...voci.map((_, i) => el('span', { class: i <= indice ? 'vista' : '' })));
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(avanti, voce.filmati ? Math.max(500, (voce.durata || 2) * 1000) : durataFoto);
|
||||
}
|
||||
|
||||
async function avanti() {
|
||||
clearTimeout(timer);
|
||||
if (indice + 1 < voci.length) { indice++; mostra(); return; }
|
||||
if (successivo) {
|
||||
await apri(successivo);
|
||||
indice = 0;
|
||||
if (voci.length) { mostra(); return; }
|
||||
}
|
||||
chiudi();
|
||||
}
|
||||
|
||||
document.getElementById('avanti').addEventListener('click', () => { avanti(); });
|
||||
document.getElementById('chiudi').addEventListener('click', chiudi);
|
||||
await apri(chiave);
|
||||
if (!voci.length) { chiudi(); return; }
|
||||
indice = idIniziale ? Math.max(0, voci.findIndex((v) => v.numero === idIniziale)) : 0;
|
||||
mostra();
|
||||
}
|
||||
|
||||
const avvio = {
|
||||
inizio,
|
||||
profilo,
|
||||
seguiti,
|
||||
post,
|
||||
storie: () => visualizzatore('storie'),
|
||||
evidenza: () => visualizzatore('evidenza'),
|
||||
}[corpo.dataset.pagina];
|
||||
if (avvio) avvio().catch(() => {});
|
||||
})();
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>The stop cases the site can play (spec §14.2), switched by the tests through <c>/_controllo</c>.</summary>
|
||||
public enum StopMode
|
||||
{
|
||||
/// <summary>Everything works.</summary>
|
||||
Normal,
|
||||
|
||||
/// <summary>Data requests get HTTP 429 (Rallentamento).</summary>
|
||||
TooManyRequests,
|
||||
|
||||
/// <summary>Pages are redirected to <c>/verifica</c>; data requests get 403 and the page moves there (Verifica).</summary>
|
||||
Challenge,
|
||||
|
||||
/// <summary>The session cookie is removed and pages move to <c>/sessione-scaduta</c> (Disconnessione).</summary>
|
||||
SessionEnded,
|
||||
|
||||
/// <summary>Data requests return empty pages.</summary>
|
||||
EmptyPages,
|
||||
|
||||
/// <summary>Data requests return a shape no reader knows (the site «changed»).</summary>
|
||||
UnknownFormat,
|
||||
}
|
||||
|
||||
/// <summary>Switches and counters of the test site. Thread-safe.</summary>
|
||||
public sealed class SiteControl
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly ConcurrentQueue<string> _dataRequests = new();
|
||||
private StopMode _mode = StopMode.Normal;
|
||||
private int _armAfter;
|
||||
|
||||
/// <summary>How long a photo story stays on screen before the viewer moves on by itself.</summary>
|
||||
public TimeSpan StoryDuration { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Validity of the CDN addresses handed out from now on.</summary>
|
||||
public TimeSpan AddressLifetime { get; set; } = TimeSpan.FromHours(6);
|
||||
|
||||
/// <summary>Paths with query of every data request, in arrival order (for the tests).</summary>
|
||||
public IReadOnlyList<string> DataRequests => [.. _dataRequests];
|
||||
|
||||
/// <summary>Number of files served by the CDN.</summary>
|
||||
public int CdnFilesServed => _cdnFiles;
|
||||
|
||||
/// <summary>Number of CDN requests refused because the address had expired.</summary>
|
||||
public int CdnExpired => _cdnExpired;
|
||||
|
||||
private int _cdnFiles;
|
||||
private int _cdnExpired;
|
||||
|
||||
public StopMode Mode
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _armAfter > 0 ? StopMode.Normal : _mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sets a stop case; with <paramref name="afterDataRequests"/> it starts after that many more data requests.</summary>
|
||||
public void Set(StopMode mode, int afterDataRequests = 0)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_mode = mode;
|
||||
_armAfter = Math.Max(0, afterDataRequests);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Back to normal; counters cleared; default story duration and address lifetime.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_mode = StopMode.Normal;
|
||||
_armAfter = 0;
|
||||
}
|
||||
|
||||
_dataRequests.Clear();
|
||||
StoryDuration = TimeSpan.FromSeconds(5);
|
||||
AddressLifetime = TimeSpan.FromHours(6);
|
||||
Interlocked.Exchange(ref _cdnFiles, 0);
|
||||
Interlocked.Exchange(ref _cdnExpired, 0);
|
||||
}
|
||||
|
||||
public void ClearRequests() => _dataRequests.Clear();
|
||||
|
||||
/// <summary>Records a data request and returns the mode that applies to it.</summary>
|
||||
internal StopMode OnDataRequest(string pathAndQuery)
|
||||
{
|
||||
_dataRequests.Enqueue(pathAndQuery);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_armAfter > 0)
|
||||
{
|
||||
_armAfter--;
|
||||
return StopMode.Normal;
|
||||
}
|
||||
|
||||
return _mode;
|
||||
}
|
||||
}
|
||||
|
||||
internal void OnCdnServed() => Interlocked.Increment(ref _cdnFiles);
|
||||
|
||||
internal void OnCdnExpired() => Interlocked.Increment(ref _cdnExpired);
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>Options of the test site.</summary>
|
||||
public sealed record TestSiteOptions
|
||||
{
|
||||
/// <summary>Port of the site on 127.0.0.1; 0 picks a free one.</summary>
|
||||
public int Port { get; init; }
|
||||
|
||||
/// <summary>Port of the «CDN»; 0 picks a free one.</summary>
|
||||
public int CdnPort { get; init; }
|
||||
|
||||
/// <summary>Address of the «CDN»: a second loopback address, so cookies of the site do not reach it.</summary>
|
||||
public string CdnAddress { get; init; } = "127.0.0.2";
|
||||
|
||||
/// <summary>Seed of the synthetic data.</summary>
|
||||
public int Seed { get; init; } = 13;
|
||||
|
||||
/// <summary>Clock of the site (dates, address expiry).</summary>
|
||||
public TimeProvider Time { get; init; } = TimeProvider.System;
|
||||
|
||||
/// <summary>Write requests to the console (the command-line tool does; tests do not).</summary>
|
||||
public bool ConsoleLog { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The local test site of spec §14.2, served on 127.0.0.1 with its «CDN» on a second address. Pages are plain and
|
||||
/// fetch JSON in a synthetic format of our own; stop cases are switched through <see cref="Control"/> or the
|
||||
/// <c>/_controllo</c> endpoints. Never Instagram, never anything that looks like it.
|
||||
/// </summary>
|
||||
public sealed class TestSite : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Name of the session cookie of the site.</summary>
|
||||
public const string SessionCookie = "sessione_prova";
|
||||
|
||||
private readonly WebApplication _app;
|
||||
private readonly TimeProvider _time;
|
||||
|
||||
private TestSite(WebApplication app, World world, SiteControl control, MediaFactory media, CdnSigner signer, int sitePort, string cdnAddress, int cdnPort, TimeProvider time)
|
||||
{
|
||||
_app = app;
|
||||
World = world;
|
||||
Control = control;
|
||||
Media = media;
|
||||
Signer = signer;
|
||||
SitePort = sitePort;
|
||||
CdnAddress = cdnAddress;
|
||||
CdnPort = cdnPort;
|
||||
_time = time;
|
||||
}
|
||||
|
||||
public World World { get; }
|
||||
|
||||
public SiteControl Control { get; }
|
||||
|
||||
public MediaFactory Media { get; }
|
||||
|
||||
public CdnSigner Signer { get; }
|
||||
|
||||
public int SitePort { get; }
|
||||
|
||||
public string CdnAddress { get; }
|
||||
|
||||
public int CdnPort { get; }
|
||||
|
||||
/// <summary>«127.0.0.1:port»: an entry for the host classifier.</summary>
|
||||
public string SiteHost => $"127.0.0.1:{SitePort.ToString(CultureInfo.InvariantCulture)}";
|
||||
|
||||
public string CdnHost => $"{CdnAddress}:{CdnPort.ToString(CultureInfo.InvariantCulture)}";
|
||||
|
||||
public string SiteUrl => $"http://{SiteHost}";
|
||||
|
||||
public string CdnUrl => $"http://{CdnHost}";
|
||||
|
||||
public string Url(string path) => SiteUrl + path;
|
||||
|
||||
public static async Task<TestSite> StartAsync(TestSiteOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
options ??= new TestSiteOptions();
|
||||
var cdnAddress = CanBind(options.CdnAddress) ? options.CdnAddress : "127.0.0.1";
|
||||
var sitePort = options.Port > 0 ? options.Port : FreePort(IPAddress.Loopback);
|
||||
var cdnPort = options.CdnPort > 0 ? options.CdnPort : FreePort(IPAddress.Parse(cdnAddress));
|
||||
if (cdnAddress == "127.0.0.1" && cdnPort == sitePort)
|
||||
{
|
||||
cdnPort = FreePort(IPAddress.Loopback);
|
||||
}
|
||||
|
||||
var world = World.Generate(options.Seed, options.Time.GetUtcNow());
|
||||
var control = new SiteControl();
|
||||
var media = new MediaFactory();
|
||||
var signer = new CdnSigner();
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder();
|
||||
builder.Services.Configure<Microsoft.Extensions.Hosting.HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(2));
|
||||
builder.Logging.ClearProviders();
|
||||
if (options.ConsoleLog)
|
||||
{
|
||||
builder.Logging.AddSimpleConsole(o => o.SingleLine = true);
|
||||
builder.Logging.SetMinimumLevel(LogLevel.Warning);
|
||||
}
|
||||
|
||||
builder.WebHost.UseKestrel(k =>
|
||||
{
|
||||
k.Listen(IPAddress.Loopback, sitePort);
|
||||
k.Listen(IPAddress.Parse(cdnAddress), cdnPort);
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
var site = new TestSite(app, world, control, media, signer, sitePort, cdnAddress, cdnPort, options.Time);
|
||||
app.Run(site.HandleAsync);
|
||||
await app.StartAsync(ct).ConfigureAwait(false);
|
||||
return site;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _app.StopAsync().ConfigureAwait(false);
|
||||
await _app.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The JSON of a data endpoint as the page would receive it (sample capture, tests).</summary>
|
||||
public async Task<string> GetDataAsync(string pathAndQuery, CancellationToken ct = default)
|
||||
{
|
||||
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false });
|
||||
return await client.GetStringAsync(new Uri(Url(pathAndQuery)), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private DataApi Api => new(World, Signer, Control, () => CdnUrl, _time);
|
||||
|
||||
private async Task HandleAsync(HttpContext context)
|
||||
{
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
if (context.Connection.LocalPort == CdnPort && context.Connection.LocalIpAddress?.ToString() == CdnAddress)
|
||||
{
|
||||
await ServeCdnAsync(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var path = context.Request.Path.Value ?? "/";
|
||||
if (path.StartsWith("/_controllo/", StringComparison.Ordinal))
|
||||
{
|
||||
await ControlAsync(context, path["/_controllo/".Length..]).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.StartsWith("/risorse/", StringComparison.Ordinal))
|
||||
{
|
||||
await ResourceAsync(context, path["/risorse/".Length..]).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.StartsWith("/dati/", StringComparison.Ordinal))
|
||||
{
|
||||
await DataAsync(context, path).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await PageAsync(context, path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task PageAsync(HttpContext context, string path)
|
||||
{
|
||||
var mode = Control.Mode;
|
||||
if (path is "/verifica" or "/verifica/")
|
||||
{
|
||||
await HtmlAsync(context, 200, Pages.Challenge()).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path is "/sessione-scaduta" or "/sessione-scaduta/")
|
||||
{
|
||||
await HtmlAsync(context, 200, Pages.SessionEnded()).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (path == "/favicon.ico")
|
||||
{
|
||||
context.Response.StatusCode = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (mode)
|
||||
{
|
||||
case StopMode.Challenge:
|
||||
context.Response.Redirect("/verifica?motivo=prova");
|
||||
return;
|
||||
case StopMode.SessionEnded:
|
||||
ExpireSession(context);
|
||||
context.Response.Redirect("/sessione-scaduta");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.Request.Cookies.ContainsKey(SessionCookie))
|
||||
{
|
||||
context.Response.Cookies.Append(SessionCookie, "attiva", new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
string html;
|
||||
var status = 200;
|
||||
lock (World.Gate)
|
||||
{
|
||||
switch (segments)
|
||||
{
|
||||
case []:
|
||||
html = Pages.Home();
|
||||
break;
|
||||
case ["profilo", var user, ..] when World.FindByUsername(user) is null:
|
||||
html = Pages.ProfileNotFound(user);
|
||||
status = 404;
|
||||
break;
|
||||
case ["profilo", var user]:
|
||||
html = Pages.Profile(user, ProfileTab.Posts);
|
||||
break;
|
||||
case ["profilo", var user, "reel"]:
|
||||
html = Pages.Profile(user, ProfileTab.Reels);
|
||||
break;
|
||||
case ["profilo", var user, "taggati"]:
|
||||
html = Pages.Profile(user, ProfileTab.Tagged);
|
||||
break;
|
||||
case ["profilo", var user, "seguiti"] when World.FindByUsername(user)?.IsViewer == true:
|
||||
html = Pages.Following(user);
|
||||
break;
|
||||
case ["post", var code, ..]:
|
||||
html = Pages.Post(code);
|
||||
break;
|
||||
case ["storie", _, ..]:
|
||||
html = Pages.Viewer("storie", Control.StoryDuration);
|
||||
break;
|
||||
case ["evidenza", _, ..]:
|
||||
html = Pages.Viewer("evidenza", Control.StoryDuration);
|
||||
break;
|
||||
default:
|
||||
html = Pages.NotFound();
|
||||
status = 404;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await HtmlAsync(context, status, html).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task DataAsync(HttpContext context, string path)
|
||||
{
|
||||
var query = context.Request.Query;
|
||||
var mode = Control.OnDataRequest(path + context.Request.QueryString.Value);
|
||||
switch (mode)
|
||||
{
|
||||
case StopMode.TooManyRequests:
|
||||
await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false);
|
||||
return;
|
||||
case StopMode.Challenge:
|
||||
await JsonAsync(context, 403, new JsonObject { ["errore"] = "verifica" }).ConfigureAwait(false);
|
||||
return;
|
||||
case StopMode.SessionEnded:
|
||||
ExpireSession(context);
|
||||
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione" }).ConfigureAwait(false);
|
||||
return;
|
||||
case StopMode.EmptyPages:
|
||||
await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false);
|
||||
return;
|
||||
case StopMode.UnknownFormat:
|
||||
await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts };
|
||||
var after = query["dopo"].ToString();
|
||||
JsonObject? result;
|
||||
lock (World.Gate)
|
||||
{
|
||||
var api = Api;
|
||||
result = segments switch
|
||||
{
|
||||
["dati", "inizio"] => api.Home(),
|
||||
["dati", "inizio", "altri"] => api.HomeMore(after),
|
||||
["dati", "profilo", var user] => api.Profile(user, tab, after),
|
||||
["dati", "profilo", var user, "altri"] => api.ProfileMore(user, tab, after),
|
||||
["dati", "post", var code] => api.SinglePost(code),
|
||||
["dati", "storie", var user] => api.Stories(user),
|
||||
["dati", "evidenza", var id] => api.HighlightItems(id),
|
||||
["dati", "seguiti"] => api.Following(after),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
if (result is null)
|
||||
{
|
||||
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ServeCdnAsync(HttpContext context)
|
||||
{
|
||||
var path = context.Request.Path.Value ?? string.Empty;
|
||||
var query = context.Request.Query;
|
||||
var check = Signer.Check(path, query["scad"].ToString(), query["firma"].ToString(), _time.GetUtcNow());
|
||||
if (check != CdnCheck.Valid)
|
||||
{
|
||||
if (check == CdnCheck.Expired)
|
||||
{
|
||||
Control.OnCdnExpired();
|
||||
}
|
||||
|
||||
context.Response.StatusCode = 403;
|
||||
context.Response.ContentType = "text/plain; charset=utf-8";
|
||||
await context.Response.WriteAsync(check == CdnCheck.Expired ? "Indirizzo scaduto." : "Firma non valida.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// /m/{key}/{w}x{h}.jpg, /m/{key}/{w}x{h}.mp4, /m/{key}/{w}x{h}-muto.mp4
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments is not ["m", var key, var file] || !TryParseSize(file, out var width, out var height, out var extension, out var silent))
|
||||
{
|
||||
context.Response.StatusCode = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
var bytes = extension == "mp4" ? Media.Video(key, width, height, !silent) : Media.Picture(key, width, height);
|
||||
Control.OnCdnServed();
|
||||
context.Response.ContentType = extension == "mp4" ? "video/mp4" : "image/jpeg";
|
||||
context.Response.ContentLength = bytes.Length;
|
||||
await context.Response.Body.WriteAsync(bytes).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ControlAsync(HttpContext context, string command)
|
||||
{
|
||||
var q = context.Request.Query;
|
||||
JsonObject answer = new() { ["ok"] = true };
|
||||
lock (World.Gate)
|
||||
{
|
||||
switch (command)
|
||||
{
|
||||
case "stato":
|
||||
answer["modo"] = Control.Mode.ToString();
|
||||
answer["richieste"] = Control.DataRequests.Count;
|
||||
break;
|
||||
case "modo":
|
||||
var mode = q["valore"].ToString() switch
|
||||
{
|
||||
"troppe-richieste" => StopMode.TooManyRequests,
|
||||
"verifica" => StopMode.Challenge,
|
||||
"sessione-scaduta" => StopMode.SessionEnded,
|
||||
"vuoto" => StopMode.EmptyPages,
|
||||
"formato-sconosciuto" => StopMode.UnknownFormat,
|
||||
_ => StopMode.Normal,
|
||||
};
|
||||
Control.Set(mode, int.TryParse(q["dopo"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var after) ? after : 0);
|
||||
answer["modo"] = mode.ToString();
|
||||
break;
|
||||
case "reimposta":
|
||||
Control.Reset();
|
||||
break;
|
||||
case "durata-storie":
|
||||
Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "scadenza-indirizzi":
|
||||
Control.AddressLifetime = TimeSpan.FromSeconds(int.Parse(q["secondi"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "rinomina":
|
||||
var account = World.FindByUsername(q["da"].ToString());
|
||||
if (account is null)
|
||||
{
|
||||
answer["ok"] = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
account.Username = q["a"].ToString();
|
||||
}
|
||||
|
||||
break;
|
||||
case "ritratto":
|
||||
if (World.FindByUsername(q["nome"].ToString()) is { } owner)
|
||||
{
|
||||
owner.PictureVersion++;
|
||||
}
|
||||
|
||||
break;
|
||||
case "pubblica":
|
||||
if (World.FindByUsername(q["nome"].ToString()) is { } author)
|
||||
{
|
||||
var post = World.Publish(author, q["tipo"].ToString() is { Length: > 0 } t ? t : "foto", _time.GetUtcNow());
|
||||
answer["sigla"] = post.Code;
|
||||
answer["numero"] = post.Id;
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
answer["ok"] = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await JsonAsync(context, answer["ok"]!.GetValue<bool>() ? 200 : 400, answer).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task ResourceAsync(HttpContext context, string name)
|
||||
{
|
||||
if (name is not ("sito.js" or "sito.css"))
|
||||
{
|
||||
context.Response.StatusCode = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
await using var stream = typeof(TestSite).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}");
|
||||
if (stream is null)
|
||||
{
|
||||
context.Response.StatusCode = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.ContentType = name.EndsWith(".js", StringComparison.Ordinal) ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8";
|
||||
await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static void ExpireSession(HttpContext context) =>
|
||||
context.Response.Cookies.Delete(SessionCookie, new CookieOptions { Path = "/" });
|
||||
|
||||
private static Task HtmlAsync(HttpContext context, int status, string html)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
return context.Response.WriteAsync(html);
|
||||
}
|
||||
|
||||
private static Task JsonAsync(HttpContext context, int status, JsonObject body)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
context.Response.ContentType = "application/json; charset=utf-8";
|
||||
return context.Response.WriteAsync(body.ToJsonString(), Encoding.UTF8);
|
||||
}
|
||||
|
||||
private static bool TryParseSize(string file, out int width, out int height, out string extension, out bool silent)
|
||||
{
|
||||
width = height = 0;
|
||||
extension = string.Empty;
|
||||
silent = false;
|
||||
var dot = file.LastIndexOf('.');
|
||||
if (dot < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
extension = file[(dot + 1)..];
|
||||
var name = file[..dot];
|
||||
if (name.EndsWith("-muto", StringComparison.Ordinal))
|
||||
{
|
||||
silent = true;
|
||||
name = name[..^"-muto".Length];
|
||||
}
|
||||
|
||||
var x = name.IndexOf('x', StringComparison.Ordinal);
|
||||
return x > 0
|
||||
&& int.TryParse(name.AsSpan(0, x), NumberStyles.Integer, CultureInfo.InvariantCulture, out width)
|
||||
&& int.TryParse(name.AsSpan(x + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out height)
|
||||
&& extension is "jpg" or "mp4";
|
||||
}
|
||||
|
||||
private static bool CanBind(string address)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var probe = new TcpListener(IPAddress.Parse(address), 0);
|
||||
probe.Start();
|
||||
probe.Stop();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is SocketException or FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int FreePort(IPAddress address)
|
||||
{
|
||||
var probe = new TcpListener(address, 0);
|
||||
probe.Start();
|
||||
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
||||
probe.Stop();
|
||||
return port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>One file of a post or story: a photo or a short video, served by the «CDN» in several sizes.</summary>
|
||||
public sealed class SiteFile
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required bool IsVideo { get; init; }
|
||||
|
||||
/// <summary>Size of the largest version.</summary>
|
||||
public required int Width { get; init; }
|
||||
|
||||
public required int Height { get; init; }
|
||||
|
||||
/// <summary>Video duration in seconds.</summary>
|
||||
public double DurationSeconds { get; init; }
|
||||
|
||||
/// <summary>Key of the generated content on the CDN: same key, same picture at every size.</summary>
|
||||
public string MediaKey => "f" + Id;
|
||||
}
|
||||
|
||||
/// <summary>A post of the grid (a reel when it is a single video).</summary>
|
||||
public sealed class SitePost
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string Code { get; init; }
|
||||
|
||||
public required DateTimeOffset PublishedAt { get; init; }
|
||||
|
||||
public required string Caption { get; init; }
|
||||
|
||||
public required SiteAccount Owner { get; init; }
|
||||
|
||||
public bool Pinned { get; set; }
|
||||
|
||||
public bool IsReel { get; init; }
|
||||
|
||||
public required IReadOnlyList<SiteFile> Files { get; init; }
|
||||
|
||||
/// <summary>Accounts tagged in the post (it appears in their «Taggati» tab).</summary>
|
||||
public List<SiteAccount> Tagged { get; } = [];
|
||||
}
|
||||
|
||||
/// <summary>A story (24 hours) or an item of a highlight collection.</summary>
|
||||
public sealed class SiteStory
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required DateTimeOffset PublishedAt { get; init; }
|
||||
|
||||
public required SiteAccount Owner { get; init; }
|
||||
|
||||
public required SiteFile File { get; init; }
|
||||
|
||||
public DateTimeOffset ExpiresAt => PublishedAt.AddHours(24);
|
||||
}
|
||||
|
||||
public sealed class SiteHighlight
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string Title { get; init; }
|
||||
|
||||
public required SiteAccount Owner { get; init; }
|
||||
|
||||
public List<SiteStory> Items { get; } = [];
|
||||
}
|
||||
|
||||
public sealed class SiteAccount
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
/// <summary>Current user name (it can change: rename detection).</summary>
|
||||
public required string Username { get; set; }
|
||||
|
||||
public required string DisplayName { get; init; }
|
||||
|
||||
public bool IsPrivate { get; init; }
|
||||
|
||||
/// <summary>Alberto follows this profile.</summary>
|
||||
public bool FollowedByViewer { get; init; }
|
||||
|
||||
/// <summary>This is Alberto's account (the connected one).</summary>
|
||||
public bool IsViewer { get; init; }
|
||||
|
||||
/// <summary>Incremented when the profile picture changes.</summary>
|
||||
public int PictureVersion { get; set; } = 1;
|
||||
|
||||
/// <summary>Posts, newest first.</summary>
|
||||
public List<SitePost> Posts { get; } = [];
|
||||
|
||||
/// <summary>Active stories, oldest first (viewing order).</summary>
|
||||
public List<SiteStory> Stories { get; } = [];
|
||||
|
||||
public List<SiteHighlight> Highlights { get; } = [];
|
||||
|
||||
public string PictureKey => $"ritratto-{Id}-{PictureVersion.ToString(CultureInfo.InvariantCulture)}";
|
||||
|
||||
public DateTimeOffset? LatestStoryAt(DateTimeOffset now) =>
|
||||
Stories.Where(s => s.ExpiresAt > now).Select(s => (DateTimeOffset?)s.PublishedAt).Max();
|
||||
}
|
||||
|
||||
/// <summary>Which tab of a profile.</summary>
|
||||
public enum ProfileTab
|
||||
{
|
||||
Posts,
|
||||
Reels,
|
||||
Tagged,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The synthetic world of the test site, generated from a seed (spec §14.2): Alberto's account, followed and not
|
||||
/// followed profiles, a private one he follows and one he does not, posts with several files, videos, pinned posts,
|
||||
/// stories, highlight collections, tagged posts and reels. Nothing here is real or imitates Instagram's data.
|
||||
/// </summary>
|
||||
/// <remarks>Thread-safety: callers hold <see cref="Gate"/> while reading or changing the world.</remarks>
|
||||
public sealed class World
|
||||
{
|
||||
private const string CodeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
|
||||
|
||||
private static readonly string[] Words =
|
||||
[
|
||||
"mare", "montagna", "colazione", "tramonto", "libro", "gatto", "bicicletta", "concerto", "pioggia", "giardino",
|
||||
"lago", "treno", "mercato", "pane", "neve", "festa", "museo", "ponte", "piazza", "sentiero",
|
||||
];
|
||||
|
||||
private readonly Random _random;
|
||||
private readonly HashSet<string> _codes = new(StringComparer.Ordinal);
|
||||
private long _nextPostId = 3_100_000_000;
|
||||
private long _nextFileId = 5_200_000_000;
|
||||
private long _nextStoryId = 7_300_000_000;
|
||||
private long _nextHighlightId = 8_400_000_000;
|
||||
|
||||
private World(int seed, DateTimeOffset now)
|
||||
{
|
||||
_random = new Random(seed);
|
||||
Seed = seed;
|
||||
CreatedAt = now;
|
||||
}
|
||||
|
||||
public Lock Gate { get; } = new();
|
||||
|
||||
public int Seed { get; }
|
||||
|
||||
public DateTimeOffset CreatedAt { get; }
|
||||
|
||||
public List<SiteAccount> Accounts { get; } = [];
|
||||
|
||||
public SiteAccount Viewer => Accounts.First(a => a.IsViewer);
|
||||
|
||||
/// <summary>Generates the world. <paramref name="now"/> anchors every date (stories are active for 24 hours from it).</summary>
|
||||
public static World Generate(int seed, DateTimeOffset now)
|
||||
{
|
||||
var world = new World(seed, new DateTimeOffset(now.UtcDateTime.Ticks - (now.UtcDateTime.Ticks % TimeSpan.TicksPerSecond), TimeSpan.Zero));
|
||||
world.Build();
|
||||
return world;
|
||||
}
|
||||
|
||||
public SiteAccount? FindByUsername(string username) =>
|
||||
Accounts.FirstOrDefault(a => string.Equals(a.Username, username, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public SiteAccount? FindById(string id) => Accounts.FirstOrDefault(a => a.Id == id);
|
||||
|
||||
public SitePost? FindPost(string code) =>
|
||||
Accounts.SelectMany(a => a.Posts).FirstOrDefault(p => string.Equals(p.Code, code, StringComparison.Ordinal));
|
||||
|
||||
public SiteHighlight? FindHighlight(string id) =>
|
||||
Accounts.SelectMany(a => a.Highlights).FirstOrDefault(h => h.Id == id);
|
||||
|
||||
public SiteFile? FindFile(string mediaKey) =>
|
||||
Accounts.SelectMany(a => a.Posts.SelectMany(p => p.Files)
|
||||
.Concat(a.Stories.Select(s => s.File))
|
||||
.Concat(a.Highlights.SelectMany(h => h.Items.Select(i => i.File))))
|
||||
.FirstOrDefault(f => f.MediaKey == mediaKey);
|
||||
|
||||
/// <summary>Profiles Alberto follows, in the order of his list.</summary>
|
||||
public IReadOnlyList<SiteAccount> Following => [.. Accounts.Where(a => a.FollowedByViewer)];
|
||||
|
||||
/// <summary>Followed profiles with active stories, latest story first (the stories bar).</summary>
|
||||
public IReadOnlyList<SiteAccount> StoryBar(DateTimeOffset now) =>
|
||||
[.. Accounts.Where(a => a.FollowedByViewer && a.LatestStoryAt(now) is not null).OrderByDescending(a => a.LatestStoryAt(now))];
|
||||
|
||||
/// <summary>Recent posts of followed profiles, newest first (the home feed).</summary>
|
||||
public IReadOnlyList<SitePost> Feed() =>
|
||||
[.. Accounts.Where(a => a.FollowedByViewer).SelectMany(a => a.Posts).OrderByDescending(p => p.PublishedAt).ThenBy(p => p.Id, StringComparer.Ordinal)];
|
||||
|
||||
/// <summary>The posts of a profile tab: pinned posts first on the main grid, then newest first.</summary>
|
||||
public IReadOnlyList<SitePost> Grid(SiteAccount account, ProfileTab tab) => tab switch
|
||||
{
|
||||
ProfileTab.Posts => [.. account.Posts.Where(p => p.Pinned).OrderByDescending(p => p.PublishedAt), .. account.Posts.Where(p => !p.Pinned)],
|
||||
ProfileTab.Reels => [.. account.Posts.Where(p => p.IsReel)],
|
||||
ProfileTab.Tagged => [.. Accounts.SelectMany(a => a.Posts).Where(p => p.Tagged.Contains(account)).OrderByDescending(p => p.PublishedAt)],
|
||||
_ => [],
|
||||
};
|
||||
|
||||
/// <summary>A new post on top of an account (control endpoint «pubblica»).</summary>
|
||||
public SitePost Publish(SiteAccount account, string kind, DateTimeOffset at)
|
||||
{
|
||||
var post = NewPost(account, at, kind);
|
||||
account.Posts.Insert(0, post);
|
||||
return post;
|
||||
}
|
||||
|
||||
/// <summary>A new active story (control endpoint «storia»).</summary>
|
||||
public SiteStory AddStory(SiteAccount account, bool video, DateTimeOffset at)
|
||||
{
|
||||
var story = NewStory(account, at, video);
|
||||
account.Stories.Add(story);
|
||||
return story;
|
||||
}
|
||||
|
||||
private void Build()
|
||||
{
|
||||
var now = CreatedAt;
|
||||
var me = Add("1000", "alberto.prova", "Alberto (prova)", followed: false, viewer: true);
|
||||
var marta = Add("1001", "marta.prova", "Marta di prova", followed: true);
|
||||
var luca = Add("1002", "luca.prova", "Luca di prova", followed: true);
|
||||
var giulia = Add("1003", "giulia.prova", "Giulia di prova", followed: true, isPrivate: true);
|
||||
var nadia = Add("1004", "nadia.prova", "Nadia di prova", followed: true);
|
||||
var paolo = Add("1005", "paolo.prova", "Paolo di prova", followed: false);
|
||||
var riservato = Add("1006", "riservato.prova", "Profilo riservato", followed: false, isPrivate: true);
|
||||
for (var i = 1; i <= 24; i++)
|
||||
{
|
||||
var n = i.ToString("00", CultureInfo.InvariantCulture);
|
||||
Add((1100 + i).ToString(CultureInfo.InvariantCulture), $"amico{n}.prova", $"Amico {n}", followed: true);
|
||||
}
|
||||
|
||||
// Posts, oldest first, so that each list ends newest first.
|
||||
AddPosts(me, 4, now.AddDays(-30), TimeSpan.FromDays(5), i => "foto");
|
||||
AddPosts(marta, 18, now.AddDays(-30), TimeSpan.FromHours(38), i => (i % 5) switch { 0 => "serie", 2 => "video", _ => "foto" });
|
||||
AddPosts(luca, 40, now.AddDays(-80), TimeSpan.FromHours(46), i => i % 7 == 3 ? "video" : "foto");
|
||||
AddPosts(giulia, 6, now.AddDays(-20), TimeSpan.FromDays(3), i => i == 2 ? "serie" : "foto");
|
||||
AddPosts(nadia, 3, now.AddDays(-10), TimeSpan.FromDays(3), i => "foto");
|
||||
AddPosts(paolo, 8, now.AddDays(-15), TimeSpan.FromDays(1.5), i => i == 5 ? "serie" : "foto");
|
||||
AddPosts(riservato, 5, now.AddDays(-15), TimeSpan.FromDays(2), i => "foto");
|
||||
foreach (var friend in Accounts.Where(a => a.Username.StartsWith("amico", StringComparison.Ordinal)))
|
||||
{
|
||||
AddPosts(friend, 1 + _random.Next(2), now.AddDays(-40 - _random.Next(20)), TimeSpan.FromDays(4), i => "foto");
|
||||
}
|
||||
|
||||
// Two of Marta's older posts are pinned on top of her grid.
|
||||
marta.Posts[8].Pinned = true;
|
||||
marta.Posts[12].Pinned = true;
|
||||
|
||||
// Tagged posts: Luca and Paolo tag Marta; Marta tags Alberto.
|
||||
luca.Posts[3].Tagged.Add(marta);
|
||||
luca.Posts[9].Tagged.Add(marta);
|
||||
paolo.Posts[2].Tagged.Add(marta);
|
||||
marta.Posts[4].Tagged.Add(me);
|
||||
|
||||
// Stories, oldest first; the bar order is Marta, Nadia, Luca, Giulia.
|
||||
AddStories(marta, now, [-10, -8, -5, -1], videoAt: 2);
|
||||
AddStories(nadia, now, [-6, -4, -2], videoAt: -1);
|
||||
AddStories(luca, now, [-9, -3], videoAt: -1);
|
||||
AddStories(giulia, now, [-20, -16, -12, -8, -4], videoAt: 3);
|
||||
AddStories(paolo, now, [-7], videoAt: -1);
|
||||
|
||||
// Highlights: Marta's «Estate» also holds one of her active stories, with the same identifier (H9).
|
||||
var summer = NewHighlight(marta, "Estate");
|
||||
summer.Items.Add(NewStory(marta, now.AddDays(-60), video: false));
|
||||
summer.Items.Add(NewStory(marta, now.AddDays(-59), video: true));
|
||||
summer.Items.Add(marta.Stories[1]);
|
||||
var travels = NewHighlight(marta, "Viaggi");
|
||||
travels.Items.Add(NewStory(marta, now.AddDays(-90), video: false));
|
||||
travels.Items.Add(NewStory(marta, now.AddDays(-89), video: false));
|
||||
var mountains = NewHighlight(luca, "Montagna");
|
||||
mountains.Items.Add(NewStory(luca, now.AddDays(-120), video: false));
|
||||
mountains.Items.Add(NewStory(luca, now.AddDays(-119), video: false));
|
||||
}
|
||||
|
||||
private SiteAccount Add(string id, string username, string displayName, bool followed, bool viewer = false, bool isPrivate = false)
|
||||
{
|
||||
var account = new SiteAccount
|
||||
{
|
||||
Id = id,
|
||||
Username = username,
|
||||
DisplayName = displayName,
|
||||
FollowedByViewer = followed,
|
||||
IsViewer = viewer,
|
||||
IsPrivate = isPrivate,
|
||||
};
|
||||
Accounts.Add(account);
|
||||
return account;
|
||||
}
|
||||
|
||||
private void AddPosts(SiteAccount account, int count, DateTimeOffset first, TimeSpan step, Func<int, string> kind)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var jitter = TimeSpan.FromMinutes(_random.Next(0, 180));
|
||||
account.Posts.Insert(0, NewPost(account, first + (step * i) + jitter, kind(i)));
|
||||
}
|
||||
}
|
||||
|
||||
private void AddStories(SiteAccount account, DateTimeOffset now, int[] hoursAgo, int videoAt)
|
||||
{
|
||||
for (var i = 0; i < hoursAgo.Length; i++)
|
||||
{
|
||||
account.Stories.Add(NewStory(account, now.AddHours(hoursAgo[i]).AddMinutes(-_random.Next(0, 30)), video: i == videoAt));
|
||||
}
|
||||
}
|
||||
|
||||
private SitePost NewPost(SiteAccount account, DateTimeOffset at, string kind)
|
||||
{
|
||||
var files = kind switch
|
||||
{
|
||||
"serie" => new List<SiteFile> { NewPhoto(960, 1200), NewVideo(720, 1280), NewPhoto(960, 1200) },
|
||||
"video" => [NewVideo(720, 1280)],
|
||||
_ => [NewPhoto(960, 1200)],
|
||||
};
|
||||
return new SitePost
|
||||
{
|
||||
Id = (_nextPostId += 7919 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture),
|
||||
Code = NewCode(),
|
||||
PublishedAt = at,
|
||||
Caption = Caption(),
|
||||
Owner = account,
|
||||
IsReel = kind == "video",
|
||||
Files = files,
|
||||
};
|
||||
}
|
||||
|
||||
private SiteStory NewStory(SiteAccount account, DateTimeOffset at, bool video) => new()
|
||||
{
|
||||
Id = (_nextStoryId += 104_729 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture),
|
||||
PublishedAt = at,
|
||||
Owner = account,
|
||||
File = video ? NewVideo(720, 1280) : NewPhoto(720, 1280),
|
||||
};
|
||||
|
||||
private SiteHighlight NewHighlight(SiteAccount account, string title)
|
||||
{
|
||||
var highlight = new SiteHighlight
|
||||
{
|
||||
Id = (_nextHighlightId += 15_485_863).ToString(CultureInfo.InvariantCulture),
|
||||
Title = title,
|
||||
Owner = account,
|
||||
};
|
||||
account.Highlights.Add(highlight);
|
||||
return highlight;
|
||||
}
|
||||
|
||||
private SiteFile NewPhoto(int width, int height) => new()
|
||||
{
|
||||
Id = (_nextFileId += 1_299_709 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture),
|
||||
IsVideo = false,
|
||||
Width = width,
|
||||
Height = height,
|
||||
};
|
||||
|
||||
private SiteFile NewVideo(int width, int height) => new()
|
||||
{
|
||||
Id = (_nextFileId += 1_299_709 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture),
|
||||
IsVideo = true,
|
||||
Width = width,
|
||||
Height = height,
|
||||
DurationSeconds = 2,
|
||||
};
|
||||
|
||||
private string NewCode()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var chars = new char[7];
|
||||
for (var i = 0; i < chars.Length; i++)
|
||||
{
|
||||
chars[i] = CodeAlphabet[_random.Next(CodeAlphabet.Length)];
|
||||
}
|
||||
|
||||
var code = new string(chars);
|
||||
if (_codes.Add(code))
|
||||
{
|
||||
return code;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string Caption()
|
||||
{
|
||||
var a = Words[_random.Next(Words.Length)];
|
||||
var b = Words[_random.Next(Words.Length)];
|
||||
return $"Una giornata fra {a} e {b} (prova {_random.Next(1, 1000).ToString(CultureInfo.InvariantCulture)})";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user