Files
shadowrun-server/source/main.cpp
2026-02-17 17:48:37 +01:00

88 lines
2.8 KiB
C++

#include <crow.h>
#include "crow/middlewares/cors.h"
#include <string>
#include "json_settings.h"
#include "utils.hpp"
#include "login.hpp"
#include "ShadowrunApi.hpp"
#include "databasepool.h"
using namespace std;
int main() {
AppSettings::Settings settings = AppSettings::load();
crow::App<crow::CORSHandler> app;
// init cors
auto& cors = app.get_middleware<crow::CORSHandler>();
cors.global()
.headers("Content-Type", "Authorization")
.methods("GET"_method, "POST"_method, "PUT"_method, "DELETE"_method, "OPTIONS"_method)
.origin(settings.domain);
// create global database
dbpool = std::make_unique<DatabasePool>(settings.db_path);
if (!dbpool->init(std::thread::hardware_concurrency())){
CROW_LOG_ERROR << "Failed to create database at : " << settings.db_path;
return 1;
}
auto opt_isPortOpen = utils::isLocalPortOpen(settings.http_port);
if (opt_isPortOpen.has_value()){
if (opt_isPortOpen.value()){
CROW_LOG_ERROR << "Local port : " << settings.http_port << " is already open";
return 1;
}
}
else {
CROW_LOG_ERROR << "failed to check if local port is open : " << opt_isPortOpen.error();
return 1;
}
// options path
CROW_ROUTE(app, "/<path>") .methods("OPTIONS"_method)
([&settings](const crow::request&, crow::response& res, const std::string&) {
res.add_header("Access-Control-Allow-Origin", settings.domain);
res.add_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.add_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.add_header("Access-Control-Max-Age", "86400"); // Cache preflight for 24h
res.code = 204;
res.end();
});
// Root route
CROW_ROUTE(app, "/")([&]() {
return utils::getFile(utils::build_dir / "index.html");
});
CROW_ROUTE(app, "/favicon.ico").methods(crow::HTTPMethod::Get)
([&]() {
return utils::getFile(utils::assets_dir / "favicon.ico");
});
shadowrun::initApi(app);
login::initLogin(app);
// asssets is not svelte generated
CROW_ROUTE(app, "/assets/<path>")
([&](const std::string& p) {
filesystem::path file_path = utils::assets_dir / p;
return utils::getFile(file_path);
});
// Catch-all route for static files and SPA fallback
CROW_ROUTE(app, "/<path>")
([&](const std::string& p) {
filesystem::path file_path = utils::build_dir / p;
// If path is a directory, serve index.html inside it
if (filesystem::is_directory(file_path))
file_path /= "index.html";
return utils::getFile(file_path);
});
app.loglevel(crow::LogLevel::INFO);
app.bindaddr("0.0.0.0").port(settings.http_port).multithreaded().run();
}