blob: dacc04a45ed24eb65ee485d0cafa4ef1eda9142d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#include <iostream>
#include <fstream>
#include <cpr/cpr.h>
#include "DownloadManager.h"
DownloadManager::DownloadManager() { }
DownloadManager::~DownloadManager() {
for (std::thread* download : download_queue) {
download->join();
delete download;
download = nullptr;
}
}
std::fstream* DownloadManager::open_file(std::string filename) {
while (this->file_queue.size() > this->max_files);
std::fstream* out = nullptr;
do {
delete out;
out = new std::fstream(filename, std::ios::out | std::ios::binary);
} while (!out->is_open());
this->file_queue.push_back(out);
return out;
}
void DownloadManager::close_file(std::fstream* file_ptr) {
file_ptr->close();
delete file_ptr;
this->file_queue.erase(std::remove(this->file_queue.begin(), this->file_queue.end(), file_ptr));
}
std::thread* DownloadManager::wget(std::string url, std::string filename) {
std::thread* download = new std::thread([url, filename, this] {
cpr::Response res;
do res = cpr::Get(cpr::Url{url});
while (res.status_code != 200);
std::fstream* file = this->open_file(filename);
file->write(res.text.data(), res.downloaded_bytes); // can't use << for binary data
this->close_file(file);
});
download_queue.push_back(download);
return download;
}
|