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.
87 lines
2.1 KiB
87 lines
2.1 KiB
#ifndef _TR_UTIL_HPP_ |
|
#define _TR_UTIL_HPP_ |
|
|
|
#include <nlohmann/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 info_hash(const std::string &hex_str) { |
|
libtorrent::sha1_hash sha1_hash; |
|
std::stringstream ss; |
|
ss << hex_str; |
|
ss >> sha1_hash; |
|
return sha1_hash; |
|
}; |
|
static auto string(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); |
|
} |
|
template <class T> |
|
static T get(const std::string &key, const nlohmann::json &object, const T &default_value) { |
|
if (object.find(key) != object.end()) { |
|
return object[key]; |
|
} |
|
return default_value; |
|
} |
|
}; |
|
} |
|
|
|
#endif
|
|
|