1#pragma once
2
3#include <framework/global.h>
4
5#include <iostream>
6#include <string>
7#include <memory>
8#include <functional>
9#include <future>
10
11#include "result.h"
12
13class HttpSession : public std::enable_shared_from_this<HttpSession>
14{
15public:
16
17 HttpSession(boost::asio::io_service& service, const std::string& url, const std::string& agent,
18 int timeout, bool isJson, HttpResult_ptr result, HttpResult_cb callback) :
19 m_service(service), m_url(url), m_agent(agent), m_socket(service), m_resolver(service),
20 m_callback(callback), m_result(result), m_timer(service), m_timeout(timeout), m_isJson(isJson)
21 {
22 VALIDATE(m_callback);
23 VALIDATE(m_result);
24 };
25
26 void start();
27 void cancel() { onError("canceled"); }
28
29private:
30 boost::asio::io_service& m_service;
31 std::string m_url;
32 std::string m_agent;
33 int m_port;
34 boost::asio::ip::tcp::socket m_socket;
35 boost::asio::ip::tcp::resolver m_resolver;
36 HttpResult_cb m_callback;
37 HttpResult_ptr m_result;
38 boost::asio::steady_timer m_timer;
39 int m_timeout;
40 bool m_isJson = false;
41
42 std::string m_domain;
43 std::shared_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>> m_ssl;
44 std::shared_ptr<boost::asio::ssl::context> m_context;
45
46 boost::beast::flat_buffer m_streambuf{ 512 * 1024 * 1024 }; // limited to 512MB
47 boost::beast::http::request<boost::beast::http::string_body> m_request;
48 boost::beast::http::response_parser<boost::beast::http::dynamic_body> m_response;
49
50 void on_resolve(const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator iterator);
51 void on_connect(const boost::system::error_code& ec);
52 void on_request_sent(const boost::system::error_code& ec);
53 void on_read_header(const boost::system::error_code & ec, size_t bytes_transferred);
54 void on_read(const boost::system::error_code& ec, size_t bytes_transferred);
55 void close();
56 void onTimeout(const boost::system::error_code& error);
57 void onError(const std::string& error, const std::string& details = "");
58};