#ifndef CURL_HTTP_HANDLER_H
|
#define CURL_HTTP_HANDLER_H
|
|
#include <curl/curl.h>
|
#include <map>
|
#include <wx/filesys.h>
|
#include <wx/log.h>
|
#include <wx/mstream.h>
|
#include <wx/webview.h>
|
|
class CurlHttpHandler : public wxWebViewHandler {
|
public:
|
CurlHttpHandler() : wxWebViewHandler("phttp") {}
|
|
wxFSFile *GetFile(const wxString &uri) override {
|
wxLogMessage("Curl HTTP Handler: Loading %s", uri);
|
|
// Check cache first
|
if (cache.find(uri) != cache.end()) {
|
return new wxFSFile(
|
new wxMemoryInputStream(cache[uri].data(), cache[uri].size()), uri,
|
"text/html", wxEmptyString, wxDateTime::Now());
|
new wxMemoryInputStream(cache[uri].data(), cache[uri].size()), uri,
|
"text/html";
|
}
|
|
// Fetch content using curl
|
std::string content = FetchURL(uri.ToStdString());
|
if (content.empty()) {
|
wxLogError("Failed to load %s", uri);
|
return nullptr;
|
}
|
|
// Cache the response
|
std::vector<char> buffer(content.begin(), content.end());
|
cache[uri] = buffer;
|
|
return new wxFSFile(
|
new wxMemoryInputStream(cache[uri].data(), cache[uri].size()), uri,
|
"text/html", wxEmptyString, wxDateTime::Now());
|
}
|
|
private:
|
static size_t WriteCallback(void *contents, size_t size, size_t nmemb,
|
std::string *output) {
|
size_t totalSize = size * nmemb;
|
output->append((char *)contents, totalSize);
|
return totalSize;
|
}
|
|
std::string FetchURL(const std::string &url) {
|
CURL *curl = curl_easy_init();
|
std::string response;
|
if (curl) {
|
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
|
curl_easy_perform(curl);
|
curl_easy_cleanup(curl);
|
}
|
return response;
|
}
|
|
std::map<wxString, std::vector<char>> cache;
|
};
|
|
#endif // CURL_HTTP_HANDLER_H
|