tv_rename/network.cpp
2019-02-04 17:39:48 +01:00

84 lines
2.4 KiB
C++

#include <iostream>
#include "network.hpp"
#ifdef _WIN32
// shamelessly stolen from http://www.cplusplus.com/forum/windows/109799/
Curl::Curl() {
connect = InternetOpen( L"WinInet/1.0", INTERNET_OPEN_TYPE_PRECONFIG,
nullptr, nullptr, 0 );
if ( !connect )
std::wcerr << "Something went wrong while connecting" << std::endl;
}
Curl::~Curl() {
if ( connect )
InternetCloseHandle( connect );
}
std::string Curl::execute( const std::wstring &url ) {
std::string source{};
source.reserve( 10000 );
HINTERNET openAddress = InternetOpenUrl(
connect, url.c_str(), nullptr, 0,
INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION, 0 );
if ( !openAddress ) {
unsigned long errorNum = GetLastError();
std::wcout << "Failed to open URL" << std::endl
<< "Error No: " << errorNum << std::endl;
return "";
}
char dataReceived[4096];
unsigned long numberOfBytesRead = 0;
while ( InternetReadFile( openAddress, dataReceived, 4096,
&numberOfBytesRead ) &&
numberOfBytesRead ) {
source.append( dataReceived, numberOfBytesRead );
}
InternetCloseHandle( openAddress );
return source;
}
#else
size_t writeCallback( void *contents, size_t size, size_t nmemb,
void *target ) {
*static_cast< std::string * >( target ) +=
std::string( static_cast< char * >( contents ), size * nmemb );
return size * nmemb;
}
Curl::Curl() {
curl_global_init( CURL_GLOBAL_ALL );
curl_handle = curl_easy_init();
curl_easy_setopt( curl_handle, CURLOPT_WRITEFUNCTION, writeCallback );
curl_easy_setopt( curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0" );
}
Curl::~Curl() {
curl_easy_cleanup( curl_handle );
curl_global_cleanup();
}
std::string Curl::execute( const std::string &url ) {
std::string source;
source.reserve( 100000 );
curl_easy_setopt( curl_handle, CURLOPT_WRITEDATA,
static_cast< void * >( &source ) );
curl_easy_setopt( curl_handle, CURLOPT_URL, url.c_str() );
auto res = curl_easy_perform( curl_handle );
if ( res != CURLE_OK ) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror( res )
<< std::endl;
return "";
}
return source;
}
#endif