diff --git a/include/instance.hpp b/include/instance.hpp index 9afc423..6fdfc0d 100644 --- a/include/instance.hpp +++ b/include/instance.hpp @@ -17,6 +17,8 @@ #ifndef MASTODONPP_INSTANCE_HPP #define MASTODONPP_INSTANCE_HPP +#include + #include namespace mastodonpp @@ -41,10 +43,30 @@ public: * @since 0.1.0 */ explicit Instance(string instance, string access_token); + ~Instance(); private: const string _instance; string _access_token; + CURL *_connection; + char _curl_buffer_error[CURL_ERROR_SIZE]; + string _curl_buffer; + + + /*! + * @brief libcurl write callback function. + * + * @since 0.1.0 + */ + static int writer(char *data, size_t size, size_t nmemb, + string *writerData); + + /*! + * @brief Setup libcurl connection. + * + * @since 0.1.0 + */ + void setup_curl(); }; } // namespace mastodonpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 17b45dd..b2a0554 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,5 +1,7 @@ include(GNUInstallDirs) +find_package(CURL REQUIRED) + # Write version in header. configure_file ("version.hpp.in" "${PROJECT_BINARY_DIR}/version.hpp" @ONLY) @@ -22,9 +24,8 @@ target_include_directories(${PROJECT_NAME} "$" "$") -# target_link_libraries(${PROJECT_NAME} -# PRIVATE -# PUBLIC) +target_link_libraries(${PROJECT_NAME} + PRIVATE CURL::libcurl) install(TARGETS ${PROJECT_NAME} diff --git a/src/instance.cpp b/src/instance.cpp index 6b3443d..6cdc956 100644 --- a/src/instance.cpp +++ b/src/instance.cpp @@ -15,6 +15,7 @@ */ #include "instance.hpp" +#include "exceptions.hpp" #include @@ -26,6 +27,53 @@ using std::move; Instance::Instance(string instance, string access_token) : _instance{move(instance)} , _access_token{move(access_token)} -{} + , _connection{curl_easy_init()} +{ + setup_curl(); +} +Instance::~Instance() +{ + curl_easy_cleanup(_connection); +} + +int Instance::writer(char *data, size_t size, size_t nmemb, string *writerData) +{ + if(writerData == nullptr) + { + return 0; + } + + writerData->append(data, size*nmemb); + + return static_cast(size * nmemb); +} + +void Instance::setup_curl() +{ + if (_connection == nullptr) + { + throw CURLException{CURLE_FAILED_INIT, "Failed to initialize curl."}; + } + + CURLcode code{curl_easy_setopt(_connection, CURLOPT_ERRORBUFFER, + _curl_buffer_error)}; + if (code != CURLE_OK) + { + throw CURLException{code, "Failed to set error buffer."}; + } + + code = curl_easy_setopt(_connection, CURLOPT_WRITEFUNCTION, writer); + if (code != CURLE_OK) + { + throw CURLException{code, "Failed to set writer", _curl_buffer_error}; + } + + code = curl_easy_setopt(_connection, CURLOPT_WRITEDATA, &_curl_buffer); + if (code != CURLE_OK) + { + throw CURLException{code, "Failed to set write data", + _curl_buffer_error}; + } +} } // namespace mastodonpp