// SPDX-License-Identifier: MIT #include "openpu/storage.hpp" #include #include #include #include #include #include #ifdef __HAIKU__ #include #include #endif namespace openpu { namespace fs = std::filesystem; using json = nlohmann::ordered_json; // keep the user's vehicle order namespace { std::string env(const char* name) { const char* v = std::getenv(name); // NOLINT(concurrency-mt-unsafe) return v != nullptr ? v : ""; } fs::path home() { const std::string h = env("HOME"); return h.empty() ? fs::current_path() : fs::path(h); } #ifdef __HAIKU__ fs::path haikuDir(directory_which which, const fs::path& fallback) { char buf[PATH_MAX] = {}; if (find_directory(which, -1, false, buf, sizeof buf) == B_OK) return buf; return fallback; } #else /// XDG_DOWNLOAD_DIR from ~/.config/user-dirs.dirs, e.g. XDG_DOWNLOAD_DIR="$HOME/Téléchargements". fs::path xdgDownloadDir() { std::string cfg = env("XDG_CONFIG_HOME"); const fs::path base = cfg.empty() ? home() / ".config" : fs::path(cfg); std::ifstream in(base / "user-dirs.dirs"); std::string line; while (std::getline(in, line)) { const std::string key = "XDG_DOWNLOAD_DIR="; if (line.rfind(key, 0) != 0) continue; std::string v = line.substr(key.size()); if (v.size() >= 2 && v.front() == '"' && v.back() == '"') v = v.substr(1, v.size() - 2); const std::string var = "$HOME"; if (v.rfind(var, 0) == 0) v = home().string() + v.substr(var.size()); if (!v.empty() && v.front() == '/') return v; } return home() / "Downloads"; } #endif std::string readFile(const fs::path& file) { std::ifstream in(file, std::ios::binary); if (!in) throw StorageError("cannot read " + file.string()); std::stringstream ss; ss << in.rdbuf(); return ss.str(); } std::string str(const json& obj, const char* key) { auto it = obj.find(key); return it != obj.end() && it->is_string() ? it->get() : std::string(); } bool boolean(const json& obj, const char* key) { auto it = obj.find(key); return it != obj.end() && it->is_boolean() && it->get(); } json parseJson(const std::string& text, const std::string& what) { // The official app writes UTF-8 with a BOM on Windows. std::string_view view(text); if (view.substr(0, 3) == "\xEF\xBB\xBF") view.remove_prefix(3); json doc = json::parse(view, nullptr, false); if (doc.is_discarded() || !doc.is_object()) throw StorageError("invalid JSON in " + what); return doc; } } // namespace namespace paths { fs::path configDir() { #ifdef __HAIKU__ return haikuDir(B_USER_SETTINGS_DIRECTORY, home() / "config" / "settings") / "OpenPU"; #else const std::string xdg = env("XDG_CONFIG_HOME"); return (xdg.empty() ? home() / ".config" : fs::path(xdg)) / "openpu"; #endif } fs::path defaultDownloadDir() { #ifdef __HAIKU__ return haikuDir(B_USER_DIRECTORY, home()) / "OpenPU downloads"; #else return xdgDownloadDir() / "OpenPU"; #endif } } // namespace paths void writeFileAtomically(const fs::path& file, const std::string& content) { std::error_code ec; if (file.has_parent_path()) fs::create_directories(file.parent_path(), ec); fs::path tmp = file; tmp += ".tmp"; { std::ofstream out(tmp, std::ios::binary | std::ios::trunc); out << content; out.flush(); if (!out) throw StorageError("cannot write " + tmp.string()); } fs::rename(tmp, file, ec); if (ec) { fs::remove(tmp, ec); throw StorageError("cannot replace " + file.string()); } } // --- vehicles --------------------------------------------------------------------------------- VehicleStore::VehicleStore(fs::path file) : file_(std::move(file)) {} std::vector VehicleStore::parse(const std::string& text) { const json doc = parseJson(text, "vehicles file"); std::vector out; for (const auto& [vin, v] : doc.items()) { if (!v.is_object()) continue; Vehicle veh; veh.vin = vin; veh.name = str(v, "name"); veh.type = headUnitTypeFromString(str(v, "type")); veh.guideKey = str(v, "wave"); auto files = v.find("undeletedFiles"); if (files != v.end() && files->is_object()) { veh.pendingFirmware = str(*files, "fw"); veh.pendingMap = str(*files, "carto"); veh.pendingLicense = str(*files, "license"); } out.push_back(std::move(veh)); } return out; } std::string VehicleStore::serialize(const std::vector& vehicles) { json doc = json::object(); for (const auto& v : vehicles) { json entry = {{"name", v.name}, {"type", std::string(headUnitTypeName(v.type))}, {"wave", v.guideKey}}; json files = json::object(); if (!v.pendingFirmware.empty()) files["fw"] = v.pendingFirmware; if (!v.pendingMap.empty()) files["carto"] = v.pendingMap; if (!v.pendingLicense.empty()) files["license"] = v.pendingLicense; if (!files.empty()) entry["undeletedFiles"] = files; doc[v.vin] = entry; } return doc.dump(2) + "\n"; } void VehicleStore::load() { std::error_code ec; if (!fs::exists(file_, ec)) { vehicles_.clear(); return; } vehicles_ = parse(readFile(file_)); } void VehicleStore::save() const { writeFileAtomically(file_, serialize(vehicles_)); } const Vehicle* VehicleStore::find(const std::string& vin) const { auto it = std::find_if(vehicles_.begin(), vehicles_.end(), [&](const Vehicle& v) { return v.vin == vin; }); return it == vehicles_.end() ? nullptr : &*it; } void VehicleStore::upsert(const Vehicle& vehicle) { auto it = std::find_if(vehicles_.begin(), vehicles_.end(), [&](const Vehicle& v) { return v.vin == vehicle.vin; }); if (it == vehicles_.end()) vehicles_.push_back(vehicle); else *it = vehicle; } bool VehicleStore::remove(const std::string& vin) { const auto before = vehicles_.size(); vehicles_.erase(std::remove_if(vehicles_.begin(), vehicles_.end(), [&](const Vehicle& v) { return v.vin == vin; }), vehicles_.end()); return vehicles_.size() != before; } // --- settings --------------------------------------------------------------------------------- fs::path Settings::effectiveDownloadDir() const { return downloadDir.empty() ? paths::defaultDownloadDir() : downloadDir; } Settings Settings::load(const fs::path& file) { Settings s; std::error_code ec; if (!fs::exists(file, ec)) return s; const json doc = parseJson(readFile(file), file.string()); s.language = str(doc, "language"); s.downloadDir = str(doc, "downloadPath"); if (auto it = doc.find("checkAppUpdates"); it != doc.end() && it->is_boolean()) s.checkAppUpdates = it->get(); auto p = doc.find("pendingDownload"); if (p != doc.end() && p->is_object() && !str(*p, "vin").empty()) { PendingDownload d; d.vin = str(*p, "vin"); d.firmware = boolean(*p, "firmware"); d.map = boolean(*p, "map"); d.firmwareVersion = str(*p, "firmwareVersion"); d.mapVersion = str(*p, "mapVersion"); d.firmwareFile = str(*p, "firmwareFile"); d.mapFile = str(*p, "mapFile"); d.licenseFile = str(*p, "licenseFile"); s.pending = d; } return s; } void Settings::save(const fs::path& file) const { json doc = json::object(); if (!language.empty()) doc["language"] = language; if (!downloadDir.empty()) doc["downloadPath"] = downloadDir.string(); doc["checkAppUpdates"] = checkAppUpdates; if (pending) { doc["pendingDownload"] = { {"vin", pending->vin}, {"firmware", pending->firmware}, {"map", pending->map}, {"firmwareVersion", pending->firmwareVersion}, {"mapVersion", pending->mapVersion}, {"firmwareFile", pending->firmwareFile}, {"mapFile", pending->mapFile}, {"licenseFile", pending->licenseFile}, }; } writeFileAtomically(file, doc.dump(2) + "\n"); } } // namespace openpu