From 72fafe4553e075c040734e31164e50c4cdc7f319 Mon Sep 17 00:00:00 2001 From: wuesk Date: Tue, 22 Sep 2026 13:30:39 +0200 Subject: initial commit --- src/guestbook.cpp | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/guestbook.cpp (limited to 'src/guestbook.cpp') diff --git a/src/guestbook.cpp b/src/guestbook.cpp new file mode 100644 index 0000000..0b58ddf --- /dev/null +++ b/src/guestbook.cpp @@ -0,0 +1,78 @@ +#include "guestbook.hpp" +#include "json.hpp" + +#include +#include +#include + +using json = nlohmann::json; + +namespace { + const std::filesystem::path guestbookFilePath = "data/guestbook.json"; +} + +std::vector loadGuestbook() +{ + std::ifstream file(guestbookFilePath); + + if (!file.is_open()) + { + return {}; + } + + if (file.peek() == std::ifstream::traits_type::eof()) + { + return {}; + } + + // An existing but empty file is not valid JSON. Treat it like a new + // guestbook so a partially initialized data directory cannot crash the + // server during startup. + json data = json::parse(file, nullptr, false); + + if (data.is_discarded() || !data.is_array()) + { + std::cerr << "Warning: ignoring invalid guestbook data in " + << guestbookFilePath << '\n'; + return {}; + } + + std::vector entries; + + for (const auto& item : data) + { + GuestbookEntry entry; + entry.name = item.at("name").get(); + entry.message = item.at("message").get(); + + entries.push_back(entry); + } + + return entries; +} + +bool saveGuestbook(const std::vector& entries) +{ + std::filesystem::create_directories(guestbookFilePath.parent_path()); + + json data = json::array(); + + for (const GuestbookEntry& entry : entries) + { + data.push_back({ + {"name", entry.name}, + {"message", entry.message} + }); + } + + std::ofstream file(guestbookFilePath); + + if (!file.is_open()) + { + return false; + } + + file << data.dump(4); + + return true; +} -- cgit v1.2.3