Files
Dreierpack-Manager/src/modern/ui/demo_news.cpp
T

426 lines
17 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/demo_news.hpp"
#include "modern/ui/demo_career.hpp"
#include "modern/ui/news_journal.hpp"
#include <algorithm>
#include <array>
#include <cctype>
#include <chrono>
#include <iomanip>
#include <optional>
#include <set>
#include <sstream>
namespace bmh::modern_ui {
namespace {
bool news_keys(const Json &v, std::initializer_list<const char *> expected) {
return v.is_object() && v.size() == expected.size() &&
std::all_of(expected.begin(), expected.end(),
[&](auto *key) { return v.contains(key); });
}
bool news_text(const Json &v, size_t cap, bool nonempty = false) {
if (!v.is_string())
return false;
const auto &s = v.get_ref<const std::string &>();
return s.size() <= cap && s.find('\0') == s.npos &&
(!nonempty || s.find_first_not_of(" \t\r\n") != s.npos);
}
bool news_id(const Json &v) {
if (!news_text(v, 64, true))
return false;
const auto &s = v.get_ref<const std::string &>();
return s.find_first_not_of("abcdefghijklmnopqrstuvwxyz0123456789-") == s.npos;
}
bool news_folder(const Json &v, bool trash = true) {
return v == "inbox" || v == "archive" || (trash && v == "trash");
}
std::optional<std::chrono::sys_days> news_date(const std::string &value) {
using namespace std::chrono;
if (value.size() != 10 || value[4] != '-' || value[7] != '-')
return {};
for (size_t i = 0; i < value.size(); ++i)
if (i != 4 && i != 7 && (value[i] < '0' || value[i] > '9'))
return {};
const int y = std::stoi(value.substr(0, 4)),
m = std::stoi(value.substr(5, 2)),
d = std::stoi(value.substr(8, 2));
const year_month_day date{year{y}, month{unsigned(m)}, day{unsigned(d)}};
if (y < 1 || y > 9999 || !date.ok())
return {};
return sys_days{date};
}
std::string news_iso(std::chrono::sys_days date) {
const std::chrono::year_month_day d{date};
std::ostringstream out;
out << std::setfill('0') << std::setw(4) << int(d.year()) << '-'
<< std::setw(2) << unsigned(d.month()) << '-' << std::setw(2)
<< unsigned(d.day());
return out.str();
}
std::string news_category(const std::string &kind) {
if (kind == "club")
return "Verein";
if (kind == "fixture")
return "Spielbetrieb";
if (kind == "transfer")
return "Personal";
if (kind == "finance")
return "Finanzen";
if (kind == "training")
return "Training";
if (kind == "stadium")
return "Stadion";
if (kind == "national")
return "Nationalteam";
if (kind == "indoor")
return "Halle";
if (kind == "career")
return "Karriere";
return {};
}
std::string news_replace(std::string text, const std::string &key,
const std::string &value) {
size_t at = 0;
while ((at = text.find(key, at)) != text.npos) {
text.replace(at, key.size(), value);
at += value.size();
}
return text;
}
std::string news_fold(std::string text) {
for (auto &ch : text)
if (static_cast<unsigned char>(ch) < 128)
ch = char(std::tolower(static_cast<unsigned char>(ch)));
for (const auto &[a, b] :
std::array<std::pair<const char *, const char *>, 4>{
{{"Ä", "ä"}, {"Ö", "ö"}, {"Ü", "ü"}, {"ẞ", "ß"}}})
text = news_replace(std::move(text), a, b);
return text;
}
Json news_pair(const Json &item) {
return {{"read", item.at("read")}, {"folder", item.at("folder")}};
}
bool news_valid_pair(const Json &v) {
return news_keys(v, {"read", "folder"}) && v.at("read").is_boolean() &&
news_folder(v.at("folder"));
}
} // namespace
Json demo_news_scope(const Json &state, const Catalog *world) {
try {
if (state.value("career", Json::object()).value("ended", false) ||
!state.contains("managers") || state.at("managers").empty())
return Json();
const auto &m = demo_career_manager(state);
const auto role = state.value("career", Json::object())
.value("role", state.value("edits", Json::object())
.value("setup", Json::object())
.value("league", true)
? "club"
: "national");
if (role == "national")
return {{"kind", "national"},
{"id", "national-de"},
{"name", "Deutschland"},
{"names", {{"de", "Deutschland"}, {"en", "Germany"}}}};
if (role != "club" || !m.contains("club") || !m.at("club").is_string())
return Json();
const auto id = m.at("club").get<std::string>();
const auto *c = world ? world->find("clubs", id) : nullptr;
return {{"kind", "club"}, {"id", id}, {"name", c ? world->name(*c) : id}};
} catch (...) {
return Json();
}
}
std::string news_display_date(const std::string &s) {
return news_date(s)
? s.substr(8, 2) + "." + s.substr(5, 2) + "." + s.substr(0, 4)
: s;
}
Json demo_news(const Catalog &world, const Json &state) {
const auto value =
state.value("date", world.manifest().value("start_date", std::string()));
const auto today = news_date(value);
if (!today)
throw editor::Error("invalid_news_date");
struct Fixture {
const char *id;
int ago;
const char *kind, *title, *body;
bool read;
const char *folder;
};
const std::array<Fixture, 12> fixtures{
{{"season", 0, "club", "Die neue Saison kann kommen",
"Willkommen zurück, {{manager}}. {{club}} startet in die "
"Saisonvorbereitung. Mannschaft, Verein und Fans blicken voller "
"Vorfreude auf die neue Spielzeit.",
false, "inbox"},
{"cup", 0, "fixture", "Der Pokal schreibt seine eigenen Geschichten",
"64 Mannschaften, 32 Paarungen und ein gemeinsames Ziel: das Finale. "
"Die erste Runde eröffnet die neue Pokalsaison.",
false, "inbox"},
{"contract", 1, "transfer", "Vertragsgespräche stehen an",
"Nico Brandt möchte seine Zukunft frühzeitig klären. Die sportliche "
"Leitung plant ein Gespräch mit dem Torwart über seine Rolle im Kader.",
false, "inbox"},
{"tickets", 1, "finance", "8.320 Dauerkarten für die neue Saison",
"Der Vorverkauf läuft gut: 8.320 Fans haben sich bereits ihren "
"Stammplatz gesichert. Die fiktiven Einnahmen aus dem "
"Dauerkartenverkauf betragen 1.450.000 €.",
false, "inbox"},
{"camp", 2, "training", "Die Vorbereitung nimmt Fahrt auf",
"Ein Trainingslager bietet Raum für Kondition, Technik und Teamgeist. "
"Das Trainerteam hat erste Ziele für die gemeinsame Vorbereitung "
"zusammengestellt.",
false, "inbox"},
{"shirt", 3, "finance", "Neue Optionen für die Trikotwerbung",
"Mehrere Unternehmen interessieren sich für eine Partnerschaft mit "
"{{club}}. Die Angebote können in Ruhe geprüft und verglichen werden.",
true, "inbox"},
{"friendly", 4, "fixture", "Ein erster Härtetest für die Mannschaft",
"Ein Testspiel steht auf dem Vorbereitungsplan. Das Trainerteam möchte "
"möglichst vielen Spielern Einsatzzeit geben.",
true, "inbox"},
{"pitch", 5, "stadium", "Der Rasen ist bereit für den Saisonstart",
"Die Platzpflege hat die Sommerpause genutzt. Der Rasen präsentiert "
"sich zum Trainingsauftakt in gutem Zustand.",
true, "inbox"},
{"fans", 6, "club", "Vorfreude auf den Rängen",
"Die Fans von {{club}} stimmen sich auf die neue Saison ein. Zum "
"Trainingsauftakt werden zahlreiche Besucher erwartet.",
true, "inbox"},
{"review", 7, "fixture", "Die Saison im Rückblick",
"Spannende Spiele, große Gefühle und viele gemeinsame Momente: Eine "
"ereignisreiche Spielzeit liegt hinter dem Verein.",
true, "archive"},
{"planning", 9, "transfer", "Sommerplanung mit klarem Kurs",
"Die sportliche Leitung hat die Aufgaben für die Sommerpause "
"zusammengestellt. Im Mittelpunkt stehen die Kaderplanung und die "
"Entwicklung junger Spieler.",
true, "archive"},
{"together", 12, "club", "Gemeinsam in die nächste Spielzeit",
"Vorstand und Trainerteam bedanken sich bei Mannschaft, Mitarbeitern "
"und Fans für ihre Unterstützung.",
true, "archive"}}};
Json items = Json::array();
for (const auto &f : fixtures) {
const auto day = *today - std::chrono::days{f.ago};
if (int(std::chrono::year_month_day{day}.year()) < 1)
throw editor::Error("invalid_news_date");
items.push_back({{"id", f.id},
{"date", news_iso(day)},
{"kind", f.kind},
{"title", f.title},
{"body", f.body},
{"read", f.read},
{"folder", f.folder}});
}
const auto scope = demo_news_scope(state, &world);
// These old authored fixtures are specifically club stories. Do not invent
// national equivalents or republish club finances under a national header.
if (scope.is_null() || scope.at("kind") != "club")
return empty_news_journal();
const auto &manager = demo_career_manager(state);
return bind_created_news(
items, scope,
{{"id", "portrait:" + std::to_string(manager.value("portrait", 0))},
{"name", manager.value("name", std::string())}});
}
bool valid_demo_news(const Json &state) {
try {
const auto &news = state.at("news");
if (news.value("version", 0) == 2)
return valid_news_journal(news);
if (!news_keys(news, {"version", "items"}) ||
!news.at("version").is_number_integer() || news.at("version") != 1 ||
!news.at("items").is_array() || news.at("items").size() > 100)
return false;
std::set<std::string> ids;
for (const auto &m : news.at("items")) {
if (!news_keys(
m, {"id", "date", "kind", "title", "body", "read", "folder"}) ||
!news_id(m.at("id")) ||
!ids.insert(m.at("id").get<std::string>()).second ||
!m.at("date").is_string() ||
!news_date(m.at("date").get<std::string>()) ||
!m.at("kind").is_string() ||
news_category(m.at("kind").get<std::string>()).empty() ||
!news_text(m.at("title"), 160, true) ||
!news_text(m.at("body"), 1200) || !m.at("read").is_boolean() ||
!news_folder(m.at("folder")))
return false;
}
return true;
} catch (const std::exception &) {
return false;
}
}
bool migrate_demo_news(Json &state, const Catalog &world) {
try {
if (!state.is_object())
return false;
if (state.contains("news")) {
if (!valid_demo_news(state))
return false;
auto proposed = state.at("news");
if (!migrate_news_journal(proposed))
return false;
state["news"] = std::move(proposed);
return true;
}
auto next = state;
next["news"] = demo_news(world, state);
if (!valid_demo_news(next))
return false;
state = std::move(next);
return true;
} catch (const std::exception &) {
return false;
}
}
std::string edit_demo_news(Json &state, const Json &action, const Catalog &) {
if (!valid_demo_news(state) || state.at("news").at("version") != 2)
return "invalid_news_state";
try {
if (!action.is_object() || !action.contains("kind") ||
!action.at("kind").is_string())
return "invalid_news_action";
const auto kind = action.at("kind").get<std::string>();
auto next = state;
const auto scope = demo_news_scope(state);
auto &items = next["news"]["items"];
if (kind == "read-all") {
if (!news_keys(action, {"kind", "folder"}) ||
!news_folder(action.at("folder"), false))
return "invalid_news_action";
for (auto &item : items)
if (item.at("folder") == action.at("folder") &&
news_row_visible(item, scope))
item["read"] = true;
} else if (kind == "read" || kind == "move") {
if (!(kind == "read" ? news_keys(action, {"kind", "id"})
: news_keys(action, {"kind", "id", "folder"})) ||
!news_id(action.at("id")) ||
(kind == "move" && !news_folder(action.at("folder"))))
return "invalid_news_action";
auto found = std::find_if(items.begin(), items.end(), [&](const auto &m) {
return m.at("id") == action.at("id") && news_row_visible(m, scope);
});
if (found == items.end() || found->at("folder") == "trash")
return "news_not_found";
if (kind == "read")
(*found)["read"] = true;
else {
(*found)["folder"] = action.at("folder");
if (action.at("folder") != "trash")
(*found)["read"] = true;
}
} else if (kind == "undo") {
if (!news_keys(action, {"kind", "patch"}) ||
!action.at("patch").is_array() || action.at("patch").empty() ||
action.at("patch").size() > 100)
return "invalid_news_action";
std::set<std::string> ids;
for (const auto &p : action.at("patch")) {
if (!news_keys(p, {"id", "before", "after"}) || !news_id(p.at("id")) ||
!ids.insert(p.at("id").get<std::string>()).second ||
!news_valid_pair(p.at("before")) ||
!news_valid_pair(p.at("after")) || p.at("before") == p.at("after"))
return "invalid_news_action";
auto found =
std::find_if(items.begin(), items.end(), [&](const auto &m) {
return m.at("id") == p.at("id") && news_row_visible(m, scope);
});
if (found == items.end() || news_pair(*found) != p.at("after"))
return "news_undo_conflict";
(*found)["read"] = p.at("before").at("read");
(*found)["folder"] = p.at("before").at("folder");
}
} else
return "invalid_news_action";
if (!valid_demo_news(next))
return "invalid_news_state";
state = std::move(next);
return {};
} catch (const std::exception &) {
return "invalid_news_action";
}
}
int demo_news_unread(const Json &state) {
if (!valid_demo_news(state))
return 0;
int count = 0;
for (const auto &m : state.at("news").at("items"))
if (m.at("folder") == "inbox" && !m.at("read").get<bool>() &&
news_row_visible(m, demo_news_scope(state)))
++count;
return count;
}
Json demo_news_view(const Catalog &world, const Json &state,
const std::string &folder, const std::string &query,
const std::string &language) {
if (!valid_demo_news(state) || (folder != "inbox" && folder != "archive") ||
query.size() > 120 || (language != "de" && language != "en"))
return {{"ok", false}, {"error", "invalid_news_view"}};
const auto scope = demo_news_scope(state, &world);
const auto &person =
state.contains("managers") && !state.at("managers").empty()
? demo_career_manager(state)
: Json::object();
const auto manager = person.value("name", std::string()),
club_id = scope.is_object() ? scope.value("id", std::string())
: std::string(),
club_name = scope.is_object() ? scope.value("name", std::string())
: std::string();
Json shown = Json::array(), counts = {{"inbox", 0}, {"archive", 0}};
bool can_read = false;
for (auto m : state.at("news").at("items")) {
const auto location = m.at("folder").get<std::string>();
if (location == "trash" || !news_row_visible(m, scope))
continue;
counts[location] = counts.at(location).get<int>() + 1;
if (location != folder)
continue;
if (!m.at("read").get<bool>())
can_read = true;
const auto rendered = news_row_text(m, language);
m["title"] = rendered.at("title");
m["body"] = rendered.at("body");
m["category"] = news_category(m.at("kind").get<std::string>());
m["display_date"] = news_display_date(m.at("date").get<std::string>());
const auto haystack = news_fold(m.at("title").get<std::string>() + " " +
m.at("body").get<std::string>() + " " +
m.at("category").get<std::string>() + " " +
m.at("display_date").get<std::string>());
if (query.empty() || haystack.find(news_fold(query)) != haystack.npos)
shown.push_back(std::move(m));
}
std::stable_sort(shown.begin(), shown.end(),
[](const auto &a, const auto &b) {
return a.at("date").template get<std::string>() >
b.at("date").template get<std::string>();
});
int unread = 0;
for (const auto &m : shown)
if (!m.at("read").get<bool>())
++unread;
return {{"ok", true},
{"fictional", true},
{"items", shown},
{"counts", counts},
{"unread", demo_news_unread(state)},
{"shown_unread", unread},
{"can_read", can_read},
{"club", club_id},
{"club_name", club_name},
{"manager", manager},
{"date", news_display_date(state.value("date", std::string()))},
{"scope", scope},
{"unbound_count", state.at("news").value("version", 1) == 2
? state.at("news").at("unbound").size()
: state.at("news").at("items").size()}};
}
} // namespace bmh::modern_ui