1
0
mirror of synced 2024-12-14 08:42:54 +01:00
ImHex/lib/libimhex/include/hex/helpers/net.hpp

72 lines
2.0 KiB
C++
Raw Normal View History

#pragma once
#include <hex.hpp>
2021-08-29 22:15:18 +02:00
#include <cstring>
#include <future>
#include <optional>
2021-08-28 00:45:59 +02:00
#include <string>
#include <filesystem>
#include <atomic>
#include <nlohmann/json_fwd.hpp>
#include <curl/system.h>
#include <hex/helpers/fs.hpp>
2022-01-13 14:33:30 +01:00
using CURL = void;
struct curl_slist;
namespace hex {
template<typename T>
struct Response {
i32 code;
2021-08-28 00:45:59 +02:00
T body;
};
template<>
struct Response<void> {
i32 code;
};
class Net {
public:
Net();
~Net();
static constexpr u32 DefaultTimeout = 2'000;
2021-08-28 00:45:59 +02:00
std::future<Response<std::string>> getString(const std::string &url, u32 timeout = DefaultTimeout);
std::future<Response<nlohmann::json>> getJson(const std::string &url, u32 timeout = DefaultTimeout);
std::future<Response<std::string>> uploadFile(const std::string &url, const std::fs::path &filePath, u32 timeout = DefaultTimeout);
std::future<Response<void>> downloadFile(const std::string &url, const std::fs::path &filePath, u32 timeout = DefaultTimeout);
2021-08-28 00:45:59 +02:00
[[nodiscard]] std::string encode(const std::string &input);
[[nodiscard]] std::string decode(const std::string &input);
[[nodiscard]] float getProgress() const { return this->m_progress; }
2021-08-28 00:45:59 +02:00
void cancel() { this->m_shouldCancel = true; }
static void setProxy(const std::string &url);
2021-08-28 00:45:59 +02:00
private:
void setCommonSettings(std::string &response, const std::string &url, u32 timeout = 2000, const std::map<std::string, std::string> &extraHeaders = {}, const std::string &body = {});
std::optional<i32> execute();
2021-08-28 00:45:59 +02:00
friend int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow);
private:
CURL *m_ctx;
curl_slist *m_headers = nullptr;
2021-08-28 00:45:59 +02:00
std::mutex m_transmissionActive;
2022-02-01 22:09:44 +01:00
float m_progress = 0.0F;
2021-08-28 00:45:59 +02:00
bool m_shouldCancel = false;
static std::string s_proxyUrl;
};
}