diff --git a/include/data.hpp b/include/data.hpp new file mode 100644 index 0000000..3840bd3 --- /dev/null +++ b/include/data.hpp @@ -0,0 +1,14 @@ +#pragma once +#include +#include + +namespace fs = std::experimental::filesystem; + +class data : public json { + fs::path &get_data_path(); + void create_data_directory(); + fs::path get_store_path(); + +public: + data(); +}; diff --git a/include/store.hpp b/include/store.hpp index a8ffe32..02c8161 100644 --- a/include/store.hpp +++ b/include/store.hpp @@ -1,9 +1,11 @@ #pragma once +#include #include #include class Application { HttpServer http_server; + data dat; static void web_server_started(std::size_t port); static void secure_web_server_started(std::size_t port); diff --git a/src/data.cpp b/src/data.cpp new file mode 100644 index 0000000..704e42d --- /dev/null +++ b/src/data.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include + +fs::path &data::get_data_path() { + static fs::path p(""); + if (p.native().length() != 0) { + return p; + } + const int uid = getuid(); + if (uid == 0) { + p = fs::path("/") / "var" / "lib" / "store"; + } else if (const auto ptr = std::getenv("HOME")) { + p = fs::path(ptr) / ".local" / "lib" / "store"; + } + return p; +} + +data::data() : json(json::object()) { + if (!fs::exists(get_data_path())) { + create_data_directory(); + } + const auto data_file = get_store_path(); + if (!fs::exists(data_file)) { + try { + std::ofstream f(data_file); + f << json::object(); + } catch (const std::exception &e) { + std::cerr << "Could not create config file:\n" << e.what() << std::endl; + } + } +} + +void data::create_data_directory() { + std::error_code ec; + fs::create_directories(get_data_path(), ec); + if (ec) { + std::cerr << "Unable to create configuration directory:\n" << ec.message(); + } +} + +fs::path data::get_store_path() { return get_data_path() / "store.json"; }