Szontágh Ferenc
2025-03-12 77bc7063534ab317a2ef96249a4f78198d01ef01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#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