第三方框架改为仓内子集并完善构建忽略规则
完整 NIM_Duilib_Framework 仓库移至父目录,third_party 仅保留实际使用的 base、duilib、bin/resources 与许可证;.gitignore 覆盖 MSBuild 与打包产物。
This commit is contained in:
1 parent
249e8548de
commit
e1e26acc49
391 files changed
+342850
No files matched your search
@@ -0,0 +1,971 @@
|
||||
#include "stdafx.h"
|
||||
#include "download_engine.h"
|
||||
|
||||
#include <winhttp.h>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cwctype>
|
||||
|
||||
#pragma comment(lib, "winhttp.lib")
|
||||
|
||||
namespace
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct UrlParts
|
||||
{
|
||||
std::wstring host;
|
||||
std::wstring path;
|
||||
INTERNET_PORT port = 0;
|
||||
bool https = false;
|
||||
};
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
bool CrackUrl(const std::wstring& url, UrlParts& parts)
|
||||
{
|
||||
URL_COMPONENTS components = {};
|
||||
components.dwStructSize = sizeof(components);
|
||||
components.dwSchemeLength = static_cast<DWORD>(-1);
|
||||
components.dwHostNameLength = static_cast<DWORD>(-1);
|
||||
components.dwUrlPathLength = static_cast<DWORD>(-1);
|
||||
components.dwExtraInfoLength = static_cast<DWORD>(-1);
|
||||
|
||||
if (!::WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &components))
|
||||
return false;
|
||||
if (components.nScheme != INTERNET_SCHEME_HTTP && components.nScheme != INTERNET_SCHEME_HTTPS)
|
||||
return false;
|
||||
|
||||
parts.host.assign(components.lpszHostName, components.dwHostNameLength);
|
||||
parts.path.assign(components.lpszUrlPath, components.dwUrlPathLength);
|
||||
if (components.lpszExtraInfo != nullptr && components.dwExtraInfoLength > 0)
|
||||
parts.path.append(components.lpszExtraInfo, components.dwExtraInfoLength);
|
||||
if (parts.path.empty())
|
||||
parts.path = L"/";
|
||||
parts.port = components.nPort;
|
||||
parts.https = components.nScheme == INTERNET_SCHEME_HTTPS;
|
||||
return !parts.host.empty();
|
||||
}
|
||||
|
||||
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 = nbase::UTF8ToUTF16(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";
|
||||
|
||||
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)
|
||||
{
|
||||
UrlParts parts;
|
||||
std::wstring path = url;
|
||||
if (CrackUrl(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;
|
||||
}
|
||||
|
||||
std::wstring NetworkErrorText(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)
|
||||
{
|
||||
HMODULE winhttp = ::GetModuleHandleW(L"winhttp.dll");
|
||||
if (winhttp != nullptr)
|
||||
{
|
||||
length = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE
|
||||
| FORMAT_MESSAGE_IGNORE_INSERTS, winhttp, 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 QueryContentLength(HINTERNET request)
|
||||
{
|
||||
unsigned long long length = 0;
|
||||
DWORD size = sizeof(length);
|
||||
if (!::WinHttpQueryHeaders(request, WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER64,
|
||||
WINHTTP_HEADER_NAME_BY_INDEX, &length, &size, WINHTTP_NO_HEADER_INDEX))
|
||||
return 0;
|
||||
return static_cast<int64_t>(length);
|
||||
}
|
||||
|
||||
std::wstring QueryHeaderText(HINTERNET request, DWORD query)
|
||||
{
|
||||
DWORD size = 0;
|
||||
::WinHttpQueryHeaders(request, query, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||
WINHTTP_NO_OUTPUT_BUFFER, &size, WINHTTP_NO_HEADER_INDEX);
|
||||
if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER || size == 0)
|
||||
return std::wstring();
|
||||
|
||||
std::wstring text(size / sizeof(wchar_t), L'\0');
|
||||
if (!::WinHttpQueryHeaders(request, query, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||
text.data(), &size, WINHTTP_NO_HEADER_INDEX))
|
||||
return std::wstring();
|
||||
|
||||
text.resize(size / sizeof(wchar_t));
|
||||
while (!text.empty() && text.back() == L'\0')
|
||||
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)
|
||||
: notify_wnd_(notify_wnd)
|
||||
{
|
||||
}
|
||||
|
||||
DownloadEngine::~DownloadEngine()
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
|
||||
void DownloadEngine::Start()
|
||||
{
|
||||
if (thread_.joinable())
|
||||
return;
|
||||
thread_ = std::thread(&DownloadEngine::ThreadMain, this);
|
||||
}
|
||||
|
||||
void DownloadEngine::Stop()
|
||||
{
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
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 db_dir = nbase::win32::GetLocalAppDataDir() + 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);
|
||||
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);
|
||||
}
|
||||
|
||||
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 = 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(); });
|
||||
}
|
||||
|
||||
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::wstring url = Trim(cmd.url);
|
||||
if (url.empty())
|
||||
{
|
||||
PostRejected(L"下载链接不能为空");
|
||||
return;
|
||||
}
|
||||
|
||||
UrlParts parts;
|
||||
if (!CrackUrl(url, parts))
|
||||
{
|
||||
PostRejected(L"仅支持有效的 HTTP/HTTPS 链接");
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& entry : tasks_)
|
||||
{
|
||||
if (entry.second.url == url)
|
||||
{
|
||||
PostRejected(L"链接已存在");
|
||||
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))
|
||||
{
|
||||
PostRejected(L"保存目录不可用");
|
||||
return;
|
||||
}
|
||||
|
||||
TaskInfo task;
|
||||
task.url = url;
|
||||
task.file_name = FileNameFromUrl(url);
|
||||
task.save_path = PickUniquePath(dir, task.file_name, tasks_);
|
||||
task.state = TaskState::kQueued;
|
||||
|
||||
if (!store_open_ || !store_.Insert(task))
|
||||
{
|
||||
PostRejected(L"无法写入任务数据库");
|
||||
return;
|
||||
}
|
||||
|
||||
tasks_[task.id] = task;
|
||||
queue_.push_back(task.id);
|
||||
|
||||
EngineEvent* event = new EngineEvent;
|
||||
event->type = EngineEventType::kTaskAdded;
|
||||
event->task = task;
|
||||
PostEvent(event);
|
||||
}
|
||||
|
||||
void DownloadEngine::HandlePause(int64_t id)
|
||||
{
|
||||
auto it = tasks_.find(id);
|
||||
if (it == tasks_.end())
|
||||
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())
|
||||
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())
|
||||
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());
|
||||
}
|
||||
|
||||
tasks_.erase(it);
|
||||
queue_.erase(std::remove(queue_.begin(), queue_.end(), id), queue_.end());
|
||||
if (store_open_)
|
||||
store_.DeleteTask(id);
|
||||
|
||||
EngineEvent* event = new EngineEvent;
|
||||
event->type = EngineEventType::kTaskRemoved;
|
||||
event->task.id = id;
|
||||
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)
|
||||
{
|
||||
UrlParts parts;
|
||||
if (!CrackUrl(task.url, parts))
|
||||
{
|
||||
error = L"无效的下载链接";
|
||||
return AttemptResult::kFatal;
|
||||
}
|
||||
|
||||
using WinHttpHandle = std::unique_ptr<void, decltype(&::WinHttpCloseHandle)>;
|
||||
WinHttpHandle session(::WinHttpOpen(L"TTDownloader/0.1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0), &::WinHttpCloseHandle);
|
||||
if (!session)
|
||||
{
|
||||
error = L"无法初始化网络连接";
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
::WinHttpSetTimeouts(session.get(), 15000, 15000, 15000, 4000);
|
||||
|
||||
WinHttpHandle connect(::WinHttpConnect(session.get(), parts.host.c_str(), parts.port, 0),
|
||||
&::WinHttpCloseHandle);
|
||||
if (!connect)
|
||||
{
|
||||
error = L"无法连接服务器";
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
|
||||
WinHttpHandle request(::WinHttpOpenRequest(connect.get(), L"GET", parts.path.c_str(), nullptr,
|
||||
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
|
||||
parts.https ? WINHTTP_FLAG_SECURE : 0), &::WinHttpCloseHandle);
|
||||
if (!request)
|
||||
{
|
||||
error = L"无法创建下载请求";
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
|
||||
int64_t offset = GetFileSize(part_path);
|
||||
if (offset > 0)
|
||||
{
|
||||
wchar_t range[64] = { 0 };
|
||||
swprintf_s(range, L"Range: bytes=%lld-", offset);
|
||||
::WinHttpAddRequestHeaders(request.get(), range, static_cast<DWORD>(-1),
|
||||
WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
|
||||
}
|
||||
|
||||
if (!::WinHttpSendRequest(request.get(), WINHTTP_NO_ADDITIONAL_HEADERS, 0,
|
||||
WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
|
||||
{
|
||||
error = L"请求发送失败:" + NetworkErrorText(::GetLastError());
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
|
||||
if (!::WinHttpReceiveResponse(request.get(), nullptr))
|
||||
{
|
||||
error = L"接收响应失败:" + NetworkErrorText(::GetLastError());
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
|
||||
DWORD status = 0;
|
||||
DWORD status_size = sizeof(status);
|
||||
if (!::WinHttpQueryHeaders(request.get(), WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
|
||||
WINHTTP_HEADER_NAME_BY_INDEX, &status, &status_size, WINHTTP_NO_HEADER_INDEX))
|
||||
{
|
||||
error = L"无法读取 HTTP 状态码";
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
|
||||
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 = QueryContentLength(request.get());
|
||||
if (status == 206)
|
||||
{
|
||||
int64_t total = ParseContentRangeTotal(
|
||||
QueryHeaderText(request.get(), WINHTTP_QUERY_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;
|
||||
|
||||
DWORD available = 0;
|
||||
if (!::WinHttpQueryDataAvailable(request.get(), &available))
|
||||
{
|
||||
DWORD code = ::GetLastError();
|
||||
if (code == ERROR_WINHTTP_TIMEOUT && ++idle_timeouts < 5)
|
||||
continue;
|
||||
error = code == ERROR_WINHTTP_TIMEOUT ? L"下载超时" : L"接收数据失败:" + NetworkErrorText(code);
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
if (available == 0)
|
||||
break;
|
||||
idle_timeouts = 0;
|
||||
|
||||
DWORD to_read = (std::min)(available, static_cast<DWORD>(buffer.size()));
|
||||
DWORD read = 0;
|
||||
if (!::WinHttpReadData(request.get(), buffer.data(), to_read, &read))
|
||||
{
|
||||
DWORD code = ::GetLastError();
|
||||
if (code == ERROR_WINHTTP_TIMEOUT && ++idle_timeouts < 5)
|
||||
continue;
|
||||
error = code == ERROR_WINHTTP_TIMEOUT ? L"下载超时" : L"读取数据失败:" + NetworkErrorText(code);
|
||||
return AttemptResult::kRetry;
|
||||
}
|
||||
if (read == 0)
|
||||
break;
|
||||
|
||||
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)
|
||||
{
|
||||
EngineEvent* event = new EngineEvent;
|
||||
event->type = EngineEventType::kTaskRejected;
|
||||
event->message = message;
|
||||
PostEvent(event);
|
||||
}
|
||||
Reference in new issue
Block a user