1
0
mirror of synced 2024-12-24 13:34:50 +01:00
ImHex/lib/libimhex/include/hex/helpers/http_requests_emscripten.hpp

76 lines
2.6 KiB
C++
Raw Normal View History

#pragma once
2024-02-29 19:48:16 +01:00
#if defined(OS_WEB)
2024-02-29 19:48:16 +01:00
#include <future>
2024-02-29 19:48:16 +01:00
#include <emscripten/fetch.h>
2024-02-29 19:48:16 +01:00
namespace hex {
template<typename T>
std::future<HttpRequest::Result<T>> HttpRequest::downloadFile(const std::fs::path &path) {
return std::async(std::launch::async, [this, path] {
std::vector<u8> response;
2024-02-29 19:48:16 +01:00
// Execute the request
auto result = this->executeImpl<T>(response);
2024-02-29 19:48:16 +01:00
// Write the result to the file
wolv::io::File file(path, wolv::io::File::Mode::Create);
file.writeBuffer(reinterpret_cast<const u8*>(result.getData().data()), result.getData().size());
2024-02-29 19:48:16 +01:00
return result;
});
}
2024-02-29 19:48:16 +01:00
template<typename T>
std::future<HttpRequest::Result<T>> HttpRequest::uploadFile(const std::fs::path &path, const std::string &mimeName) {
hex::unused(path, mimeName);
throw std::logic_error("Not implemented");
}
2024-02-29 19:48:16 +01:00
template<typename T>
std::future<HttpRequest::Result<T>> HttpRequest::uploadFile(std::vector<u8> data, const std::string &mimeName, const std::fs::path &fileName) {
hex::unused(data, mimeName, fileName);
throw std::logic_error("Not implemented");
}
2024-02-29 19:48:16 +01:00
template<typename T>
std::future<HttpRequest::Result<T>> HttpRequest::execute() {
return std::async(std::launch::async, [this] {
std::vector<u8> responseData;
2024-02-29 19:48:16 +01:00
return this->executeImpl<T>(responseData);
});
}
2024-02-29 19:48:16 +01:00
template<typename T>
HttpRequest::Result<T> HttpRequest::executeImpl(std::vector<u8> &data) {
strcpy(m_attr.requestMethod, m_method.c_str());
m_attr.attributes = EMSCRIPTEN_FETCH_SYNCHRONOUS | EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
if (!m_body.empty()) {
m_attr.requestData = m_body.c_str();
m_attr.requestDataSize = m_body.size();
}
2024-02-29 19:48:16 +01:00
std::vector<const char*> headers;
for (auto it = m_headers.begin(); it != m_headers.end(); it++) {
headers.push_back(it->first.c_str());
headers.push_back(it->second.c_str());
}
headers.push_back(nullptr);
m_attr.requestHeaders = headers.data();
2024-02-29 19:48:16 +01:00
// Send request
emscripten_fetch_t* fetch = emscripten_fetch(&m_attr, m_url.c_str());
data.resize(fetch->numBytes);
std::copy(fetch->data, fetch->data + fetch->numBytes, data.begin());
return Result<T>(fetch->status, { data.begin(), data.end() });
}
}
2024-02-29 19:48:16 +01:00
#endif