875 lines
24 KiB
C++
875 lines
24 KiB
C++
#include "stdafx.h"
|
|
#include "platform.h"
|
|
#include "download_engine.h"
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cstdio>
|
|
#include <cwctype>
|
|
|
|
|
|
namespace
|
|
{
|
|
std::wstring Trim(const std::wstring& text)
|
|
{
|
|
size_t begin = 0;
|
|
size_t end = text.size();
|
|
while (begin < end && iswspace(text[begin]) != 0)
|
|
++begin;
|
|
while (end > begin && iswspace(text[end - 1]) != 0)
|
|
--end;
|
|
return text.substr(begin, end - begin);
|
|
}
|
|
|
|
std::wstring GetDefaultSaveDir()
|
|
{
|
|
PWSTR known=nullptr;
|
|
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Downloads,KF_FLAG_DONT_VERIFY,nullptr,&known))) {
|
|
std::wstring directory(known); CoTaskMemFree(known); return directory;
|
|
}
|
|
wchar_t profile[MAX_PATH] = { 0 };
|
|
if (::GetEnvironmentVariableW(L"USERPROFILE", profile, MAX_PATH) == 0)
|
|
return L".";
|
|
return std::wstring(profile) + L"\\Downloads";
|
|
}
|
|
|
|
bool PathExists(const std::wstring& path)
|
|
{
|
|
return ::GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES;
|
|
}
|
|
|
|
int64_t GetFileSize(const std::wstring& path)
|
|
{
|
|
WIN32_FILE_ATTRIBUTE_DATA data = {};
|
|
if (!::GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &data))
|
|
return 0;
|
|
if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
|
|
return 0;
|
|
ULARGE_INTEGER size;
|
|
size.LowPart = data.nFileSizeLow;
|
|
size.HighPart = data.nFileSizeHigh;
|
|
return static_cast<int64_t>(size.QuadPart);
|
|
}
|
|
|
|
bool EnsureDirectory(const std::wstring& dir)
|
|
{
|
|
DWORD attributes = ::GetFileAttributesW(dir.c_str());
|
|
if (attributes != INVALID_FILE_ATTRIBUTES)
|
|
return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
|
return ::CreateDirectoryW(dir.c_str(), nullptr) == TRUE;
|
|
}
|
|
|
|
int HexDigit(wchar_t c)
|
|
{
|
|
if (c >= L'0' && c <= L'9')
|
|
return c - L'0';
|
|
if (c >= L'a' && c <= L'f')
|
|
return c - L'a' + 10;
|
|
if (c >= L'A' && c <= L'F')
|
|
return c - L'A' + 10;
|
|
return -1;
|
|
}
|
|
|
|
std::wstring PercentDecode(const std::wstring& text)
|
|
{
|
|
std::string bytes;
|
|
bytes.reserve(text.size());
|
|
for (size_t i = 0; i < text.size(); ++i)
|
|
{
|
|
wchar_t c = text[i];
|
|
if (c == L'%' && i + 2 < text.size())
|
|
{
|
|
int high = HexDigit(text[i + 1]);
|
|
int low = HexDigit(text[i + 2]);
|
|
if (high >= 0 && low >= 0)
|
|
{
|
|
bytes.push_back(static_cast<char>((high << 4) | low));
|
|
i += 2;
|
|
continue;
|
|
}
|
|
}
|
|
if (c < 0x80)
|
|
{
|
|
bytes.push_back(static_cast<char>(c));
|
|
}
|
|
else
|
|
{
|
|
int length = ::WideCharToMultiByte(CP_UTF8, 0, &c, 1, nullptr, 0, nullptr, nullptr);
|
|
if (length > 0)
|
|
{
|
|
char buffer[8] = { 0 };
|
|
::WideCharToMultiByte(CP_UTF8, 0, &c, 1, buffer, length, nullptr, nullptr);
|
|
bytes.append(buffer, length);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (bytes.empty())
|
|
return std::wstring();
|
|
std::wstring decoded = platform::FromUtf8(bytes);
|
|
return decoded.empty() ? text : decoded;
|
|
}
|
|
|
|
std::wstring SanitizeFileName(std::wstring name)
|
|
{
|
|
for (wchar_t& c : name)
|
|
{
|
|
if (c < 0x20 || wcschr(L"\\/:*?\"<>|", c) != nullptr)
|
|
c = L'_';
|
|
}
|
|
while (!name.empty() && (name.back() == L'.' || name.back() == L' '))
|
|
name.pop_back();
|
|
if (name.empty())
|
|
name = L"download";
|
|
|
|
auto stem=name.substr(0,name.find(L'.'));
|
|
bool reserved=_wcsicmp(stem.c_str(),L"CON")==0 || _wcsicmp(stem.c_str(),L"PRN")==0 || _wcsicmp(stem.c_str(),L"AUX")==0 || _wcsicmp(stem.c_str(),L"NUL")==0;
|
|
if (stem.size()==4 && stem[3]>=L'1' && stem[3]<=L'9')
|
|
reserved=reserved || _wcsnicmp(stem.c_str(),L"COM",3)==0 || _wcsnicmp(stem.c_str(),L"LPT",3)==0;
|
|
if (reserved) name=L"_"+name;
|
|
|
|
if (name.size() > 120)
|
|
{
|
|
size_t dot = name.find_last_of(L'.');
|
|
if (dot != std::wstring::npos && name.size() - dot <= 16)
|
|
name = name.substr(0, 120 - (name.size() - dot)) + name.substr(dot);
|
|
else
|
|
name.resize(120);
|
|
}
|
|
return name;
|
|
}
|
|
|
|
std::wstring FileNameFromUrl(const std::wstring& url,const http::Transport& transport)
|
|
{
|
|
http::UrlParts parts;
|
|
std::wstring path = url;
|
|
if (transport.ParseUrl(url, parts))
|
|
path = parts.path;
|
|
|
|
size_t query = path.find_first_of(L"?#");
|
|
if (query != std::wstring::npos)
|
|
path = path.substr(0, query);
|
|
|
|
size_t slash = path.find_last_of(L"/\\");
|
|
std::wstring segment = slash != std::wstring::npos ? path.substr(slash + 1) : path;
|
|
return SanitizeFileName(PercentDecode(segment));
|
|
}
|
|
|
|
bool UsedByTask(const std::map<int64_t, TaskInfo>& tasks, const std::wstring& path)
|
|
{
|
|
for (const auto& entry : tasks)
|
|
{
|
|
if (_wcsicmp(entry.second.save_path.c_str(), path.c_str()) == 0)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
std::wstring PickUniquePath(const std::wstring& dir, const std::wstring& file_name,
|
|
const std::map<int64_t, TaskInfo>& tasks)
|
|
{
|
|
std::wstring stem = file_name;
|
|
std::wstring extension;
|
|
size_t dot = file_name.find_last_of(L'.');
|
|
if (dot != std::wstring::npos && dot > 0)
|
|
{
|
|
stem = file_name.substr(0, dot);
|
|
extension = file_name.substr(dot);
|
|
}
|
|
|
|
for (int index = 0; index < 1000; ++index)
|
|
{
|
|
wchar_t name[160] = { 0 };
|
|
if (index == 0)
|
|
swprintf_s(name, L"%s", file_name.c_str());
|
|
else
|
|
swprintf_s(name, L"%s (%d)%s", stem.c_str(), index, extension.c_str());
|
|
|
|
std::wstring path = dir + L"\\" + name;
|
|
if (!PathExists(path) && !PathExists(path + L".tdpart") && !UsedByTask(tasks, path))
|
|
return path;
|
|
}
|
|
return dir + L"\\" + file_name;
|
|
}
|
|
|
|
std::wstring Win32ErrorText(DWORD code)
|
|
{
|
|
wchar_t* buffer = nullptr;
|
|
DWORD length = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
|
|
| FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, code, 0,
|
|
reinterpret_cast<wchar_t*>(&buffer), 0, nullptr);
|
|
if (length == 0 || buffer == nullptr)
|
|
{
|
|
wchar_t fallback[32] = { 0 };
|
|
swprintf_s(fallback, L"错误码 %u", code);
|
|
return fallback;
|
|
}
|
|
|
|
std::wstring text(buffer, length);
|
|
::LocalFree(buffer);
|
|
while (!text.empty() && (text.back() == L'\r' || text.back() == L'\n' || text.back() == L' '))
|
|
text.pop_back();
|
|
return text;
|
|
}
|
|
|
|
int64_t ParseContentRangeTotal(const std::wstring& value)
|
|
{
|
|
size_t slash = value.find_last_of(L'/');
|
|
if (slash == std::wstring::npos)
|
|
return 0;
|
|
std::wstring total = Trim(value.substr(slash + 1));
|
|
if (total.empty() || total == L"*")
|
|
return 0;
|
|
return _wcstoi64(total.c_str(), nullptr, 10);
|
|
}
|
|
}
|
|
|
|
DownloadEngine::DownloadEngine(HWND notify_wnd)
|
|
:DownloadEngine(notify_wnd,http::CreateDefaultTransport()) {}
|
|
|
|
DownloadEngine::DownloadEngine(HWND notify_wnd,std::unique_ptr<http::Transport> transport)
|
|
:notify_wnd_(notify_wnd),transport_(std::move(transport)) {
|
|
if (!transport_) transport_=http::CreateDefaultTransport();
|
|
}
|
|
|
|
DownloadEngine::~DownloadEngine()
|
|
{
|
|
Stop();
|
|
}
|
|
|
|
void DownloadEngine::Start()
|
|
{
|
|
if (thread_.joinable())
|
|
return;
|
|
thread_ = std::thread(&DownloadEngine::ThreadMain, this);
|
|
}
|
|
|
|
void DownloadEngine::Stop()
|
|
{
|
|
ready_=false;
|
|
{
|
|
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
|
stop_ = true;
|
|
}
|
|
cmd_cv_.notify_all();
|
|
if (thread_.joinable())
|
|
thread_.join();
|
|
}
|
|
|
|
void DownloadEngine::AddTask(const std::wstring& url, const std::wstring& save_dir)
|
|
{
|
|
Command cmd;
|
|
cmd.kind = Command::kAdd;
|
|
cmd.url = url;
|
|
cmd.save_dir = save_dir;
|
|
{
|
|
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
|
commands_.push_back(std::move(cmd));
|
|
}
|
|
cmd_cv_.notify_all();
|
|
}
|
|
|
|
std::shared_ptr<ExternalSubmission> DownloadEngine::SubmitExternal(ExternalDownload request) {
|
|
Command cmd; cmd.kind=Command::kAdd; cmd.url=request.url; cmd.save_dir=request.save_dir; cmd.external=std::move(request);
|
|
auto state=std::make_shared<ExternalSubmission>(); cmd.submission=state;
|
|
{ std::lock_guard lock(cmd_mutex_); commands_.push_back(std::move(cmd)); }
|
|
cmd_cv_.notify_all(); return state;
|
|
}
|
|
|
|
void DownloadEngine::PauseTask(int64_t id)
|
|
{
|
|
Command cmd;
|
|
cmd.kind = Command::kPause;
|
|
cmd.id = id;
|
|
{
|
|
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
|
commands_.push_back(std::move(cmd));
|
|
}
|
|
cmd_cv_.notify_all();
|
|
}
|
|
|
|
void DownloadEngine::ResumeTask(int64_t id)
|
|
{
|
|
Command cmd;
|
|
cmd.kind = Command::kResume;
|
|
cmd.id = id;
|
|
{
|
|
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
|
commands_.push_back(std::move(cmd));
|
|
}
|
|
cmd_cv_.notify_all();
|
|
}
|
|
|
|
void DownloadEngine::DeleteTask(int64_t id, bool delete_file)
|
|
{
|
|
Command cmd;
|
|
cmd.kind = Command::kDelete;
|
|
cmd.id = id;
|
|
cmd.delete_file = delete_file;
|
|
{
|
|
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
|
commands_.push_back(std::move(cmd));
|
|
}
|
|
cmd_cv_.notify_all();
|
|
}
|
|
|
|
void DownloadEngine::ThreadMain()
|
|
{
|
|
std::wstring local_data = platform::LocalAppData();
|
|
if (local_data.empty()) {
|
|
auto* event = new EngineEvent;
|
|
event->type = EngineEventType::kFatal;
|
|
event->message = L"无法定位用户应用数据目录,下载引擎未启动。";
|
|
PostEvent(event);
|
|
return;
|
|
}
|
|
std::wstring db_dir = local_data + L"\\TTDownloader";
|
|
::CreateDirectoryW(db_dir.c_str(), nullptr);
|
|
store_open_ = store_.Open(db_dir + L"\\tasks.db");
|
|
|
|
if (!store_open_)
|
|
{
|
|
EngineEvent* event = new EngineEvent;
|
|
event->type = EngineEventType::kFatal;
|
|
event->message = L"无法打开任务数据库,下载任务将不会被保存。";
|
|
PostEvent(event);
|
|
}
|
|
else
|
|
{
|
|
for (TaskInfo task : store_.LoadTasks())
|
|
{
|
|
if (task.file_name.empty())
|
|
{
|
|
std::wstring dir = task.save_path;
|
|
task.file_name = FileNameFromUrl(task.url,*transport_);
|
|
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
|
store_.UpdateTarget(task.id, task.save_path, task.file_name);
|
|
}
|
|
|
|
// 上次退出时仍在下载的任务自动续传;暂停和失败的任务保持原状
|
|
if (task.state == TaskState::kQueued || task.state == TaskState::kDownloading)
|
|
{
|
|
task.state = TaskState::kQueued;
|
|
task.downloaded_bytes = GetFileSize(task.save_path + L".tdpart");
|
|
store_.UpdateState(task.id, TaskState::kQueued, task.downloaded_bytes,
|
|
task.total_bytes, L"");
|
|
queue_.push_back(task.id);
|
|
}
|
|
tasks_[task.id] = task;
|
|
}
|
|
|
|
std::vector<TaskInfo> snapshot;
|
|
snapshot.reserve(tasks_.size());
|
|
for (const auto& entry : tasks_)
|
|
snapshot.push_back(entry.second);
|
|
|
|
EngineEvent* event = new EngineEvent;
|
|
event->type = EngineEventType::kSnapshot;
|
|
event->tasks = std::move(snapshot);
|
|
PostEvent(event);
|
|
}
|
|
|
|
ready_=store_open_;
|
|
while (!stop_)
|
|
{
|
|
DrainCommands();
|
|
if (stop_)
|
|
break;
|
|
|
|
if (!queue_.empty())
|
|
{
|
|
int64_t id = queue_.front();
|
|
queue_.pop_front();
|
|
|
|
auto it = tasks_.find(id);
|
|
if (it == tasks_.end() || it->second.state == TaskState::kCompleted)
|
|
continue;
|
|
|
|
TaskInfo task = it->second;
|
|
current_id_ = id;
|
|
cancel_current_ = false;
|
|
removed_current_ = false;
|
|
delete_file_current_ = false;
|
|
pause_current_ = false;
|
|
Download(task);
|
|
current_id_ = 0;
|
|
cancel_current_ = false;
|
|
removed_current_ = false;
|
|
delete_file_current_ = false;
|
|
pause_current_ = false;
|
|
|
|
auto live = tasks_.find(id);
|
|
if (live != tasks_.end() && live->second.state!=TaskState::kDeleted)
|
|
live->second = task;
|
|
continue;
|
|
}
|
|
|
|
std::unique_lock<std::mutex> lock(cmd_mutex_);
|
|
cmd_cv_.wait_for(lock, std::chrono::milliseconds(200),
|
|
[this]() { return stop_.load() || !commands_.empty(); });
|
|
}
|
|
|
|
ready_=false;
|
|
store_.Close();
|
|
}
|
|
|
|
void DownloadEngine::DrainCommands()
|
|
{
|
|
std::deque<Command> commands;
|
|
{
|
|
std::lock_guard<std::mutex> lock(cmd_mutex_);
|
|
commands.swap(commands_);
|
|
}
|
|
|
|
for (const Command& cmd : commands)
|
|
{
|
|
switch (cmd.kind)
|
|
{
|
|
case Command::kAdd:
|
|
HandleAdd(cmd);
|
|
break;
|
|
case Command::kPause:
|
|
HandlePause(cmd.id);
|
|
break;
|
|
case Command::kResume:
|
|
HandleResume(cmd.id);
|
|
break;
|
|
case Command::kDelete:
|
|
HandleDelete(cmd.id, cmd.delete_file);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void DownloadEngine::HandleAdd(const Command& cmd)
|
|
{
|
|
std::unique_lock<std::mutex> decision;
|
|
if (cmd.submission) {
|
|
decision=std::unique_lock<std::mutex>(cmd.submission->mutex);
|
|
if (cmd.submission->canceled) return;
|
|
}
|
|
auto reply=[&](const std::string& status,const std::wstring& message,int64_t id=0) {
|
|
if (!cmd.submission) return;
|
|
cmd.submission->status=status; cmd.submission->message=platform::ToUtf8(message);
|
|
cmd.submission->task_id=id; cmd.submission->done=true; cmd.submission->changed.notify_all();
|
|
};
|
|
auto reject=[&](const std::wstring& message) { reply("rejected",message); PostRejected(message,cmd.external.request_id); };
|
|
std::wstring url = Trim(cmd.url);
|
|
if (url.empty())
|
|
{
|
|
reject(L"下载链接不能为空");
|
|
return;
|
|
}
|
|
|
|
http::UrlParts parts;
|
|
if (!transport_->ParseUrl(url, parts))
|
|
{
|
|
reject(L"仅支持有效的 HTTP/HTTPS 链接");
|
|
return;
|
|
}
|
|
|
|
for (const auto& entry : tasks_)
|
|
{
|
|
if (entry.second.state==TaskState::kDeleted) {
|
|
if (!cmd.external.request_id.empty() && entry.second.request_id==cmd.external.request_id) { reject(L"原下载任务已删除"); return; }
|
|
continue;
|
|
}
|
|
if (!cmd.external.request_id.empty() && entry.second.request_id==cmd.external.request_id && entry.second.url!=url) {
|
|
reject(L"请求编号已用于其他下载地址"); return;
|
|
}
|
|
if (entry.second.url == url)
|
|
{
|
|
if (!cmd.external.request_id.empty() && entry.second.request_id==cmd.external.request_id)
|
|
reply("accepted",L"此请求已接管",entry.first);
|
|
else { reply("duplicate",L"链接已存在",entry.first); PostRejected(L"链接已存在",cmd.external.request_id); }
|
|
return;
|
|
}
|
|
}
|
|
|
|
std::wstring dir = Trim(cmd.save_dir);
|
|
if (dir.empty())
|
|
dir = GetDefaultSaveDir();
|
|
while (dir.size() > 3 && (dir.back() == L'\\' || dir.back() == L'/'))
|
|
dir.pop_back();
|
|
if (!EnsureDirectory(dir))
|
|
{
|
|
reject(L"保存目录不可用");
|
|
return;
|
|
}
|
|
|
|
TaskInfo task;
|
|
task.url = url;
|
|
task.file_name = FileNameFromUrl(url,*transport_);
|
|
if (!cmd.external.filename.empty()) {
|
|
auto slash=cmd.external.filename.find_last_of(L"/\\");
|
|
task.file_name=SanitizeFileName(cmd.external.filename.substr(slash==std::wstring::npos?0:slash+1));
|
|
}
|
|
task.request_id=cmd.external.request_id; task.referrer=cmd.external.referrer; task.user_agent=cmd.external.user_agent;
|
|
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
|
task.state = TaskState::kQueued;
|
|
|
|
if (!store_open_ || !store_.Insert(task))
|
|
{
|
|
reject(L"无法写入任务数据库");
|
|
return;
|
|
}
|
|
|
|
tasks_[task.id] = task;
|
|
queue_.push_back(task.id);
|
|
|
|
EngineEvent* event = new EngineEvent;
|
|
event->type = EngineEventType::kTaskAdded;
|
|
event->task = task;
|
|
event->request_id=cmd.external.request_id;
|
|
PostEvent(event);
|
|
reply("accepted",L"任务已保存并交给 TTDownloader",task.id);
|
|
}
|
|
|
|
void DownloadEngine::HandlePause(int64_t id)
|
|
{
|
|
auto it = tasks_.find(id);
|
|
if (it == tasks_.end() || it->second.state==TaskState::kDeleted)
|
|
return;
|
|
|
|
if (id == current_id_)
|
|
{
|
|
pause_current_ = true;
|
|
cancel_current_ = true;
|
|
return;
|
|
}
|
|
|
|
if (it->second.state != TaskState::kQueued)
|
|
return;
|
|
|
|
queue_.erase(std::remove(queue_.begin(), queue_.end(), id), queue_.end());
|
|
it->second.state = TaskState::kPaused;
|
|
it->second.downloaded_bytes = GetFileSize(it->second.save_path + L".tdpart");
|
|
if (store_open_)
|
|
store_.UpdateState(id, TaskState::kPaused, it->second.downloaded_bytes,
|
|
it->second.total_bytes, L"");
|
|
PostUpdate(it->second, 0.0);
|
|
}
|
|
|
|
void DownloadEngine::HandleResume(int64_t id)
|
|
{
|
|
auto it = tasks_.find(id);
|
|
if (it == tasks_.end() || it->second.state==TaskState::kDeleted)
|
|
return;
|
|
|
|
if (id == current_id_)
|
|
{
|
|
// 暂停还没处理完时点“开始”,继续原下载
|
|
if (pause_current_)
|
|
{
|
|
pause_current_ = false;
|
|
cancel_current_ = false;
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (it->second.state != TaskState::kPaused && it->second.state != TaskState::kFailed)
|
|
return;
|
|
|
|
TaskInfo& task = it->second;
|
|
task.state = TaskState::kQueued;
|
|
task.error.clear();
|
|
task.downloaded_bytes = GetFileSize(task.save_path + L".tdpart");
|
|
if (store_open_)
|
|
store_.UpdateState(task.id, TaskState::kQueued, task.downloaded_bytes,
|
|
task.total_bytes, L"");
|
|
queue_.push_back(task.id);
|
|
PostUpdate(task, 0.0);
|
|
}
|
|
|
|
void DownloadEngine::HandleDelete(int64_t id, bool delete_file)
|
|
{
|
|
auto it = tasks_.find(id);
|
|
if (it == tasks_.end() || it->second.state==TaskState::kDeleted)
|
|
return;
|
|
|
|
auto deleted=it->second; deleted.state=TaskState::kDeleted;
|
|
if (!store_open_ || !store_.UpdateState(id,TaskState::kDeleted,deleted.downloaded_bytes,deleted.total_bytes,L"")) {
|
|
PostRejected(L"无法保存删除记录,任务未删除"); return;
|
|
}
|
|
const std::wstring part_path = it->second.save_path + L".tdpart";
|
|
const std::wstring save_path = it->second.save_path;
|
|
if (id == current_id_)
|
|
{
|
|
cancel_current_ = true;
|
|
removed_current_ = true;
|
|
delete_file_current_ = delete_file;
|
|
}
|
|
else
|
|
{
|
|
::DeleteFileW(part_path.c_str());
|
|
if (delete_file)
|
|
::DeleteFileW(save_path.c_str());
|
|
}
|
|
|
|
it->second=deleted;
|
|
queue_.erase(std::remove(queue_.begin(), queue_.end(), id), queue_.end());
|
|
|
|
|
|
EngineEvent* event = new EngineEvent;
|
|
event->type = EngineEventType::kTaskRemoved;
|
|
event->task = deleted;
|
|
PostEvent(event);
|
|
}
|
|
|
|
void DownloadEngine::Download(TaskInfo& task)
|
|
{
|
|
const std::wstring part_path = task.save_path + L".tdpart";
|
|
|
|
task.downloaded_bytes = GetFileSize(part_path);
|
|
task.state = TaskState::kDownloading;
|
|
task.error.clear();
|
|
if (store_open_)
|
|
store_.UpdateState(task.id, TaskState::kDownloading, task.downloaded_bytes, task.total_bytes, L"");
|
|
PostUpdate(task, 0.0);
|
|
|
|
for (int attempt = 0; attempt < 3 && !stop_ && !cancel_current_; ++attempt)
|
|
{
|
|
std::wstring error;
|
|
AttemptResult result = RunAttempt(task, part_path, error);
|
|
if (result == AttemptResult::kCompleted)
|
|
{
|
|
if (stop_ || cancel_current_)
|
|
break;
|
|
if (!::MoveFileExW(part_path.c_str(), task.save_path.c_str(),
|
|
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
|
|
{
|
|
Fail(task, L"无法保存文件:" + Win32ErrorText(::GetLastError()));
|
|
return;
|
|
}
|
|
task.state = TaskState::kCompleted;
|
|
if (task.total_bytes > 0)
|
|
task.downloaded_bytes = task.total_bytes;
|
|
task.error.clear();
|
|
if (store_open_)
|
|
store_.UpdateState(task.id, TaskState::kCompleted, task.downloaded_bytes,
|
|
task.total_bytes, L"");
|
|
PostUpdate(task, 0.0);
|
|
return;
|
|
}
|
|
|
|
if (result == AttemptResult::kCanceled)
|
|
break;
|
|
|
|
if (result == AttemptResult::kFatal)
|
|
{
|
|
Fail(task, error);
|
|
return;
|
|
}
|
|
|
|
if (attempt == 2 || !WaitBeforeRetry())
|
|
{
|
|
if (!stop_ && !cancel_current_)
|
|
Fail(task, error);
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (removed_current_)
|
|
{
|
|
::DeleteFileW(part_path.c_str());
|
|
if (delete_file_current_)
|
|
::DeleteFileW(task.save_path.c_str());
|
|
}
|
|
else if (pause_current_)
|
|
{
|
|
task.downloaded_bytes = GetFileSize(part_path);
|
|
task.state = TaskState::kPaused;
|
|
task.error.clear();
|
|
if (store_open_)
|
|
store_.UpdateState(task.id, TaskState::kPaused, task.downloaded_bytes,
|
|
task.total_bytes, L"");
|
|
PostUpdate(task, 0.0);
|
|
}
|
|
}
|
|
|
|
DownloadEngine::AttemptResult DownloadEngine::RunAttempt(TaskInfo& task,
|
|
const std::wstring& part_path, std::wstring& error)
|
|
{
|
|
const int64_t offset=GetFileSize(part_path);
|
|
http::Request request;
|
|
request.url=task.url;
|
|
request.range_offset=offset;
|
|
request.referrer=task.referrer; request.user_agent=task.user_agent;
|
|
auto opened=transport_->Open(request);
|
|
if (!opened.stream) {
|
|
error=opened.error;
|
|
return opened.kind==http::OpenError::kInvalidRequest?AttemptResult::kFatal:AttemptResult::kRetry;
|
|
}
|
|
auto stream=std::move(opened.stream);
|
|
const auto& response=stream->Headers();
|
|
const unsigned status=response.status;
|
|
|
|
if (status == 416)
|
|
{
|
|
::DeleteFileW(part_path.c_str());
|
|
task.downloaded_bytes = 0;
|
|
error = L"服务器拒绝断点续传";
|
|
return AttemptResult::kRetry;
|
|
}
|
|
|
|
if (status != 200 && status != 206)
|
|
{
|
|
wchar_t text[64] = { 0 };
|
|
swprintf_s(text, L"服务器返回 HTTP %u", status);
|
|
error = text;
|
|
return AttemptResult::kFatal;
|
|
}
|
|
|
|
int64_t downloaded = status == 200 ? 0 : offset;
|
|
int64_t content_length = response.content_length;
|
|
if (status == 206)
|
|
{
|
|
int64_t total = ParseContentRangeTotal(response.content_range);
|
|
if (total > 0)
|
|
task.total_bytes = total;
|
|
else if (content_length > 0)
|
|
task.total_bytes = downloaded + content_length;
|
|
}
|
|
else if (content_length > 0)
|
|
{
|
|
task.total_bytes = content_length;
|
|
}
|
|
task.downloaded_bytes = downloaded;
|
|
|
|
using FileHandle = std::unique_ptr<void, decltype(&::CloseHandle)>;
|
|
FileHandle file(::CreateFileW(part_path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr,
|
|
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr), &::CloseHandle);
|
|
if (file.get() == INVALID_HANDLE_VALUE)
|
|
{
|
|
error = L"无法创建文件:" + Win32ErrorText(::GetLastError());
|
|
return AttemptResult::kFatal;
|
|
}
|
|
|
|
LARGE_INTEGER position = {};
|
|
position.QuadPart = downloaded;
|
|
if (!::SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN)
|
|
|| (downloaded == 0 && !::SetEndOfFile(file.get())))
|
|
{
|
|
error = L"无法写入目标文件:" + Win32ErrorText(::GetLastError());
|
|
return AttemptResult::kFatal;
|
|
}
|
|
|
|
PostUpdate(task, 0.0);
|
|
|
|
std::vector<char> buffer(64 * 1024);
|
|
auto last_report = std::chrono::steady_clock::now();
|
|
auto last_save = last_report;
|
|
int64_t bytes_since_report = 0;
|
|
int idle_timeouts = 0;
|
|
|
|
while (true)
|
|
{
|
|
DrainCommands();
|
|
if (stop_ || cancel_current_)
|
|
return AttemptResult::kCanceled;
|
|
|
|
const auto chunk=stream->Read(buffer);
|
|
DrainCommands();
|
|
if (stop_ || cancel_current_) return AttemptResult::kCanceled;
|
|
if (chunk.state==http::ReadState::kTimeout && ++idle_timeouts<5) continue;
|
|
if (chunk.state==http::ReadState::kTimeout || chunk.state==http::ReadState::kError) {
|
|
error=chunk.error;
|
|
return AttemptResult::kRetry;
|
|
}
|
|
if (chunk.state==http::ReadState::kEnd) break;
|
|
idle_timeouts=0;
|
|
if (chunk.size==0 || chunk.size>buffer.size()) {
|
|
error=L"HTTP 传输层返回了无效的数据长度";
|
|
return AttemptResult::kFatal;
|
|
}
|
|
const DWORD read=static_cast<DWORD>(chunk.size);
|
|
|
|
DWORD written = 0;
|
|
if (!::WriteFile(file.get(), buffer.data(), read, &written, nullptr) || written != read)
|
|
{
|
|
error = L"写入文件失败:" + Win32ErrorText(::GetLastError());
|
|
return AttemptResult::kFatal;
|
|
}
|
|
|
|
downloaded += read;
|
|
task.downloaded_bytes = downloaded;
|
|
bytes_since_report += read;
|
|
|
|
auto now = std::chrono::steady_clock::now();
|
|
auto report_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
now - last_report).count();
|
|
if (report_ms >= 150)
|
|
{
|
|
PostUpdate(task, bytes_since_report * 1000.0 / static_cast<double>(report_ms));
|
|
bytes_since_report = 0;
|
|
last_report = now;
|
|
}
|
|
|
|
auto save_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
now - last_save).count();
|
|
if (save_ms >= 3000)
|
|
{
|
|
if (store_open_)
|
|
store_.UpdateProgress(task.id, downloaded, task.total_bytes);
|
|
last_save = now;
|
|
}
|
|
}
|
|
|
|
if (task.total_bytes > 0 && downloaded < task.total_bytes)
|
|
{
|
|
error = L"连接提前中断";
|
|
return AttemptResult::kRetry;
|
|
}
|
|
|
|
task.downloaded_bytes = downloaded;
|
|
return AttemptResult::kCompleted;
|
|
}
|
|
|
|
void DownloadEngine::Fail(TaskInfo& task, const std::wstring& error)
|
|
{
|
|
task.state = TaskState::kFailed;
|
|
task.error = error;
|
|
if (store_open_)
|
|
store_.UpdateState(task.id, TaskState::kFailed, task.downloaded_bytes,
|
|
task.total_bytes, error);
|
|
PostUpdate(task, 0.0);
|
|
}
|
|
|
|
bool DownloadEngine::WaitBeforeRetry()
|
|
{
|
|
for (int i = 0; i < 10; ++i)
|
|
{
|
|
DrainCommands();
|
|
if (stop_ || cancel_current_)
|
|
return false;
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
|
}
|
|
return !stop_ && !cancel_current_;
|
|
}
|
|
|
|
void DownloadEngine::PostEvent(EngineEvent* event)
|
|
{
|
|
if (event == nullptr)
|
|
return;
|
|
if (::PostMessageW(notify_wnd_, kEventMessage, 0, reinterpret_cast<LPARAM>(event)) == FALSE)
|
|
delete event;
|
|
}
|
|
|
|
void DownloadEngine::PostUpdate(const TaskInfo& task, double speed)
|
|
{
|
|
EngineEvent* event = new EngineEvent;
|
|
event->type = EngineEventType::kTaskUpdated;
|
|
event->task = task;
|
|
event->speed = speed;
|
|
PostEvent(event);
|
|
}
|
|
|
|
void DownloadEngine::PostRejected(const std::wstring& message,const std::wstring& request_id)
|
|
{
|
|
EngineEvent* event = new EngineEvent;
|
|
event->type = EngineEventType::kTaskRejected;
|
|
event->message = message;
|
|
event->request_id=request_id;
|
|
PostEvent(event);
|
|
}
|