You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.7 KiB
72 lines
1.7 KiB
#include <data.hpp> |
|
#include <fstream> |
|
#include <iostream> |
|
#include <unistd.h> |
|
|
|
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"; } |
|
|
|
json data::process(const json &input) { |
|
if (!validate(input)) { |
|
return nullptr; |
|
} |
|
|
|
return input; |
|
} |
|
|
|
bool data::validate(const json &input) { |
|
const std::string name = input.value("name", ""); |
|
const std::string address = input.value("address", ""); |
|
const std::string phone = input.value("phone", ""); |
|
const std::string email = input.value("email", ""); |
|
|
|
const std::unordered_map<std::string, std::string> strings{ |
|
{"name", name}, {"address", address}, {"phone", phone}, {"email", email}}; |
|
|
|
for (const auto &f : strings) { |
|
if (f.second.size() == 0) { |
|
return false; |
|
} |
|
if (f.second.size() >= 255) { |
|
return false; |
|
} |
|
} |
|
|
|
return true; |
|
}
|
|
|