Files
Echoion/src/Core/Url.cpp
T
2026-01-18 18:22:09 +03:00

65 lines
2.0 KiB
C++

#include <ts6bot/Url.hpp>
#include <curl/curl.h>
#include <stdexcept>
#include <string_view>
namespace ts6bot::url {
std::string EncodeComponent(const std::string& s) {
CURL* h = curl_easy_init();
if (!h) throw std::runtime_error("curl_easy_init failed");
char* esc = curl_easy_escape(h, s.c_str(), static_cast<int>(s.size()));
curl_easy_cleanup(h);
if (!esc) throw std::runtime_error("curl_easy_escape failed");
std::string out{esc};
curl_free(esc);
return out;
}
static bool starts_with(std::string_view s, std::string_view p) {
return s.size() >= p.size() && s.substr(0, p.size()) == p;
}
HttpUrl ParseHttpUrl(const std::string& httpUrl) {
std::string_view s{httpUrl};
if (!starts_with(s, "http://")) {
throw std::runtime_error("redirect_uri must start with http://");
}
s.remove_prefix(7);
// host[:port][/path]
auto slash = s.find('/');
std::string_view hostPort = (slash == std::string_view::npos) ? s : s.substr(0, slash);
std::string_view path = (slash == std::string_view::npos) ? std::string_view{"/"} : s.substr(slash);
auto colon = hostPort.rfind(':');
if (colon == std::string_view::npos) {
throw std::runtime_error("redirect_uri must include explicit :port");
}
HttpUrl out;
out.host = std::string(hostPort.substr(0, colon));
if (out.host.empty()) throw std::runtime_error("redirect_uri host empty");
auto portSv = hostPort.substr(colon + 1);
if (portSv.empty()) throw std::runtime_error("redirect_uri port empty");
unsigned long port = 0;
for (char c : portSv) {
if (c < '0' || c > '9') throw std::runtime_error("redirect_uri port not numeric");
port = port * 10 + static_cast<unsigned long>(c - '0');
if (port > 65535) throw std::runtime_error("redirect_uri port out of range");
}
out.port = static_cast<uint16_t>(port);
out.path = std::string(path);
if (out.path.empty() || out.path[0] != '/') out.path = "/" + out.path;
return out;
}
} // namespace ts6bot::url