Refactor image loading to a separate class. Add dependency to curl
[claws.git] / src / plugins / litehtml_viewer / http.cpp
1 #include "http.h"
2
3 http::http()
4 {
5     curl = curl_easy_init();
6     curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
7     curl_easy_setopt(curl, CURLOPT_TIMEOUT, HTTP_GET_TIMEOUT);
8     curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
9     curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
10     curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 120L);
11     curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 60L);
12     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http::curl_write_data);
13     response_data = NULL;
14     response_size = 0;;
15 }
16
17 http::~http()
18 {
19     curl_easy_cleanup(curl);
20     if (response_data) {
21         g_free(response_data);
22     }
23 }
24
25 size_t http::curl_write_data(char* ptr, size_t size, size_t nmemb, void* data) {
26         if (!response_data)
27                 response_data = (char *) malloc(size * nmemb);
28         else
29                 response_data = (char *) realloc(response_data, response_size + size * nmemb);
30         if (response_data) {
31                 memcpy(response_data + response_size, ptr, size * nmemb);
32                 response_size += size * nmemb;
33         }
34         return size * nmemb;
35 }
36
37 void http::destroy_giostream(gpointer data) {
38         GInputStream* gio;
39         if (data) {
40                 gio = G_INPUT_STREAM(data);
41                 g_input_stream_close(gio, NULL, NULL);
42                 gio = NULL;
43         }
44 }
45
46 GInputStream *http::load_url(const gchar *url, GError **error)
47 {
48         GError* _error = NULL;
49         CURLcode res = CURLE_OK;
50         gsize len;
51         gchar* content;
52     GInputStream* stream = NULL;
53
54
55         if (!strncmp(url, "file:///", 8) || g_file_test(url, G_FILE_TEST_EXISTS)) {
56                 gchar* newurl = g_filename_from_uri(url, NULL, NULL);
57                 if (g_file_get_contents(newurl ? newurl : url, &content, &len, &_error)) {
58                         stream = g_memory_input_stream_new_from_data(content, len, http::destroy_giostream);
59                 } else {
60                         g_log(NULL, G_LOG_LEVEL_MESSAGE, "%s", _error->message);
61                 }
62                 g_free(newurl);
63         } else {
64                 if (!curl) return NULL;
65             curl_easy_setopt(curl, CURLOPT_URL, url);
66             curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_data);
67             res = curl_easy_perform(curl);
68             if (res != CURLE_OK) {
69                     _error = g_error_new_literal(G_FILE_ERROR, res, curl_easy_strerror(res));
70             } else {
71                 stream = g_memory_input_stream_new_from_data(response_data, response_size, http::destroy_giostream);
72             }
73         }
74
75         if (error && _error) *error = _error;
76
77         return stream;
78 }
79