ZLMediaKit/src/Http/HttpDownloader.cpp

75 lines
2.1 KiB
C++
Raw Normal View History

2017-10-09 22:11:01 +08:00
/*
2020-04-04 20:30:09 +08:00
* Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
2017-09-27 16:20:30 +08:00
*
* This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).
2017-09-27 16:20:30 +08:00
*
2020-04-04 20:30:09 +08:00
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
2017-05-05 18:02:54 +08:00
*/
#include "HttpDownloader.h"
#include "Util/File.h"
#include "Util/MD5.h"
2018-10-24 17:17:55 +08:00
using namespace toolkit;
2017-05-05 18:02:54 +08:00
2018-10-24 17:17:55 +08:00
namespace mediakit {
2017-05-05 18:02:54 +08:00
HttpDownloader::~HttpDownloader() {
2020-03-20 11:51:24 +08:00
closeFile();
2017-05-05 18:02:54 +08:00
}
2022-01-20 14:48:45 +08:00
void HttpDownloader::startDownload(const string &url, const string &file_path, bool append) {
_file_path = file_path;
if (_file_path.empty()) {
_file_path = exeDir() + "HttpDownloader/" + MD5(url).hexdigest();
2020-03-20 11:51:24 +08:00
}
2022-01-20 14:48:45 +08:00
_save_file = File::create_file(_file_path.data(), append ? "ab" : "wb");
if (!_save_file) {
auto strErr = StrPrinter << "打开文件失败:" << file_path << endl;
2020-03-20 11:51:24 +08:00
throw std::runtime_error(strErr);
}
2022-01-20 14:48:45 +08:00
if (append) {
auto currentLen = ftell(_save_file);
if (currentLen) {
2020-03-20 11:51:24 +08:00
//最少续传一个字节怕遇到http 416的错误
currentLen -= 1;
2022-01-20 14:48:45 +08:00
fseek(_save_file, -1, SEEK_CUR);
2020-03-20 11:51:24 +08:00
}
addHeader("Range", StrPrinter << "bytes=" << currentLen << "-" << endl);
}
setMethod("GET");
sendRequest(url);
2017-05-05 18:02:54 +08:00
}
2022-01-20 14:48:45 +08:00
void HttpDownloader::onResponseHeader(const string &status, const HttpHeader &headers) {
if (status != "200" && status != "206") {
2020-03-20 11:51:24 +08:00
//失败
2022-01-20 14:48:45 +08:00
throw std::invalid_argument("bad http status: " + status);
2020-03-20 11:51:24 +08:00
}
2017-05-05 18:02:54 +08:00
}
2022-01-20 14:48:45 +08:00
void HttpDownloader::onResponseBody(const char *buf, size_t size) {
if (_save_file) {
fwrite(buf, size, 1, _save_file);
2020-03-20 11:51:24 +08:00
}
2017-05-05 18:02:54 +08:00
}
2022-01-20 14:48:45 +08:00
void HttpDownloader::onResponseCompleted(const SockException &ex) {
2020-03-20 11:51:24 +08:00
closeFile();
2022-01-20 14:48:45 +08:00
if (_on_result) {
_on_result(ex, _file_path);
_on_result = nullptr;
2020-03-20 11:51:24 +08:00
}
2017-05-05 18:02:54 +08:00
}
void HttpDownloader::closeFile() {
2022-01-20 14:48:45 +08:00
if (_save_file) {
fflush(_save_file);
fclose(_save_file);
_save_file = nullptr;
2020-03-20 11:51:24 +08:00
}
2017-05-05 18:02:54 +08:00
}
2018-10-24 17:17:55 +08:00
} /* namespace mediakit */