added JSON support to select the services

This commit is contained in:
2025-05-27 21:33:15 +02:00
parent d9d0643dfc
commit 1e9a377c2a
19 changed files with 26060 additions and 139 deletions

72
src/main.cpp Normal file
View File

@@ -0,0 +1,72 @@
#include <crow.h>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <string>
#include <optional>
#include "json_settings.h"
#include "htmx_helper.h"
#include "systemd.h"
using namespace std;
string load_file(const string& path) {
ifstream f(path);
stringstream buffer;
buffer << f.rdbuf();
return buffer.str();
}
optional<string> get_body_name(const string& body) {
const auto pos = body.find('=');
if (pos == std::string::npos) return {};
const string key = body.substr(0, pos);
string value = body.substr(pos + 1);
if (key != "name") return {};
return value;
}
int main() {
crow::SimpleApp app;
CROW_ROUTE(app, "/")([] {
return crow::response(load_file("templates/index.html"));
});
CROW_ROUTE(app, "/static/<string>")([](const std::string& file) {
return crow::response(load_file("static/" + file));
});
CROW_ROUTE(app, "/status")([] {
auto table = create_service_table();
return crow::response{table.htmx()};
});
CROW_ROUTE(app, "/toggle-service").methods(crow::HTTPMethod::Post)([](const crow::request& req) {
auto body = get_body_name(req.body);
if (!body.has_value())
return crow::response(400);
const string& serviceName = body.value();
auto opt_settings = AppSettings::loadAppSettings();
HtmxTableRow row;
if (opt_settings.has_value()) {
auto& settings = opt_settings.value();
const auto& service_id = settings.getId(serviceName).value_or(serviceName);
systemd::toggle_service(service_id);
row = create_service_table_row(serviceName, service_id);
}
else {
row = create_error_table_row(opt_settings.error());
}
return crow::response{row.htmx()};
});
app.port(8080).multithreaded().run();
}