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.

98 lines
2.4 KiB

#ifndef _TR_UTIL_HPP_
#define _TR_UTIL_HPP_
#include <json.hpp>
#include <libtorrent/sha1_hash.hpp>
#include <unordered_map>
namespace util {
class uri {
public:
auto static parse(const std::string &request_path) {
std::unordered_map<std::string, std::string> options;
std::string option, value;
bool collect = false;
for (auto &c : request_path) {
switch (c) {
case '&':
options.insert(std::make_pair(option, value));
option = "";
collect = true;
break;
case '?':
collect = true;
break;
case '=':
collect = false;
value = "";
break;
default:
if (collect)
option += c;
else
value += c;
break;
}
}
if (!option.empty() || !value.empty())
options.insert(std::make_pair(option, value));
return options;
}
};
struct sha1 {
static auto string(const std::string &hex_str) {
libtorrent::sha1_hash sha1_hash;
std::stringstream ss;
ss << hex_str;
ss >> sha1_hash;
return sha1_hash;
};
static auto info_hash(const libtorrent::sha1_hash &info_hash) {
std::stringstream ss;
ss << info_hash;
std::string res = ss.str();
return res;
};
};
class json {
public:
/*! @brief Wrapper for nlohmann::json::parse. If the parse fails, result.is_null() will be */
static nlohmann::json parse(std::istream &istream) {
try {
return nlohmann::json::parse(istream);
} catch (const std::invalid_argument &exp) {
}
return nlohmann::json(nullptr);
}
/*! @brief wrapper around nlohmann::json::parse, but object returns null on throw */
static nlohmann::json parse(const std::string &string) {
try {
return nlohmann::json::parse(string);
} catch (const std::invalid_argument &exp) {
}
return nlohmann::json(nullptr);
}
static bool has_property(const std::string &key, const nlohmann::json &object) {
auto it = object.find(key);
return it != object.end();
}
template <class T>
static auto get(const std::string &key, const nlohmann::json &object, const T &default_value) {
if (has_property(key, object)) {
T r;
try {
r = object[key]; //TODO fix use json parser where a non-throwable exist
} catch (const std::exception &) {
return default_value;
}
return r;
}
return default_value;
}
};
}
#endif