Download::Download(const URL& url) :
m_data(),
m_url(url),
m_size(0),
m_state(Stopped),
m_function([](bool, const std::string&) {}){
fetchMetadata();
}
Download::~Download() {
m_thread.join();
}
void Download::onComplete(std::function<void (bool success, const std::string&)> function) {
m_function = function;
}
void Download::start() {
m_state = Downloading;
m_thread = std::thread(&Download::run, this);
}
int Download::getSize() const {
return m_size;
}
Download::State Download::getState() const {
return m_state;
}
bool Download::isComplete() const {
return m_state == Complete;
}
void Download::fetchMetadata() {
sf::Http http(m_url.getProtocol() + "://" + m_url.getHost());
sf::Http::Request request(m_url.getPath(), sf::Http::Request::Head);
sf::Http::Response response = http.sendRequest(request);
if (response.getStatus() == sf::Http::Response::Ok) {
m_size = std::stoi(response.getField("Content-Length"));
}
}
void Download::run() {
sf::Http http(m_url.getProtocol() + "://" + m_url.getHost());
sf::Http::Request request(m_url.getPath(), sf::Http::Request::Get);
sf::Http::Response response = http.sendRequest(request);
bool success;
if (response.getStatus() == sf::Http::Response::Ok) {
m_state = Complete;
m_data = response.getBody();
success = true;
} else {
m_state = Error;
success = false;
}
if (m_function) {
m_function(success, m_data);
}
}