mastorss/src/http.cpp

88 lines
2.4 KiB
C++
Raw Permalink Normal View History

2018-02-10 12:35:06 +01:00
/* This file is part of mastorss.
2019-04-21 03:38:15 +02:00
* Copyright © 2018, 2019 tastytea <tastytea@tastytea.de>
*
2018-01-26 02:33:58 +01:00
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <cstdint>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
2018-02-10 10:01:17 +01:00
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>
#include <curlpp/Infos.hpp>
2018-02-10 12:35:06 +01:00
#include "mastorss.hpp"
2018-01-26 02:33:58 +01:00
using std::string;
using std::cerr;
2018-02-10 10:01:17 +01:00
namespace curlopts = curlpp::options;
2018-01-26 02:33:58 +01:00
void curlpp_init()
{
curlpp::initialize();
}
2019-04-21 03:38:15 +02:00
std::uint16_t http_get(const string &feedurl, string &answer,
const string &useragent)
2018-01-26 02:33:58 +01:00
{
try
{
std::ostringstream oss;
2018-02-10 10:01:17 +01:00
curlpp::Easy request;
request.setOpt<curlopts::Url>(feedurl);
request.setOpt<curlopts::UserAgent>(useragent);
request.setOpt<curlopts::HttpHeader>(
2018-01-26 02:33:58 +01:00
{
2018-02-10 10:01:17 +01:00
"Connection: close",
});
request.setOpt<curlopts::FollowLocation>(true);
request.setOpt<curlopts::WriteStream>(&oss);
2019-04-21 03:38:15 +02:00
request.perform();
std::uint16_t ret = curlpp::infos::ResponseCode::get(request);
if (ret == 200 || ret == 302 || ret == 307)
{ // OK or Found or Temporary Redirect
answer = oss.str();
}
else if (ret == 301 || ret == 308)
{ // Moved Permanently or Permanent Redirect
// FIXME: The new URL should be passed back somehow
answer = oss.str();
}
else
{
return ret;
}
2018-02-10 10:01:17 +01:00
return 0;
}
2018-02-28 22:51:25 +01:00
// TODO: More error codes
2018-02-10 10:01:17 +01:00
catch (curlpp::RuntimeError &e)
{
cerr << "RUNTIME ERROR: " << e.what() << std::endl;
return 0xffff;
2018-01-26 02:33:58 +01:00
}
2018-02-10 10:01:17 +01:00
catch (curlpp::LogicError &e)
2018-01-26 02:33:58 +01:00
{
2018-02-10 10:01:17 +01:00
cerr << "LOGIC ERROR: " << e.what() << std::endl;
2018-01-26 02:33:58 +01:00
return 0xffff;
}
return 0;
}