coyote/settings.cpp

76 lines
2.2 KiB
C++
Raw Normal View History

#include <string>
#include <stdexcept>
#include "settings.h"
static void set_settings(std::string_view str, const char* delimiter, UserSettings& settings);
static inline bool lowercase_compare(std::string_view lhs, std::string_view rhs);
static bool parse_bool(std::string_view value);
void UserSettings::set(std::string_view key, std::string_view value) {
if (key == "auto-open-cw") {
this->auto_open_cw = parse_bool(value);
}
}
void UserSettings::load_from_cookies(const httplib::Request& req) {
for (const auto& i : req.headers) {
if (lowercase_compare(i.first, "cookie")) {
set_settings(i.second, "; ", *this);
}
}
}
static void set_settings(std::string_view str, const char* delimiter, UserSettings& settings) {
using namespace std::string_literals;
size_t offset = 0;
size_t new_offset = 0;
size_t delimiter_len = strlen(delimiter);
while (offset < str.size()) {
new_offset = str.find(delimiter, offset);
std::string_view item = str.substr(offset, new_offset != std::string_view::npos ? new_offset - offset : std::string_view::npos);
size_t equal_offset = item.find('=');
if (equal_offset == std::string_view::npos) {
throw std::invalid_argument("invalid user setting item: "s + std::string(item));
}
settings.set(item.substr(0, equal_offset), item.substr(equal_offset + 1));
if (new_offset == std::string_view::npos) {
break;
}
offset = new_offset + delimiter_len;
}
}
static inline bool lowercase_compare(std::string_view lhs, std::string_view rhs) {
if (lhs.size() != rhs.size()) {
return false;
}
auto lower = [](char c) {
return c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c;
};
for (size_t i = 0; i < lhs.size(); i++) {
if (lower(lhs[i]) != lower(rhs[i])) {
return false;
}
}
return true;
}
static bool parse_bool(std::string_view value) {
using namespace std::string_literals;
if (value == "true") {
return true;
} else if (value == "false") {
return false;
} else {
throw std::invalid_argument("unknown boolean value: "s + std::string(value));
}
}