350 lines
20 KiB
C++
350 lines
20 KiB
C++
// SPDX-License-Identifier: GPL-3.0-only
|
|
#include "modern/ui/demo_files.hpp"
|
|
#include "modern/ui/demo_career.hpp"
|
|
#include "modern/ui/desktop.hpp"
|
|
#include "editor/images.hpp"
|
|
#include "content/digest.hpp"
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <iomanip>
|
|
#include <sstream>
|
|
|
|
namespace bmh::modern_ui {
|
|
namespace {
|
|
constexpr uint64_t file_limit = 64 * 1024 * 1024;
|
|
std::string stamp(std::chrono::system_clock::time_point time = std::chrono::system_clock::now()) {
|
|
const auto days = std::chrono::floor<std::chrono::days>(time);
|
|
const std::chrono::year_month_day date{days};
|
|
const std::chrono::hh_mm_ss clock{std::chrono::floor<std::chrono::seconds>(time - days)};
|
|
std::ostringstream out;
|
|
out << std::setfill('0') << std::setw(4) << int(date.year()) << '-'
|
|
<< std::setw(2) << unsigned(date.month()) << '-' << std::setw(2) << unsigned(date.day())
|
|
<< ' ' << std::setw(2) << clock.hours().count() << ':' << std::setw(2) << clock.minutes().count()
|
|
<< ':' << std::setw(2) << clock.seconds().count() << " UTC";
|
|
return out.str();
|
|
}
|
|
void safe_directory(const fs::path &path, bool create = false) {
|
|
fs::path current;
|
|
for (const auto &part : fs::absolute(path).lexically_normal()) {
|
|
current /= part;
|
|
const auto status = fs::symlink_status(current);
|
|
if (fs::is_symlink(status) || (fs::exists(status) && !fs::is_directory(status)))
|
|
throw editor::Error("Dateiablage verweist auf einen unsicheren Pfad.");
|
|
}
|
|
if (create) fs::create_directories(path);
|
|
}
|
|
struct Lock {
|
|
fs::path path;
|
|
explicit Lock(const fs::path &root) : path(root / ".files-transaction") {
|
|
safe_directory(root, true);
|
|
if (!fs::create_directory(path))
|
|
throw editor::Error("Die Dateiablage ist gerade belegt. Bitte erneut versuchen.");
|
|
}
|
|
~Lock() { std::error_code error; fs::remove(path, error); }
|
|
};
|
|
std::vector<uint32_t> codepoints(const std::string &name) {
|
|
std::vector<uint32_t> out;
|
|
for (size_t i = 0; i < name.size();) {
|
|
const uint8_t first = uint8_t(name[i++]);
|
|
uint32_t value = first;
|
|
int remaining = 0;
|
|
if (first >= 0xc2 && first <= 0xdf) { value &= 31; remaining = 1; }
|
|
else if (first >= 0xe0 && first <= 0xef) { value &= 15; remaining = 2; }
|
|
else if (first >= 0xf0 && first <= 0xf4) { value &= 7; remaining = 3; }
|
|
else if (first >= 0x80) throw editor::Error("Die Bezeichnung enthält ungültigen Text.");
|
|
const int count = remaining;
|
|
while (remaining--) {
|
|
if (i == name.size() || (uint8_t(name[i]) & 0xc0) != 0x80)
|
|
throw editor::Error("Die Bezeichnung enthält ungültigen Text.");
|
|
value = value * 64 + (uint8_t(name[i++]) & 63);
|
|
}
|
|
if ((count == 1 && value < 0x80) || (count == 2 && value < 0x800) ||
|
|
(count == 3 && value < 0x10000) || value > 0x10ffff ||
|
|
(value >= 0xd800 && value <= 0xdfff))
|
|
throw editor::Error("Die Bezeichnung enthält ungültigen Text.");
|
|
out.push_back(value);
|
|
}
|
|
return out;
|
|
}
|
|
void utf8(std::string &out, uint32_t value) {
|
|
if (value < 128) out += char(value);
|
|
else if (value < 2048) { out += char(0xc0 | value >> 6); out += char(0x80 | (value & 63)); }
|
|
else if (value < 65536) { out += char(0xe0 | value >> 12); out += char(0x80 | ((value >> 6) & 63)); out += char(0x80 | (value & 63)); }
|
|
else { out += char(0xf0 | value >> 18); out += char(0x80 | ((value >> 12) & 63)); out += char(0x80 | ((value >> 6) & 63)); out += char(0x80 | (value & 63)); }
|
|
}
|
|
std::string hex(const std::string &data) {
|
|
constexpr char digits[] = "0123456789abcdef";
|
|
std::string out; out.reserve(data.size() * 2);
|
|
for (uint8_t value : data) { out += digits[value >> 4]; out += digits[value & 15]; }
|
|
return out;
|
|
}
|
|
std::string unhex(const std::string &data) {
|
|
if (data.size() % 2 || data.size() > 32 * 1024 * 1024)
|
|
throw editor::Error("Ungültige Vorschau.");
|
|
const auto digit = [](char c) -> int {
|
|
if (c >= '0' && c <= '9') return c - '0';
|
|
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
|
throw editor::Error("Ungültige Vorschau.");
|
|
};
|
|
std::string out; out.reserve(data.size() / 2);
|
|
for (size_t i = 0; i < data.size(); i += 2) out += char(digit(data[i]) * 16 + digit(data[i + 1]));
|
|
return out;
|
|
}
|
|
void validate_png(const std::string &bytes, bool required) {
|
|
if (bytes.empty()) {
|
|
if (required) throw editor::Error("Die Desktop-Vorschau fehlt.");
|
|
return;
|
|
}
|
|
if (bytes.size() < 24 || bytes.size() > 16 * 1024 * 1024 ||
|
|
bytes.substr(0, 8) != std::string("\x89PNG\r\n\x1a\n", 8))
|
|
throw editor::Error("Die Vorschau ist keine gültige PNG-Datei.");
|
|
const auto integer = [&](size_t at) {
|
|
uint32_t n = 0; for (size_t i = at; i < at + 4; ++i) n = n * 256 + uint8_t(bytes[i]); return n;
|
|
};
|
|
const uint64_t width = integer(16), height = integer(20);
|
|
if (!width || !height || width > 8192 || height > 8192 || width * height > 32 * 1024 * 1024)
|
|
throw editor::Error("Die Desktop-Vorschau ist zu groß.");
|
|
const auto decoded = editor::images::decode(bytes, ".png");
|
|
if (uint64_t(decoded.width) != width || uint64_t(decoded.height) != height)
|
|
throw editor::Error("Die Desktop-Vorschau ist beschädigt.");
|
|
}
|
|
std::string read_regular(const fs::path &path) {
|
|
if (fs::is_symlink(fs::symlink_status(path)) || !fs::is_regular_file(path))
|
|
throw editor::Error("Die ausgewählte Datei ist nicht mehr vorhanden oder unsicher.");
|
|
return editor::read_file(path, file_limit);
|
|
}
|
|
bool path_inside(const fs::path &directory, const fs::path &candidate) {
|
|
auto parent = directory.begin();
|
|
auto child = candidate.begin();
|
|
for (; parent != directory.end(); ++parent, ++child)
|
|
if (child == candidate.end() || *parent != *child) return false;
|
|
return true;
|
|
}
|
|
void validate_export_destination(const fs::path &root, const fs::path &destination) {
|
|
const auto lexical = fs::absolute(destination).lexically_normal();
|
|
const auto resolved = fs::weakly_canonical(destination);
|
|
for (const char *name : {"saves", "layouts"}) {
|
|
const auto directory = root / name;
|
|
const auto lexical_directory = fs::absolute(directory).lexically_normal();
|
|
const auto resolved_directory = fs::weakly_canonical(directory);
|
|
if (path_inside(lexical_directory, lexical) || path_inside(resolved_directory, resolved))
|
|
throw editor::Error("Bitte außerhalb der verwalteten Spielstand- und Ansichtsablage exportieren.");
|
|
// Filesystem equivalence also covers Windows case aliases and directory
|
|
// junctions without relying on lexical casing of the supplied path.
|
|
for (auto ancestor = resolved; !ancestor.empty();) {
|
|
std::error_code error;
|
|
if (fs::equivalent(directory, ancestor, error) && !error)
|
|
throw editor::Error("Bitte außerhalb der verwalteten Spielstand- und Ansichtsablage exportieren.");
|
|
const auto parent = ancestor.parent_path();
|
|
if (parent == ancestor) break;
|
|
ancestor = parent;
|
|
}
|
|
}
|
|
}
|
|
} // namespace
|
|
DemoFiles::DemoFiles(fs::path root, DemoFileKind kind, std::shared_ptr<const Catalog> world)
|
|
: root_(fs::weakly_canonical(std::move(root))), directory_(root_ / (kind == DemoFileKind::career ? "saves" : "layouts")), kind_(kind), world_(std::move(world)) {}
|
|
std::string DemoFiles::clean_name(const std::string &raw) {
|
|
const auto first = raw.find_first_not_of(" "), last = raw.find_last_not_of(" ");
|
|
if (first == raw.npos) throw editor::Error("Bitte eine Bezeichnung mit 1 bis 64 Zeichen eingeben.");
|
|
const auto name = raw.substr(first, last - first + 1);
|
|
const auto points = codepoints(name);
|
|
if (points.empty() || points.size() > 64 || std::any_of(points.begin(), points.end(), [](uint32_t c) { return c < 32 || (c >= 127 && c < 160); }))
|
|
throw editor::Error("Bitte eine Bezeichnung mit 1 bis 64 Zeichen ohne Steuerzeichen eingeben.");
|
|
return name;
|
|
}
|
|
std::string DemoFiles::name_key(const std::string &name, bool compatibility) {
|
|
const auto points = codepoints(clean_name(name));
|
|
std::string result;
|
|
for (size_t i = 0; i < points.size(); ++i) {
|
|
auto c = points[i];
|
|
if (compatibility && c >= 0xff01 && c <= 0xff5e) c -= 0xfee0;
|
|
if (c >= 'A' && c <= 'Z') c += 32;
|
|
if ((c >= 0xc0 && c <= 0xd6) || (c >= 0xd8 && c <= 0xde)) c += 32;
|
|
if (c == 0x1e9e || c == 0xdf) { result += "ss"; continue; }
|
|
// Compose Latin keyboard accent sequences without depending on the
|
|
// current OS locale or filesystem's normalization rules.
|
|
if (i + 1 < points.size()) {
|
|
const auto accent = points[i + 1]; uint32_t composed = 0;
|
|
const std::string letters = "aeiou";
|
|
const auto index = letters.find(char(c));
|
|
if (c < 128 && index != letters.npos) {
|
|
const std::array<uint32_t, 5> grave{0xe0,0xe8,0xec,0xf2,0xf9}, acute{0xe1,0xe9,0xed,0xf3,0xfa}, circumflex{0xe2,0xea,0xee,0xf4,0xfb}, diaeresis{0xe4,0xeb,0xef,0xf6,0xfc};
|
|
if (accent == 0x300) composed = grave[index];
|
|
if (accent == 0x301) composed = acute[index];
|
|
if (accent == 0x302) composed = circumflex[index];
|
|
if (accent == 0x308) composed = diaeresis[index];
|
|
}
|
|
if (accent == 0x303) composed = c == 'a' ? 0xe3 : c == 'n' ? 0xf1 : c == 'o' ? 0xf5 : 0;
|
|
if (accent == 0x30a && c == 'a') composed = 0xe5;
|
|
if (accent == 0x327 && c == 'c') composed = 0xe7;
|
|
if (accent == 0x301 && c == 'y') composed = 0xfd;
|
|
if (accent == 0x308 && c == 'y') composed = 0xff;
|
|
if (composed) { c = composed; ++i; }
|
|
}
|
|
if (c >= 0x410 && c <= 0x42f) c += 32;
|
|
if (c >= 0x391 && c <= 0x3ab && c != 0x3a2) c += 32;
|
|
utf8(result, c);
|
|
}
|
|
return result;
|
|
}
|
|
fs::path DemoFiles::path(const std::string &id) const {
|
|
if (id.empty() || id.size() > 255 || id.find_first_of("/\\:") != id.npos ||
|
|
id.front() == '.' || editor::path(id).extension() != ".json")
|
|
throw editor::Error("Ungültige Dateiauswahl.");
|
|
safe_directory(directory_);
|
|
return directory_ / editor::path(id);
|
|
}
|
|
void DemoFiles::validate(const Json &data) const {
|
|
if (kind_ == DemoFileKind::desktop) {
|
|
if (!data.is_object() || data.size() != 2 || !data.contains("layout") || !valid_desktop(data.at("layout")) ||
|
|
(data.value("theme", "") != "midnight" && data.value("theme", "") != "silver" && data.value("theme", "") != "matchday"))
|
|
throw editor::Error("Ungültige Desktopansicht.");
|
|
} else {
|
|
if (!world_) throw editor::Error("Bitte zuerst eine Welt auswählen.");
|
|
DemoSource staged(world_);
|
|
staged.load_data(data);
|
|
}
|
|
}
|
|
DemoFileEntry DemoFiles::decode(const fs::path &file, const std::string &raw) const {
|
|
DemoFileEntry row;
|
|
row.id = editor::utf8(file.filename()); row.token = content::sha256(raw); row.bytes = raw.size();
|
|
// Bridge relative durations instead of relying on file_clock::to_sys,
|
|
// which is not provided by every supported standard library.
|
|
const auto elapsed = fs::last_write_time(file) - fs::file_time_type::clock::now();
|
|
row.modified = stamp(std::chrono::system_clock::now() +
|
|
std::chrono::duration_cast<std::chrono::system_clock::duration>(elapsed));
|
|
const auto value = Json::parse(raw);
|
|
if (value.value("schema", "") == "openbmh-ui-file@1") {
|
|
const auto expected_kind = kind_ == DemoFileKind::career ? "career" : "desktop";
|
|
if (value.at("kind") != expected_kind) throw editor::Error("Die Datei gehört nicht zu dieser Ansicht.");
|
|
if (kind_ == DemoFileKind::career && (!world_ || value.at("world") != world_->manifest().value("id", "") || value.at("world_revision") != content::sha256(world_->manifest().dump())))
|
|
throw editor::Error("Die Datei gehört zu einer anderen Welt oder Quellrevision.");
|
|
row.name = clean_name(value.at("name")); row.created = value.at("created").get<std::string>();
|
|
if (row.created.size() > 64) throw editor::Error("Ungültige Dateimetadaten.");
|
|
row.data = value.at("data"); row.preview_png = unhex(value.at("preview_png"));
|
|
if (value.at("data_sha256") != content::sha256(row.data.dump()) || value.at("preview_sha256") != content::sha256(row.preview_png))
|
|
throw editor::Error("Datei und Vorschau sind beschädigt.");
|
|
} else {
|
|
row.legacy = true; row.name = clean_name(editor::utf8(file.stem())); row.created = row.modified;
|
|
row.data = kind_ == DemoFileKind::career ? value : Json{{"layout", value}, {"theme", "midnight"}};
|
|
if (kind_ == DemoFileKind::desktop && !migrate_desktop(row.data["layout"]))
|
|
throw editor::Error("Ungültige ältere Desktopansicht.");
|
|
auto image = file; image.replace_extension(".png");
|
|
if (fs::exists(image)) row.preview_png = read_regular(image);
|
|
}
|
|
validate_png(row.preview_png, kind_ == DemoFileKind::desktop && !row.legacy);
|
|
return row;
|
|
}
|
|
std::vector<DemoFileEntry> DemoFiles::list() const {
|
|
safe_directory(directory_);
|
|
std::vector<DemoFileEntry> rows;
|
|
if (!fs::exists(directory_)) return rows;
|
|
for (const auto &file : fs::directory_iterator(directory_)) {
|
|
if (file.path().extension() != ".json" || editor::utf8(file.path().filename()).starts_with('.')) continue;
|
|
DemoFileEntry row;
|
|
try { row = decode(file.path(), read_regular(file.path())); }
|
|
catch (const std::exception &e) {
|
|
row.id = editor::utf8(file.path().filename()); row.name = editor::utf8(file.path().stem()); row.error = e.what();
|
|
try {
|
|
if (!file.is_symlink() && file.is_regular_file()) { const auto bytes = editor::read_file(file.path(), file_limit); row.token = content::sha256(bytes); row.bytes = bytes.size(); }
|
|
} catch (...) { /* Keep the explicit unreadable row without a delete token. */ }
|
|
}
|
|
rows.push_back(std::move(row));
|
|
}
|
|
std::sort(rows.begin(), rows.end(), [](const auto &a, const auto &b) { return a.name < b.name; });
|
|
return rows;
|
|
}
|
|
DemoFileEntry DemoFiles::read(const std::string &id, const std::string &expected) const {
|
|
const auto file = path(id);
|
|
const auto raw = read_regular(file);
|
|
if (!expected.empty() && content::sha256(raw) != expected)
|
|
throw editor::Error("Diese Datei wurde inzwischen geändert. Bitte erneut auswählen.");
|
|
auto row = decode(file, raw); validate(row.data); return row;
|
|
}
|
|
std::string DemoFiles::free_name(const std::string &base) const {
|
|
const auto clean = clean_name(base); const auto rows = list();
|
|
const bool compatibility = kind_ == DemoFileKind::desktop;
|
|
const auto used = [&](const std::string &n) { const auto key = name_key(n, compatibility); return std::any_of(rows.begin(), rows.end(), [&](const auto &r) { try { return name_key(r.name, compatibility) == key; } catch (...) { return false; } }); };
|
|
if (!used(clean) && !(kind_ == DemoFileKind::desktop && name_key(clean, compatibility) == "standard")) return clean;
|
|
auto points = codepoints(clean); if (points.size() > 50) points.resize(50);
|
|
std::string prefix; for (auto c : points) utf8(prefix, c);
|
|
for (uint64_t number = 2;; ++number) { const auto n = prefix + " (" + std::to_string(number) + ")"; if (!used(n)) return n; }
|
|
}
|
|
DemoFileEntry DemoFiles::commit(const std::string &raw_name, const Json &data, const std::string &png, const std::string &id, const std::string &expected, const std::string &created) {
|
|
const auto name = clean_name(raw_name), key = name_key(name, kind_ == DemoFileKind::desktop);
|
|
if (kind_ == DemoFileKind::desktop && key == "standard") throw editor::Error("Die Standardansicht bleibt unveränderlich.");
|
|
validate(data); validate_png(png, kind_ == DemoFileKind::desktop);
|
|
if (!id.empty() && expected.empty()) throw editor::Error("Die Bestätigung der Dateiversion fehlt.");
|
|
for (const auto &row : list()) {
|
|
bool duplicate = false;
|
|
try { duplicate = row.id != id && name_key(row.name, kind_ == DemoFileKind::desktop) == key; } catch (...) {}
|
|
if (duplicate) throw editor::Error("Diese Bezeichnung wird bereits verwendet.");
|
|
}
|
|
if (!id.empty()) read(id, expected);
|
|
static std::atomic<uint64_t> serial{0};
|
|
const auto stamp_now = stamp();
|
|
const auto selected = id.empty() ? "entry-" + content::sha256(name + stamp_now + std::to_string(++serial) + data.dump()).substr(0, 32) + ".json" : id;
|
|
const Json envelope = {{"schema", "openbmh-ui-file@1"}, {"kind", kind_ == DemoFileKind::career ? "career" : "desktop"},
|
|
{"name", name}, {"created", created.empty() ? stamp_now : created}, {"world", world_ ? world_->manifest().value("id", "") : ""},
|
|
{"world_revision", world_ ? content::sha256(world_->manifest().dump()) : ""}, {"data", data},
|
|
{"data_sha256", content::sha256(data.dump())}, {"preview_png", hex(png)}, {"preview_sha256", content::sha256(png)}};
|
|
const auto bytes = envelope.dump(2); if (bytes.size() > file_limit) throw editor::Error("Die Datei ist zu groß.");
|
|
safe_directory(directory_, true);
|
|
const auto destination = path(selected);
|
|
editor::write_atomic(destination, bytes, !id.empty());
|
|
return decode(destination, bytes);
|
|
}
|
|
DemoFileEntry DemoFiles::put(const std::string &name, const Json &data, const std::string &png, const std::string &id, const std::string &expected) {
|
|
Lock lock(root_); return commit(name, data, png, id, expected);
|
|
}
|
|
DemoFileEntry DemoFiles::rename(const std::string &id, const std::string &expected, const std::string &name) {
|
|
Lock lock(root_); const auto previous = read(id, expected);
|
|
return commit(name, previous.data, previous.preview_png, id, previous.token, previous.created);
|
|
}
|
|
void DemoFiles::remove(const std::string &id, const std::string &expected) {
|
|
Lock lock(root_); const auto file = path(id); const auto raw = read_regular(file);
|
|
if (expected.empty() || content::sha256(raw) != expected) throw editor::Error("Diese Datei wurde inzwischen geändert. Bitte erneut auswählen.");
|
|
// Rename is the atomic removal point. An interrupted cleanup retains the
|
|
// recoverable original bytes in a hidden tombstone, never a half record.
|
|
const auto trash = directory_ / (".deleted-" + content::sha256(raw) + "-" + content::sha256(id).substr(0, 12));
|
|
if (fs::exists(trash)) throw editor::Error("Eine frühere Löschung muss erst geprüft werden.");
|
|
fs::rename(file, trash); std::error_code error; fs::remove(trash, error);
|
|
}
|
|
DemoFileEntry DemoFiles::import_file(const fs::path &file) {
|
|
auto imported = decode(file, read_regular(file)); validate(imported.data);
|
|
// Import always creates a new record; an existing local save is never lost.
|
|
return put(free_name(imported.name), imported.data, imported.preview_png);
|
|
}
|
|
void DemoFiles::export_file(const std::string &id, const std::string &expected, const fs::path &destination, bool overwrite) const {
|
|
const auto entry = read(id, expected);
|
|
validate_export_destination(root_, destination);
|
|
safe_directory(fs::weakly_canonical(destination.has_parent_path() ? destination.parent_path() : fs::path(".")));
|
|
const Json envelope = {{"schema", "openbmh-ui-file@1"}, {"kind", kind_ == DemoFileKind::career ? "career" : "desktop"},
|
|
{"name", entry.name}, {"created", entry.created}, {"world", world_ ? world_->manifest().value("id", "") : ""},
|
|
{"world_revision", world_ ? content::sha256(world_->manifest().dump()) : ""}, {"data", entry.data},
|
|
{"data_sha256", content::sha256(entry.data.dump())}, {"preview_png", hex(entry.preview_png)}, {"preview_sha256", content::sha256(entry.preview_png)}};
|
|
editor::write_atomic(destination, envelope.dump(2), overwrite);
|
|
}
|
|
fs::path DemoFiles::preview_file(const DemoFileEntry &entry) const {
|
|
if (entry.preview_png.empty()) return {};
|
|
validate_png(entry.preview_png, true);
|
|
const auto folder = root_ / ".previews"; safe_directory(folder, true);
|
|
const auto output = folder / (content::sha256(entry.preview_png) + ".png");
|
|
if (!fs::exists(output) || content::sha256(read_regular(output)) != content::sha256(entry.preview_png)) editor::write_atomic(output, entry.preview_png);
|
|
return output;
|
|
}
|
|
Json DemoFiles::career_metadata(const Json &data) {
|
|
const auto date = data.at("date").get<std::string>();
|
|
if (date.size() != 10) throw editor::Error("Ungültiges Spieldatum.");
|
|
const int season = std::stoi(date.substr(0, 4)) - (date.substr(5, 2) < "07" ? 1 : 0);
|
|
int matchday = 0;
|
|
if (data.contains("game_info")) matchday = data.at("game_info").value("matchday", 0);
|
|
return {{"season", std::to_string(season) + "/" + std::to_string(season + 1).substr(2)},
|
|
{"matchday", matchday > 0 ? std::to_string(matchday) + ". Spieltag" : "Vorbereitung"},
|
|
{"date", date}, {"managers", data.at("managers")}, {"current_manager",demo_career_manager(data)}, {"role",data.value("career",Json::object()).value("role","club")}, {"ended",data.value("career",Json::object()).value("ended",false)}, {"human_count",data.value("career",Json::object()).value("ended",false)?0:data.at("managers").size()}};
|
|
}
|
|
} // namespace bmh::modern_ui
|