// SPDX-License-Identifier: GPL-3.0-only // The engine's kickoff recording, shaped for the live ticker. Nothing here simulates or // estimates: the recording is copied, its phases and tables are renamed to the ticker's // vocabulary and the desk manager's squad is attached for the team tab. #include "modern/ui/engine_live.hpp" #include #include #include #include namespace bmh::modern_ui { namespace { Json failure(const std::string &error) { return {{"ok", false}, {"error", error}}; } bool text(const Json &v, size_t max = 400) { return v.is_string() && v.get_ref().size() <= max; } bool count(const Json &v, uint64_t max = 1000000) { return v.is_number_integer() && v.get() >= 0 && uint64_t(v.get()) <= max; } bool team_ok(const Json &v) { return v.is_object() && text(v.at("id")) && !v.at("id").get_ref().empty() && text(v.at("name")); } Json metric(const Json &player, const char *key) { try { const auto &value = player.at("metrics").at(key).at("value"); return value.is_number_integer() ? value : Json(); } catch (const std::exception &) { return Json(); } } } // namespace Json engine_advance_command(const Json &bundle, const std::string &request_id, const Json &payload) { validate_engine_desk(bundle); if (request_id.empty()) throw editor::Error("Anfrage-ID fehlt."); const auto &meta = bundle.at("desktop").at("meta"); const auto commands = meta.at("scope").value("allowedCommands", Json::array()); if (!commands.is_array() || std::find(commands.begin(), commands.end(), Json("session.advance")) == commands.end()) throw editor::Error("Der Anstoß ist in diesem Kontext gesperrt."); return {{"messageType", "command"}, {"contractVersion", meta.at("contractVersion")}, {"requestId", request_id}, {"careerId", meta.at("careerId")}, {"expectedRevision", meta.at("stateRevision")}, {"owner", {{"managerId", meta.at("scope").at("managerId")}}}, {"kind", "session.advance"}, {"payload", payload.is_object() ? payload : Json::object()}}; } bool valid_engine_live_fixture(const Json &v) { try { if (!v.is_object() || !v.value("ok", false) || v.at("schema") != "openbmh-live-fixture@1" || v.at("source") != "engine-recording" || !text(v.at("fixture_id")) || !count(v.at("source_revision"), UINT64_MAX >> 1) || !v.at("owners").is_array() || v.at("owners").empty() || v.at("owners").size() > 4 || !v.at("matches").is_array() || v.at("matches").empty() || v.at("matches").size() > 16 || !v.at("frames").is_array() || v.at("frames").size() < 2 || v.at("frames").size() > 2000 || !count(v.at("duration"), 200) || !count(v.at("field_count"), 11) || (v.at("role") != "club" && v.at("role") != "national") || (v.at("surface") != "outdoor" && v.at("surface") != "indoor")) return false; std::set match_ids, owner_ids; for (const auto &match : v.at("matches")) { if (!text(match.at("id")) || !match_ids.insert(match.at("id")).second || !team_ok(match.at("home")) || !team_ok(match.at("away")) || !match.at("owners").is_array()) return false; for (const auto &id : match.at("owners")) if (!id.is_string()) return false; } for (const auto &owner : v.at("owners")) { if (!text(owner.at("id")) || !owner_ids.insert(owner.at("id")).second || !text(owner.at("name")) || !count(owner.at("portrait"), 11) || !team_ok(owner.at("team")) || !match_ids.contains(owner.at("match_id")) || !owner.at("view").is_object() || owner.at("view").at("engine") != true || !owner.at("view").at("rows").is_array() || owner.at("view").at("rows").size() > 64) return false; for (const auto &row : owner.at("view").at("rows")) if (!text(row.at("id")) || !text(row.at("name")) || !row.contains("strength") || !row.contains("condition")) return false; } const int64_t duration = v.at("duration"); int64_t minute = -1; size_t sequence = 0; for (const auto &frame : v.at("frames")) { if (frame.at("sequence") != sequence++ || !count(frame.at("minute"), uint64_t(duration)) || frame.at("minute").get() < minute || !frame.at("events").is_array() || frame.at("events").size() > 8000 || !frame.at("matches").is_array() || frame.at("matches").size() != match_ids.size()) return false; minute = frame.at("minute"); const auto phase = frame.value("phase", ""); if (phase != "first_half" && phase != "interval" && phase != "second_half" && phase != "extra_time" && phase != "shootout" && phase != "finished") return false; // a kickoff still under way has no final frame yet if (v.value("live_running", false) ? phase == "finished" : (phase == "finished") != (sequence == v.at("frames").size())) return false; std::set scored; for (const auto &m : frame.at("matches")) { if (!match_ids.contains(m.at("match_id")) || !scored.insert(m.at("match_id")).second) return false; for (auto key : {"score", "chances", "yellow", "red", "players"}) if (!m.at(key).is_array() || m.at(key).size() != 2 || !count(m.at(key)[0], 1000) || !count(m.at(key)[1], 1000)) return false; if (!m.at("standings").is_array() || m.at("standings").size() > 128) return false; for (const auto &row : m.at("standings")) { if (!team_ok(row.at("team"))) return false; for (auto key : {"position", "played", "gf", "ga", "points"}) if (!count(row.at(key))) return false; } } for (const auto &event : frame.at("events")) if (!text(event.at("id")) || !match_ids.contains(event.at("match_id")) || !count(event.at("minute"), 200) || !text(event.at("headline")) || !text(event.at("body"), 2200) || !text(event.at("kind"), 40) || (event.at("side") != "home" && event.at("side") != "away") || !event.at("score").is_array() || event.at("score").size() != 2 || !count(event.at("score")[0], 1000) || !count(event.at("score")[1], 1000)) return false; } return true; } catch (const std::exception &) { return false; } } Json engine_live_fixture(const Json &recording, const Json &bundle) { try { if (!recording.is_object()) return failure("live_unavailable"); if (!recording.value("ok", false)) return failure(recording.value("error", "live_unavailable")); Json out = recording; out["source"] = "engine-recording"; const std::string role = out.value("role", "club") == "national" ? "national" : "club"; out["role"] = role; if (!out.contains("surface")) out["surface"] = "outdoor"; if (!out.contains("date")) out["date"] = ""; try { out["world"] = bundle.at("desktop").at("meta").at("worldId"); } catch (const std::exception &) { out["world"] = ""; } // The desk manager's squad in line-up order (the squad after the kickoff). std::string desk_team; Json rows = Json::array(); try { desk_team = bundle.at("desktop").at("meta").at("scope").at("teamId").get(); const auto &players = bundle.at("squad").at("data").at("players"); std::map by_id; std::vector listed; for (const auto &p : players) { const std::string id = p.at("player").at("id"); by_id[id] = &p; listed.push_back(id); } std::vector order; try { for (const auto &id : bundle.at("lineup").at("data").at("order")) if (id.is_string()) order.push_back(id); } catch (const std::exception &) {} std::set seen; const auto add = [&](const std::string &id) { const auto at = by_id.find(id); if (at == by_id.end() || !seen.insert(id).second) return; const auto &p = *at->second; rows.push_back({{"id", id}, {"name", p.at("player").at("name")}, {"slot", rows.size()}, {"strength", metric(p, "strength")}, {"condition", metric(p, "condition")}, {"position", p.at("player").value("positions", Json::array()).empty() ? Json() : p.at("player").at("positions").front()}, {"caps", nullptr}, {"international_goals", nullptr}}); }; for (const auto &id : order) add(id); for (const auto &id : listed) add(id); } catch (const std::exception &) { rows = Json::array(); } if (!out.at("owners").is_array() || out.at("owners").empty()) return failure("live_no_human_match"); std::set portraits; for (auto &owner : out.at("owners")) { int portrait = owner.value("portrait", 0); portrait = std::clamp(portrait, 0, 11); for (int tries = 0; tries < 12 && portraits.contains(portrait); ++tries) portrait = (portrait + 1) % 12; portraits.insert(portrait); owner["portrait"] = portrait; if (!owner.at("team").contains("role")) owner["team"]["role"] = role; const bool own = owner.at("team").at("id") == desk_team; owner["view"] = {{"ok", true}, {"engine", true}, {"rows", own ? rows : Json::array()}, {"field_count", out.value("field_count", 11)}}; } for (auto &match : out.at("matches")) { for (auto side : {"home", "away"}) if (!match.at(side).contains("role")) match[side]["role"] = role; if (!match.contains("owners") || !match.at("owners").is_array()) match["owners"] = Json::array(); } // Tables arrive on the frame when they change; the ticker wants each match's table. std::map tables; // competition id -> ticker rows const int64_t duration = out.value("duration", 90); auto &frames = out.at("frames"); for (size_t i = 0; i < frames.size(); ++i) { auto &frame = frames[i]; const std::string phase = frame.value("phase", ""); const bool last = i + 1 == frames.size(); frame["phase"] = last ? "finished" : phase == "kickoff" ? "first_half" : phase == "restart" ? "second_half" : phase == "fulltime" || phase == "shootout_end" || phase == "finished" ? "second_half" : phase; if (frame.at("minute").is_number_integer()) frame["minute"] = std::clamp(frame.at("minute").get(), 0, duration); if (frame.contains("standings") && frame.at("standings").is_array()) for (const auto &table : frame.at("standings")) { if (!table.is_object() || !table.contains("rows")) continue; Json converted = Json::array(); for (const auto &row : table.at("rows")) { Json team = row.at("team"); team["role"] = "club"; converted.push_back({{"team", team}, {"position", row.at("rank")}, {"played", row.at("played")}, {"gf", row.at("goalsFor")}, {"ga", row.at("goalsAgainst")}, {"points", row.at("points")}, {"won", row.value("won", Json())}, {"drawn", row.value("drawn", Json())}, {"lost", row.value("lost", Json())}}); } tables[table.value("competitionId", std::string("table"))] = std::move(converted); } for (auto &score : frame.at("matches")) { score["standings"] = Json::array(); for (auto key : {"score", "chances", "yellow", "red", "players"}) for (auto &value : score.at(key)) if (value.is_number_integer() && value.get() < 0) value = 0; const Json *home = nullptr; for (const auto &match : out.at("matches")) if (match.at("id") == score.at("match_id")) home = &match.at("home").at("id"); if (!home || role == "national") continue; for (const auto &[id, table] : tables) { (void)id; const bool has = std::any_of(table.begin(), table.end(), [&](const Json &row) { return row.at("team").at("id") == *home; }); if (has) { score["standings"] = table; break; } } } } if (!valid_engine_live_fixture(out)) return failure("invalid_live_fixture"); return out; } catch (const std::exception &) { return failure("invalid_live_fixture"); } } Json engine_live_command(const Json &bundle, const std::string &revision, const std::string &request_id, const std::string &kind, const Json &payload) { const auto &meta = bundle.at("desktop").at("meta"); return {{"messageType", "command"}, {"contractVersion", meta.at("contractVersion")}, {"requestId", request_id}, {"careerId", meta.at("careerId")}, {"expectedRevision", revision}, {"owner", {{"managerId", meta.at("scope").at("managerId")}}}, {"kind", kind}, {"payload", payload.is_object() ? payload : Json::object()}}; } Json engine_post_match_records(const Json &read, const Json &fixture) { try { if (!read.is_object() || read.value("messageType", "") != "snapshot") return Json(); const auto &elevens = read.at("data").at("teamOfTheDay"); if (!elevens.is_array() || elevens.empty()) return Json(); // club names as the recording spells them (its matches and final tables) std::map clubs; for (const auto &match : fixture.at("matches")) for (auto side : {"home", "away"}) clubs[match.at(side).at("id")] = match.at(side).at("name"); for (const auto &snapshot : fixture.at("frames").back().at("matches")) for (const auto &row : snapshot.at("standings")) clubs[row.at("team").at("id")] = row.at("team").at("name"); for (const auto &eleven : elevens) { if (!eleven.contains("players") || !eleven.at("players").is_array() || eleven.at("players").size() != 11) continue; Json rows = Json::array(); for (const auto &p : eleven.at("players")) { const auto club = clubs.find(p.value("teamId", std::string())); if (club == clubs.end()) break; rows.push_back({{"player", {{"id", p.at("playerId")}, {"name", p.at("name")}}}, {"team", {{"id", club->first}, {"name", club->second}, {"role", "club"}}}, {"position", p.at("position")}, {"rating", nullptr}}); } if (rows.size() != 11) continue; return {{"schema", "openbmh-post-match-records@1"}, {"fixture_id", fixture.at("fixture_id")}, {"source_revision", fixture.at("source_revision")}, {"eleven", {{"available", true}, {"source", "supplied-records"}, {"notice", eleven.value("competition", std::string("Liga")) + " · nach Toren, Vorlagen, Karten und Ergebnis des Spieltags"}, {"formation", "3-4-3"}, {"rows", rows}}}}; } return Json(); } catch (const std::exception &) { return Json(); } } Json engine_live_roster(const Json &bundle) { Json rows = Json::array(); try { const auto &players = bundle.at("squad").at("data").at("players"); std::map by_id; std::vector listed, order; for (const auto &p : players) { const std::string id = p.at("player").at("id"); by_id[id] = &p; listed.push_back(id); } try { for (const auto &id : bundle.at("lineup").at("data").at("order")) if (id.is_string()) order.push_back(id); } catch (const std::exception &) {} std::set seen; const auto add = [&](const std::string &id) { const auto at = by_id.find(id); if (at == by_id.end() || !seen.insert(id).second) return; const auto &p = *at->second; rows.push_back({{"id", id}, {"name", p.at("player").at("name")}, {"slot", rows.size()}, {"strength", metric(p, "strength")}, {"condition", metric(p, "condition")}, {"position", p.at("player").value("positions", Json::array()).empty() ? Json() : p.at("player").at("positions").front()}, {"caps", nullptr}, {"international_goals", nullptr}}); }; for (const auto &id : order) add(id); for (const auto &id : listed) add(id); } catch (const std::exception &) { rows = Json::array(); } return rows; } // The standing kickoff as the ticker's fixture: the frames so far plus one for this minute. // Event texts are composed here from the engine's facts (kind, player, minute); the full // recording with the engine's own wording replaces this fixture after the final whistle. Json engine_live_progress(const Json &previous, const Json &state, const Json &bundle, const Json &roster) { try { if (!state.is_object() || !state.value("ok", false) || !state.value("live", false)) return failure("live_unavailable"); const auto &meta = bundle.at("desktop").at("meta"); const std::string desk_team = meta.at("scope").at("teamId"), desk_manager = meta.at("scope").at("managerId"); const std::string role = desk_team.starts_with("nt:") || meta.at("scope").value("role", "club") == "national" ? "national" : "club"; const int64_t minute = std::clamp(state.at("minute").get(), 0, 120); Json out = previous.is_object() && previous.value("live_running", false) ? previous : Json(); if (!out.is_object()) { out = {{"ok", true}, {"schema", "openbmh-live-fixture@1"}, {"source", "engine-recording"}, {"live_running", true}, {"fixture_id", "live:running:" + meta.at("date").get()}, {"source_revision", 0}, {"date", meta.at("date")}, {"world", meta.value("worldId", std::string())}, {"role", role}, {"surface", "outdoor"}, {"duration", 90}, {"field_count", 11}, {"owners", Json::array()}, {"matches", Json::array()}, {"frames", Json::array()}, {"notice", "Der Spieltag läuft"}}; std::set portraits; for (const auto &m : state.at("matches")) { const std::string id = "live:" + m.at("home").at("id").get(); Json owners = Json::array(); for (auto side : {"home", "away"}) { const auto &manager = m.at(std::string(side) + "ManagerId"); if (!manager.is_string() || out.at("owners").size() >= 4) continue; const bool own = manager == desk_manager; int portrait = int(out.at("owners").size()); Json team = m.at(side); team["role"] = role; std::string name = own ? bundle.at("desktop").at("data").at("manager").value("name", std::string("Manager")) : std::string("Manager"); // the fellow players' names stand in the session's list of managers if (!own) try { for (const auto &person : bundle.at("session").at("data").at("managers")) { if (person.at("id") != manager) continue; const auto &value = person.at("name"); const std::string found = value.is_string() ? value.get() : value.value("text", std::string()); if (!found.empty()) name = found; } } catch (const std::exception &) {} out["owners"].push_back({{"id", manager}, {"portrait", portrait}, {"name", name}, {"team", team}, {"match_id", id}, {"view", {{"ok", true}, {"engine", true}, {"rows", own ? roster : Json::array()}, {"field_count", 11}}}}); owners.push_back(manager); } Json home = m.at("home"), away = m.at("away"); home["role"] = role; away["role"] = role; // the desk announced this fixture with its competition; other matches stay unnamed std::string competition = "Spieltag"; try { const auto &next = bundle.at("desktop").at("data").at("nextFixture"); if (next.is_object() && next.at("home").at("id") == m.at("home").at("id")) { competition = next.at("competition").value("text", competition); std::replace(competition.begin(), competition.end(), '\n', ' '); // the original's column label for a postponed league match, spelled out if (competition == "Verlegte Sp.") competition = "Nachholspiel"; // "24.Spieltag" of the original reads "24. Spieltag" for (size_t i = 0; i + 1 < competition.size(); ++i) if (competition[i] == '.' && std::isalpha(static_cast(competition[i + 1]))) competition.insert(++i, 1, ' '); } } catch (const std::exception &) {} out["matches"].push_back({{"id", id}, {"home", home}, {"away", away}, {"owners", owners}, {"competition", competition}, {"attendance", m.value("attendance", Json())}, {"weather", m.value("weather", Json())}, {"capacity", m.value("capacity", Json())}, {"stadiumName", m.value("stadiumName", Json())}, {"lineups", m.value("lineups", Json())}}); } if (out.at("owners").empty() || out.at("matches").empty()) return failure("live_no_human_match"); } // the desk manager's roster follows substitutions made during the match for (auto &owner : out.at("owners")) if (owner.at("id") == desk_manager) owner["view"]["rows"] = roster; if (minute > 90) out["duration"] = 120; Json events = Json::array(), scores = Json::array(); const size_t sequence = out.at("frames").size() + (out.at("frames").empty() ? 1 : 0); // earlier events keep the frame they first appeared in std::map known; if (!out.at("frames").empty()) for (const auto &e : out.at("frames").back().at("events")) known[e.at("id")] = e; for (const auto &m : state.at("matches")) { const std::string id = "live:" + m.at("home").at("id").get(); int goals[2] = {0, 0}, chances[2] = {0, 0}, yellow[2] = {0, 0}, red[2] = {0, 0}; size_t index = 0; for (const auto &e : m.at("events")) { const std::string kind = e.value("kind", std::string()); const size_t side = e.value("side", std::string("home")) == "away" ? 1 : 0; const std::string team = m.at(side ? "away" : "home").at("name"); const std::string player = e.at("player").is_object() ? e.at("player").value("name", std::string()) : std::string(); const std::string other = e.contains("other") && e.at("other").is_object() ? e.at("other").value("name", std::string()) : std::string(); std::string headline, body, shown = kind; if (kind == "goal") { ++goals[side]; ++chances[side]; headline = "Tor für " + team; body = (player.empty() ? std::string("Treffer") : player + " trifft") + " zum " + std::to_string(goals[0]) + ":" + std::to_string(goals[1]) + "." + (other.empty() ? "" : " Vorlage: " + other + "."); } else if (kind == "miss") { ++chances[side]; shown = "chance"; headline = "Chance für " + team; body = player.empty() ? "Die Chance bleibt ungenutzt." : player + " vergibt."; } else if (kind == "yellow") { ++yellow[side]; headline = "Gelbe Karte"; body = (player.empty() ? "Ein Spieler" : player) + " (" + team + ") sieht Gelb."; } else if (kind == "second_yellow" || kind == "red") { ++red[side]; shown = "red"; headline = kind == "red" ? "Rote Karte" : "Gelb-Rot"; body = (player.empty() ? "Ein Spieler" : player) + " (" + team + ") muss vom Platz."; } else if (kind == "injury") { headline = "Verletzung"; body = (player.empty() ? "Ein Spieler" : player) + " (" + team + ") muss behandelt werden."; } else continue; if (e.contains("headline") && e.at("headline").is_string() && e.contains("body") && e.at("body").is_string() && !e.at("headline").get().empty()) { headline = e.at("headline").get(); body = e.at("body").get(); } const std::string event_id = id + ":event:" + std::to_string(index++); const auto at = known.find(event_id); events.push_back(at != known.end() ? at->second : Json{{"id", event_id}, {"sequence", sequence}, {"match_id", id}, {"minute", std::clamp(e.value("minute", int64_t(minute)), 0, minute)}, {"kind", shown}, {"headline", headline}, {"body", body}, {"score", {goals[0], goals[1]}}, {"side", side ? "away" : "home"}, {"player", e.at("player")}, {"other", e.value("other", Json())}}); } { // the whistle, as in the recording: kickoff, and half time once the second half runs const auto whistle = [&](const char *suffix, int64_t at, const char *kind, const std::string &headline, const std::string &body, int h, int a) { const std::string event_id = id + suffix; const auto known_at = known.find(event_id); events.push_back(known_at != known.end() ? known_at->second : Json{{"id", event_id}, {"sequence", sequence}, {"match_id", id}, {"minute", at}, {"kind", kind}, {"headline", headline}, {"body", body}, {"score", {h, a}}, {"side", "home"}, {"player", nullptr}, {"other", nullptr}}); }; whistle(":kickoff", 0, "kickoff", "Anpfiff", m.at("home").at("name").get() + " gegen " + m.at("away").at("name").get() + ": Der Ball rollt.", 0, 0); if (minute > 45) { int h = 0, a = 0; for (const auto &e : m.at("events")) if (e.value("kind", std::string()) == "goal" && e.value("minute", int64_t(0)) <= 45) ++(e.value("side", std::string("home")) == "away" ? a : h); whistle(":interval", 45, "interval", "Halbzeit", "Zur Pause steht es " + std::to_string(h) + ":" + std::to_string(a) + ".", h, a); } } Json score = m.value("score", Json::array({goals[0], goals[1]})); Json standings = Json::array(); if (role == "club" && state.contains("standings")) for (const auto &table : state.at("standings")) { if (!table.is_object() || !table.contains("rows")) continue; Json rows = Json::array(); bool has = false; for (const auto &row : table.at("rows")) { Json team = row.at("team"); team["role"] = "club"; has = has || team.at("id") == m.at("home").at("id"); rows.push_back({{"team", team}, {"position", row.at("rank")}, {"played", row.at("played")}, {"gf", row.at("goalsFor")}, {"ga", row.at("goalsAgainst")}, {"points", row.at("points")}, {"won", row.value("won", Json())}, {"drawn", row.value("drawn", Json())}, {"lost", row.value("lost", Json())}}); } if (has) { standings = std::move(rows); break; } } scores.push_back({{"match_id", id}, {"score", score}, {"chances", {chances[0], chances[1]}}, {"yellow", {yellow[0], yellow[1]}}, {"red", {red[0], red[1]}}, {"players", {std::max(0, 11 - red[0]), std::max(0, 11 - red[1])}}, {"standings", standings}}); } // events are shown newest last, in minute order across the matches std::stable_sort(events.begin(), events.end(), [](const Json &a, const Json &b) { return a.at("minute").get() < b.at("minute").get(); }); if (out.at("frames").empty()) { Json zero = Json::array(); for (const auto &s : scores) zero.push_back({{"match_id", s.at("match_id")}, {"score", {0, 0}}, {"chances", {0, 0}}, {"yellow", {0, 0}}, {"red", {0, 0}}, {"players", {11, 11}}, {"standings", s.at("standings")}}); out["frames"].push_back({{"sequence", 0}, {"minute", 0}, {"phase", "first_half"}, {"matches", zero}, {"events", Json::array()}}); } const int64_t last_minute = out.at("frames").back().at("minute"); out["frames"].push_back({{"sequence", out.at("frames").size()}, {"minute", std::max(minute, last_minute)}, {"phase", minute <= 45 ? "first_half" : minute <= 90 ? "second_half" : "extra_time"}, {"matches", scores}, {"events", events}}); if (out.at("frames").size() > 1900) return failure("invalid_live_fixture"); if (!valid_engine_live_fixture(out)) return failure("invalid_live_fixture"); return out; } catch (const std::exception &) { return failure("invalid_live_fixture"); } } } // namespace bmh::modern_ui