The bank-transfer block on the order page now gives two ways to pay. First a payto link (RFC 8905) that hands the IBAN, the amount, the account-holder name and the order code to a payment app in one go, then "Or do a manual transfer" with the same details as before. The manual details list the order code as the Description and nothing else. The page used to print the structured RF reference as well, with a paragraph on which code goes in which field, and that read as two codes for one payment. Matching never needed the RF form: the matcher finds the CC- code anywhere in the remittance text, the RF form included. OrderCryptoPay::structuredReference, which only fed that row, is gone; CreditorReferenceFromToken stays, with its unit test. The link is built in the view from the very values the manual details print, so the two cannot disagree. Url() now lets payto: through, like ethereum:, and the name is percent-encoded because Url() strips spaces. ShouldSettleBankTransfers asserts the whole link, including that its message is the reference the matcher looks for. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
538 lines
25 KiB
C++
538 lines
25 KiB
C++
/*
|
|
catcrafts.net
|
|
Copyright (C) 2026 Catcrafts
|
|
|
|
The source code of this website is made available for viewing purposes only.
|
|
No permission is granted to copy, modify, distribute, or create derivative works.
|
|
*/
|
|
|
|
// Content types, and loaders for the two files that stay data.
|
|
//
|
|
// The split: content a person authors (products, projects, legal pages,
|
|
// demos) is compiled in — see :Content — so a typo in it is a build error,
|
|
// not a silently blank page. Content a machine writes at build time stays
|
|
// JSON under content/: posts.json (fetched from the fediverse by CI) and
|
|
// rates.json (ECB rates). Those change without anyone editing C++, so their
|
|
// loaders live here.
|
|
//
|
|
// Both hosts call the same loaders on the same bytes; only where the bytes
|
|
// come from differs. The wasm build gets the files through Crafter.Build's
|
|
// VFS (cfg.files -> files.json -> fetched before _start, readable at the
|
|
// bundle root); the native server reads content/ off disk. So the loaders
|
|
// take text, not paths.
|
|
//
|
|
// Loading never fails hard. These files are generated by our own CI, so a
|
|
// missing or wrong-typed field is a generator bug, and a page rendering with
|
|
// one bad card beats a page that refuses to render at all. Malformed JSON is
|
|
// the one exception — that yields an empty list, because a half-parsed
|
|
// document is worse than none.
|
|
|
|
export module Catcrafts.Shared:Model;
|
|
import std;
|
|
import :Json;
|
|
// For IsValidSlug. A post slug becomes a URL, so it is checked here on the way
|
|
// in rather than trusted because CI wrote it: an unparseable slug would render
|
|
// a "read more" link to a route that can never match, which is a 404 the site
|
|
// links to itself. Dropping it instead degrades to a post with no page.
|
|
import :Route;
|
|
|
|
namespace Catcrafts {
|
|
|
|
// One image or video belonging to a post.
|
|
//
|
|
// `src` is a local path under /media once tools/fetch-media.sh has mirrored it.
|
|
// It can still be an absolute URL if that download failed, which is why the
|
|
// renderer puts it through Url() rather than assuming it is site-relative.
|
|
//
|
|
// Width and height come from ffprobe at mirror time and exist to stop layout
|
|
// shift: without them the browser cannot reserve space, and the text below every
|
|
// card jumps as each file arrives.
|
|
export struct PostMedia {
|
|
std::string src;
|
|
std::string kind; // "image" | "video"
|
|
// Still frame for a video, from the instance's own thumbnail. Without it a
|
|
// <video preload="metadata"> shows a black box until the visitor presses
|
|
// play — and these posts are their video, so the black box is the page.
|
|
// Empty for images, and empty when the instance generated no thumbnail.
|
|
std::string poster;
|
|
// The rendition every browser can take, and the bottom of the format
|
|
// ladder :Media builds. Empty means there is only `src`.
|
|
//
|
|
// video H.264 in MP4, uploaded beside the AV1 by
|
|
// tools/publish-media.sh. Without it a browser lacking AV1
|
|
// (Safari before 17, Apple hardware without the decoder) has an
|
|
// element it cannot play.
|
|
// image PNG, transcoded by tools/fetch-media.sh. It is what the <img>
|
|
// itself points at, so a browser that understands no <source>
|
|
// type at all still gets the picture.
|
|
std::string fallback;
|
|
// AVIF rendition of an image, transcoded by tools/fetch-media.sh. Offered
|
|
// above `src` — it is consistently smaller than the WebP the instances
|
|
// serve, at 4:4:4 chroma so coloured text in a screenshot does not fringe.
|
|
// Empty for videos, and for an image the transcode could not produce.
|
|
std::string avif;
|
|
std::int64_t width = 0;
|
|
std::int64_t height = 0;
|
|
};
|
|
|
|
// A post mirrored from the fediverse (Lemmy).
|
|
//
|
|
// The body IS mirrored — the comments are not. That split is the whole policy:
|
|
// the writing is the work and belongs on the site that is about the work (and
|
|
// is the only version a search engine can be pointed at as canonical), while
|
|
// the discussion belongs to the community that is having it. So every post
|
|
// page carries the full text and then hands off to the thread. No crawling, no
|
|
// comment mirroring, no runtime dependency on the instance.
|
|
//
|
|
// `permalink` is resolved at fetch time to the COMMUNITY's instance, not the
|
|
// author's. Both host a federated copy; the community's is where the discussion
|
|
// actually is, and it is what the site should be pointing readers at.
|
|
export struct Post {
|
|
std::string title;
|
|
// URL-safe name of this post's own page at /posts/<slug>, derived from the
|
|
// title by tools/fetch-posts.sh. Empty only if the title reduced to nothing
|
|
// a slug can be made of, which is what HasPage() below tests for.
|
|
std::string slug;
|
|
std::string permalink; // canonical ap_id on the instance; where "discuss" goes
|
|
std::string linkUrl; // for link posts, the linked target; empty otherwise
|
|
std::string community; // e.g. "linux@lemmy.ml"
|
|
std::string published; // ISO-8601, as emitted by the API
|
|
std::string excerpt; // plain text, truncated by CI — never markdown
|
|
// The full post, still as Markdown. Rendered by :Markdown at page-render
|
|
// time rather than converted to HTML at fetch time, because the renderer is
|
|
// where this codebase's escaping guarantee lives — text that arrives from
|
|
// someone else's server must not become markup anywhere but there.
|
|
std::string body;
|
|
std::int64_t score = 0;
|
|
std::int64_t comments = 0;
|
|
// The post's headline media — `post.url` upstream, the recording or
|
|
// screenshot the post is *about*. Shown on the card and above the body.
|
|
std::vector<PostMedia> media;
|
|
// Files embedded inside the body, mirrored by the same pass. The body text
|
|
// already points at these local paths; this list exists so the renderer can
|
|
// attach dimensions (and a poster, and the H.264 fallback) to them, which
|
|
// Markdown syntax has nowhere to carry.
|
|
std::vector<PostMedia> bodyMedia;
|
|
|
|
// Whether this post gets its own page. A post with no body has nothing to
|
|
// put on one — a page consisting of a title and a link out is thin content
|
|
// that should not be minted as a URL, indexed, or linked to as "read more".
|
|
bool HasPage() const { return !slug.empty() && !body.empty(); }
|
|
};
|
|
|
|
// An entry on the projects page. Repo content, not a database — these change
|
|
// on the order of months.
|
|
//
|
|
// Deliberately shallow: name, one sentence, a link. The Forgejo page is the
|
|
// canonical home for details, so anything richer here (status, feature lists)
|
|
// just drifts out of date against it.
|
|
export struct Project {
|
|
std::string name;
|
|
std::string blurb;
|
|
std::string url;
|
|
std::string language;
|
|
bool featured = false;
|
|
};
|
|
|
|
// Everything the document <head> needs. Emitted server-side once SSR lands;
|
|
// until then catcrafts-head.js sets the title and the rest is unused but
|
|
// carried so the renderers don't need changing later.
|
|
export struct PageMeta {
|
|
std::string title;
|
|
std::string description;
|
|
std::string canonical;
|
|
std::string ogType = "website";
|
|
std::string ogImage;
|
|
bool noindex = false;
|
|
// >0 emits <meta http-equiv="refresh"> — the no-JavaScript way for a page
|
|
// to track changing server state. Used by the order page while a payment
|
|
// is pending; leave 0 everywhere content is static.
|
|
int refreshSeconds = 0;
|
|
// Emits the inline timezone hint script (see RenderDocument): pages that
|
|
// show the dual EU/export price set this so the browser can move the
|
|
// emphasis onto whichever price applies locally. Presentation only — both
|
|
// prices are always in the markup, the HTML is identical for every
|
|
// visitor, and nothing is detected server-side.
|
|
bool geoPriceHint = false;
|
|
// schema.org JSON-LD for this page, already serialized. Emitted verbatim
|
|
// inside <script type="application/ld+json"> — inert data, not code, so
|
|
// it does not count against the shop pages' one-executable-script rule.
|
|
// Set by RenderHome (an @graph of Organization + WebSite: who Catcrafts is
|
|
// and what this domain is, versus the two name-twins), RenderAbout
|
|
// (ProfilePage: who the founder is), RenderShop (ItemList: which product
|
|
// pages exist) and RenderProduct (ProductGroup: what is sold, per colour,
|
|
// at which prices — the same integers the checkout charges). About and
|
|
// the offers reference the home page's Organization by @id rather than
|
|
// restating it — and home's founder references about's Person the same
|
|
// way — so every page describes one entity; see the identity graph in
|
|
// RenderHome for why that join carries the weight it does.
|
|
std::string jsonLd;
|
|
};
|
|
|
|
export struct Spec {
|
|
std::string label;
|
|
std::string value;
|
|
};
|
|
|
|
// A buyable variation of a product — currently colour. Each carries its own
|
|
// VAT-inclusive price because the supplier prices them differently (white
|
|
// costs ~€90 more wholesale than green). The ex-VAT export price is always
|
|
// DERIVED (Money::NetFromGross), never stored.
|
|
export struct Variant {
|
|
std::string slug; // "green" — form value and order-record field
|
|
std::string label; // "Green" — what the buyer reads
|
|
std::int64_t priceInclMinor = 0;
|
|
};
|
|
|
|
export struct Product {
|
|
std::string slug;
|
|
std::string name;
|
|
std::string tagline;
|
|
// The hardware manufacturer, for the Product schema's brand field.
|
|
// Deliberately NOT accompanied by a GTIN: the device is materially
|
|
// modified (different OS), and Google's product-data rules say a
|
|
// customized product must not carry the original manufacturer's GTIN —
|
|
// which also matches the legal framing that this is the manufacturer's
|
|
// device with different software, not a Catcrafts-manufactured one.
|
|
// Empty = omit.
|
|
std::string brand;
|
|
// "available" — buyable now. "coming-soon" — listed with launch prices,
|
|
// orders not open yet. "unavailable" — listed but not sellable (sourcing
|
|
// gap, price swing). In both closed states the page stays up, the buy
|
|
// form does not, and the checkout POST is refused server-side.
|
|
std::string status;
|
|
// A donation rather than goods: the buyer names the amount, nothing ships,
|
|
// and no VAT is charged (a gift with nothing supplied in return is not a
|
|
// taxable supply). This flag is what routes a checkout POST through the
|
|
// donation validator instead of the address-and-shipping one, so setting
|
|
// it on a priced product would let orders skip shipping — it belongs on
|
|
// exactly one kind of catalogue entry.
|
|
bool donation = false;
|
|
// The EU consumer price, VAT-inclusive, in cents. With variants present
|
|
// this is the FROM price (cheapest variant) and is kept in sync by the
|
|
// loader; without variants it is simply the price.
|
|
std::int64_t priceInclMinor = 0;
|
|
std::vector<Variant> variants;
|
|
std::string currency = "EUR";
|
|
// Shipping weight of ONE unit as it leaves here — device, retail box and
|
|
// outer packaging — in grams. There are no shipping prices in this record
|
|
// any more: the carrier prices by weight bracket, so this number plus the
|
|
// quantity is what selects a rate from the live Sendcloud table, and what
|
|
// decides how many units fit one parcel. A destination the carrier has no
|
|
// bracket for is refused at checkout rather than priced from a guess.
|
|
std::int64_t shipWeightGrams = 0;
|
|
// Root-relative path of the product photo, e.g. "/widget.jpg". Served
|
|
// from our own origin like every other asset — the privacy notice's
|
|
// "everything comes from catcrafts.net" applies to product images too.
|
|
std::string image;
|
|
std::string summary;
|
|
std::string warranty;
|
|
// Rendered as a prominent warning box when non-empty. No product sets it
|
|
// today: it existed for the emergency-calling caveat, which came off once
|
|
// 112 was verified on a live network. It stays because the next safety
|
|
// claim — something about safety rather than features — belongs in a
|
|
// warning box above the fold, not in a spec-table row.
|
|
std::string safetyNote;
|
|
std::vector<Spec> specs;
|
|
|
|
// A donation has no fixed price by definition, so the price check applies
|
|
// only to goods — where a zero price is a content bug that must not sell.
|
|
bool Buyable() const {
|
|
return status == "available" && (donation || priceInclMinor > 0);
|
|
}
|
|
bool ComingSoon() const { return status == "coming-soon"; }
|
|
|
|
// nullptr for a colour we never listed — the checkout rejects rather than
|
|
// guessing, so a tampered form value cannot buy an unpriced variant.
|
|
const Variant* FindVariant(std::string_view vslug) const {
|
|
for (const Variant& v : variants) {
|
|
if (v.slug == vslug) return &v;
|
|
}
|
|
return nullptr;
|
|
}
|
|
// The default selection: the cheapest variant, which is also what the
|
|
// "from" price shows — so the page never advertises a number the default
|
|
// choice doesn't honour.
|
|
const Variant* CheapestVariant() const {
|
|
const Variant* best = nullptr;
|
|
for (const Variant& v : variants) {
|
|
if (!best || v.priceInclMinor < best->priceInclMinor) best = &v;
|
|
}
|
|
return best;
|
|
}
|
|
};
|
|
|
|
// ECB euro reference rates, baked in at build time by tools/fetch-rates.sh.
|
|
// Values are integer micro-units of target currency per euro (1 EUR = 1.0834
|
|
// USD -> 1'083'400) — the script does the decimal-to-integer conversion so no
|
|
// float ever touches a money path here. Used ONLY for the indicative national-
|
|
// currency line on the order page; every charge is in euros.
|
|
export struct Rates {
|
|
std::string date; // ECB publication date
|
|
std::vector<std::pair<std::string, std::int64_t>> microPerEur;
|
|
|
|
std::int64_t Find(std::string_view code) const {
|
|
for (const auto& [k, v] : microPerEur) {
|
|
if (k == code) return v;
|
|
}
|
|
return 0;
|
|
}
|
|
};
|
|
|
|
export Rates LoadRates(std::string_view json) {
|
|
Rates out;
|
|
auto doc = Json::Parse(json);
|
|
if (!doc || !doc->IsObject()) return out;
|
|
out.date = std::string(doc->Str("date"));
|
|
if (const Json::Value* m = doc->Find("micro_per_eur"); m && m->IsObject()) {
|
|
for (const auto& [k, v] : m->object) {
|
|
if (v.type == Json::Type::Number && v.number > 0) {
|
|
out.microPerEur.emplace_back(k, static_cast<std::int64_t>(v.number));
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// The bank-derived aggregates for the public /financials page, read from a
|
|
// state file the owner's tooling writes (<orders>.financials.json on the
|
|
// server). Aggregates by construction: a category is a label and a running
|
|
// total, donations are a count and a running total, and nothing finer ever
|
|
// exists in this structure — that is the page's privacy design, not an
|
|
// implementation shortcut. Sales are not in here: they fold live out of the
|
|
// order ledger on the server and arrive at the renderer as two integers.
|
|
export struct FinCategory {
|
|
std::string label; // "Hosting" — shown verbatim
|
|
std::int64_t totalMinor = 0; // running total, EUR cents
|
|
};
|
|
|
|
export struct Financials {
|
|
std::string asOf; // ISO date the figures are current to;
|
|
// empty = nothing published yet
|
|
std::int64_t donationCount = 0;
|
|
std::int64_t donationsMinor = 0;
|
|
// ONE flat list of expense categories. This carried a recurring/one-off
|
|
// split until it was removed deliberately: the page publishes LIFETIME
|
|
// running totals, and a lifetime total cannot express a rate. "Telecom
|
|
// €158.18" says nothing about whether that is monthly or once ever, so
|
|
// the grouping conveyed no information while inviting the reader to infer
|
|
// one. Rate belongs to a cash-flow view this page is not.
|
|
std::vector<FinCategory> expenses;
|
|
|
|
bool Loaded() const { return !asOf.empty(); }
|
|
std::int64_t ExpensesMinor() const {
|
|
std::int64_t sum = 0;
|
|
for (const FinCategory& c : expenses) sum += c.totalMinor;
|
|
return sum;
|
|
}
|
|
};
|
|
|
|
export Financials LoadFinancials(std::string_view json) {
|
|
Financials out;
|
|
auto doc = Json::Parse(json);
|
|
if (!doc || !doc->IsObject()) return out;
|
|
out.asOf = std::string(doc->Str("as_of"));
|
|
// Undated figures stay unpublished: the page promises an honest
|
|
// freshness line, and numbers that cannot carry one are not shown.
|
|
if (out.asOf.empty()) return out;
|
|
if (const Json::Value* d = doc->Find("donations"); d && d->IsObject()) {
|
|
out.donationCount = d->Int("count");
|
|
out.donationsMinor = d->Int("total_minor");
|
|
}
|
|
if (const Json::Value* arr = doc->Find("expenses"); arr && arr->IsArray()) {
|
|
for (const Json::Value& v : arr->array) {
|
|
if (!v.IsObject()) continue;
|
|
FinCategory c;
|
|
c.label = std::string(v.Str("label"));
|
|
c.totalMinor = v.Int("total_minor");
|
|
// A category with no label has nothing to render as; dropping it
|
|
// beats an anonymous row that looks like a redaction.
|
|
if (c.label.empty()) continue;
|
|
out.expenses.push_back(std::move(c));
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// Everything the order status page needs to render — a projection of the
|
|
// server's order record, not the record itself. The renderer stays a pure
|
|
// function in Shared; the server owns storage and fills this in.
|
|
// Self-hosted crypto payment instructions, rendered on the order page when the
|
|
// rail has no hosted checkout to send the buyer to. Everything is pre-formatted
|
|
// text: the renderer should not know what a chain id or a token decimal is, any
|
|
// more than it knows where ECB rates come from.
|
|
export struct OrderCryptoPay {
|
|
std::string address; // where the money goes: "0x…", or an IBAN
|
|
std::string amount; // decimal EURC amount ("570.43") — equals the
|
|
// euro total; EURC is euro-denominated at par
|
|
std::int64_t minutesLeft = 0; // until the window closes; <= 0 = closed
|
|
|
|
// ── bank transfer instead of on-chain ─────────────────────────────
|
|
//
|
|
// Both live rails are self-hosted, so both render instructions here rather
|
|
// than a button. Non-empty `beneficiary` is what marks this a bank
|
|
// transfer: `address` is then an IBAN, `chains` is empty, and the copy
|
|
// must not mention networks or tokens.
|
|
//
|
|
// The name is not decoration. Since 2025-10-09 every euro-area transfer is
|
|
// name-checked against the IBAN by Verification of Payee, and the payer
|
|
// gets a mismatch warning mid-payment if what we printed is not what the
|
|
// bank holds. Printing a friendly trading name here would scare buyers off
|
|
// at the last step, so this carries the bank's own spelling.
|
|
std::string beneficiary;
|
|
// Shown only when configured, and labelled as the field a payer sending
|
|
// from OUTSIDE SEPA needs. An IBAN alone has been sufficient within SEPA
|
|
// since 2016, so putting a BIC in front of a Dutch buyer is one more box
|
|
// to fill and one more thing to mistype.
|
|
std::string bic;
|
|
// The transfer is visible on the network but not yet in a finalized
|
|
// block. Display-only: the buyer whose wallet said "success" needs to
|
|
// hear "we see it, it is finalizing" or their next step is a support
|
|
// email — the first live payment proved exactly this.
|
|
bool seen = false;
|
|
struct Chain {
|
|
std::string name; // "base"
|
|
std::string contract; // token contract, shown so the buyer can verify
|
|
std::string link; // EIP-681 wallet URI; empty = no link rendered
|
|
std::string note; // short hint ("lowest fees"), may be empty
|
|
};
|
|
std::vector<Chain> chains; // in display order — first is the recommended one
|
|
};
|
|
|
|
export struct OrderView {
|
|
std::string token; // the capability that IS the URL — never logged
|
|
std::string reference; // short human code, quoted in the bank transfer
|
|
std::string status; // "awaiting_payment" | "paid" | "shipped" | "cancelled"
|
|
std::string productName;
|
|
std::string colorLabel; // "Forest Green", empty for variantless products
|
|
std::int64_t quantity = 1;
|
|
std::int64_t unitMinor = 0;
|
|
std::string payUrl; // the provider's hosted checkout; empty once paid
|
|
// or when cancelled
|
|
std::string payChoice; // Form::kPayBank | Form::kPayCrypto — decides what
|
|
// the "resume payment" copy promises is waiting
|
|
// there. Anything but crypto reads as bank.
|
|
std::string createdAt; // ISO 8601, shown verbatim
|
|
std::string country;
|
|
std::int64_t goodsMinor = 0;
|
|
std::int64_t shippingMinor = 0;
|
|
std::int64_t totalMinor = 0;
|
|
bool vatIncluded = false;
|
|
// A donation order: one amount, nothing ships, no VAT, no invoice. The
|
|
// renderer folds the money table to a single row and swaps the paid-state
|
|
// copy from "your device ships" to a thank-you.
|
|
bool donation = false;
|
|
// Present only for an awaiting order on a rail without a hosted checkout;
|
|
// the page then renders instructions instead of a "resume payment" button.
|
|
std::optional<OrderCryptoPay> cryptoPay;
|
|
};
|
|
|
|
// An entry on the demos page.
|
|
//
|
|
// `needsWasm` is what decides whether a page ships the ~239 KB module, so it is
|
|
// data rather than a hardcoded route check: adding a demo that needs the
|
|
// renderer, or one that does not, should not require touching the server.
|
|
export struct Demo {
|
|
std::string slug;
|
|
std::string name;
|
|
std::string blurb;
|
|
std::string tech;
|
|
std::string needs; // what the browser must support, in plain words ("requires" is a keyword)
|
|
std::string mountId; // element id the renderer reparents its canvas into
|
|
std::string aspect; // CSS aspect-ratio for the mount box
|
|
bool needsWasm = false;
|
|
};
|
|
|
|
// A legal / informational page. Sections of headed paragraphs rather than
|
|
// markdown: these are written once and read rarely, and a prose format would
|
|
// mean carrying a markdown renderer for four pages.
|
|
export struct LegalSection {
|
|
std::string heading;
|
|
std::vector<std::string> body;
|
|
};
|
|
|
|
export struct LegalPage {
|
|
std::string slug;
|
|
std::string title;
|
|
std::string updated; // ISO date, shown to the reader
|
|
std::string lede;
|
|
std::vector<LegalSection> sections;
|
|
};
|
|
|
|
// ── loaders ───────────────────────────────────────────────────────────
|
|
|
|
// The media array shape, shared by a post's headline media and its body media —
|
|
// they are the same records produced by the same mirror pass, so they are read
|
|
// by one function rather than two that could drift.
|
|
std::vector<PostMedia> LoadPostMedia(const Json::Value* array) {
|
|
std::vector<PostMedia> out;
|
|
if (!array || !array->IsArray()) return out;
|
|
for (const Json::Value& mv : array->array) {
|
|
if (!mv.IsObject()) continue;
|
|
PostMedia pm;
|
|
pm.src = std::string(mv.Str("src"));
|
|
pm.kind = std::string(mv.Str("kind", "image"));
|
|
pm.poster = std::string(mv.Str("poster"));
|
|
pm.fallback = std::string(mv.Str("fallback"));
|
|
pm.avif = std::string(mv.Str("avif"));
|
|
pm.width = mv.Int("w");
|
|
pm.height = mv.Int("h");
|
|
// Only the two kinds the renderer knows how to emit. Anything else
|
|
// would fall through to an <img> for a file that is not an image, so
|
|
// treat it as image only when it says so.
|
|
if (pm.kind != "image" && pm.kind != "video") pm.kind = "image";
|
|
if (pm.src.empty()) continue;
|
|
out.push_back(std::move(pm));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export std::vector<Post> LoadPosts(std::string_view json) {
|
|
std::vector<Post> out;
|
|
auto doc = Json::Parse(json);
|
|
if (!doc || !doc->IsArray()) return out;
|
|
out.reserve(doc->array.size());
|
|
for (const Json::Value& item : doc->array) {
|
|
if (!item.IsObject()) continue;
|
|
Post p;
|
|
p.title = std::string(item.Str("title"));
|
|
if (const std::string_view slug = item.Str("slug"); IsValidSlug(slug)) {
|
|
p.slug = std::string(slug);
|
|
}
|
|
p.permalink = std::string(item.Str("permalink"));
|
|
p.linkUrl = std::string(item.Str("url"));
|
|
p.community = std::string(item.Str("community"));
|
|
p.published = std::string(item.Str("published"));
|
|
p.excerpt = std::string(item.Str("excerpt"));
|
|
p.body = std::string(item.Str("body"));
|
|
p.score = item.Int("score");
|
|
p.comments = item.Int("comments");
|
|
p.media = LoadPostMedia(item.Find("media"));
|
|
p.bodyMedia = LoadPostMedia(item.Find("body_media"));
|
|
// A post with no title and nowhere to click is not renderable; drop it
|
|
// rather than emit an empty card.
|
|
if (p.title.empty() && p.permalink.empty()) continue;
|
|
out.push_back(std::move(p));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ── formatting helpers ────────────────────────────────────────────────
|
|
|
|
// "2026-07-18T14:03:22.123456Z" -> "2026-07-18".
|
|
//
|
|
// Deliberately not a date parser. The only thing the UI needs is the day, the
|
|
// API always emits ISO-8601, and pulling in civil-time handling to render ten
|
|
// characters would be the wrong trade. Anything unexpected is passed through
|
|
// unchanged so a format change shows up as visibly odd text rather than a
|
|
// silently wrong date.
|
|
export std::string_view DateOnly(std::string_view iso) {
|
|
if (iso.size() >= 10 && iso[4] == '-' && iso[7] == '-') return iso.substr(0, 10);
|
|
return iso;
|
|
}
|
|
|
|
} // namespace Catcrafts
|