#include "Worker.h" #include "Api.h" #include "Config.h" #include "Http.h" #include "Unzip.h" #include "Utils.h" #include #include #include #include #pragma comment(lib, "shlwapi.lib") namespace updater { namespace { void CollectFiles(const std::wstring& dir, const std::wstring& relBase, std::vector& files, std::vector& dirs) { WIN32_FIND_DATAW data; std::wstring pattern = dir; if (!pattern.empty() && pattern.back() != L'\\') pattern += L'\\'; pattern += L"*"; HANDLE handle = FindFirstFileW(pattern.c_str(), &data); if (handle == INVALID_HANDLE_VALUE) return; do { std::wstring name = data.cFileName; if (name == L"." || name == L"..") continue; std::wstring rel = relBase.empty() ? name : relBase + L"\\" + name; if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { dirs.push_back(rel); CollectFiles(dir + L"\\" + name, rel, files, dirs); } else { files.push_back(rel); } } while (FindNextFileW(handle, &data)); FindClose(handle); } // 取文件名的主干(去掉目录和扩展名),用作快捷方式名字 std::wstring StemOf(const std::wstring& path) { size_t slash = path.find_last_of(L"\\/"); std::wstring base = (slash == std::wstring::npos) ? path : path.substr(slash + 1); size_t dot = base.rfind(L'.'); if (dot == std::wstring::npos || dot == 0) return base; return base.substr(0, dot); } std::vector SplitProcessNames(const std::wstring& text) { std::vector names; std::wstring current; for (size_t i = 0; i < text.size(); ++i) { wchar_t c = text[i]; if (c == L',' || c == L';') { std::wstring name = Utils::Trim(current); if (!name.empty()) names.push_back(name); current.clear(); } else { current += c; } } std::wstring name = Utils::Trim(current); if (!name.empty()) names.push_back(name); return names; } bool SameHash(const std::wstring& expected, const std::string& actual) { std::string want = Utils::WideToUtf8(expected); if (want.empty()) return true; return Utils::ToLowerAscii(want) == Utils::ToLowerAscii(actual); } } Worker::Worker() : cancel_(false), running_(false) {} Worker::~Worker() { Cancel(); if (thread_) { WaitForSingleObject(thread_, 5000); CloseHandle(thread_); thread_ = nullptr; } } unsigned __stdcall Worker::ThreadEntry(void* param) { Worker* worker = static_cast(param); worker->Run(); _endthreadex(0); return 0; } void Worker::Cancel() { cancel_.store(true); } void Worker::Emit(int percent, const std::wstring& text) { if (onState_) onState_(percent, text); } void Worker::Finish(bool success, const std::wstring& text) { running_.store(false); if (onFinish_) onFinish_(success, text); } void Worker::Start(const UpdateOptions& options, StateCallback onState, FinishCallback onFinish, InfoCallback onInfo) { options_ = options; onState_ = onState; onFinish_ = onFinish; onInfo_ = onInfo; cancel_.store(false); running_.store(true); if (thread_) { CloseHandle(thread_); thread_ = nullptr; } thread_ = reinterpret_cast(_beginthreadex(nullptr, 0, &Worker::ThreadEntry, this, 0, nullptr)); if (!thread_) { running_.store(false); Finish(false, L"无法创建工作线程"); } } bool Worker::CopyToTarget(const std::wstring& staging, const std::wstring& targetDir, std::wstring& err) { std::vector files; std::vector dirs; CollectFiles(staging, L"", files, dirs); if (!Utils::CreateDirRecursive(targetDir)) { err = L"无法创建目录:" + targetDir; return false; } for (size_t i = 0; i < dirs.size(); ++i) { std::wstring dst = Utils::JoinPath(targetDir, dirs[i]); if (!Utils::CreateDirRecursive(dst)) { err = L"无法创建目录:" + dst; return false; } } for (size_t i = 0; i < files.size(); ++i) { if (cancel_.load()) { err = L"已取消"; return false; } int percent = 92 + static_cast((i + 1) * 6 / (files.size() + 1)); Emit(percent, L"正在更新文件 (" + std::to_wstring(i + 1) + L"/" + std::to_wstring(files.size()) + L")"); std::wstring src = Utils::JoinPath(staging, files[i]); std::wstring dst = Utils::JoinPath(targetDir, files[i]); if (Utils::FileExists(dst)) { if (CopyFileW(src.c_str(), dst.c_str(), FALSE)) continue; // 目标文件可能被占用,改用延时替换 std::wstring tmp = dst + L".updater.tmp"; Utils::DeleteFileForce(tmp); if (!CopyFileW(src.c_str(), tmp.c_str(), FALSE)) { err = L"无法写入文件:" + dst; return false; } if (!Utils::ReplaceInUse(tmp, dst)) { Utils::DeleteFileForce(tmp); err = L"文件被占用,无法替换:" + dst; return false; } continue; } if (!CopyFileW(src.c_str(), dst.c_str(), TRUE)) { err = L"无法写入文件:" + dst; return false; } } return true; } void Worker::Run() { std::wstring targetDir = options_.targetDir; if (targetDir.empty()) targetDir = UPDATER_TARGET_DIR; if (targetDir.empty()) targetDir = Utils::GetModuleDir(); Emit(2, L"正在准备更新..."); #if UPDATER_WAIT_EXIT_SEC > 0 std::wstring waitName = options_.launchExe.empty() ? UPDATER_LAUNCH_EXE : options_.launchExe; if (!waitName.empty()) { Emit(3, L"正在等待主程序退出..."); Utils::WaitForProcessExit(waitName, UPDATER_WAIT_EXIT_SEC); } #endif if (cancel_.load()) { Finish(false, L"已取消"); return; } Emit(5, L"正在检查更新..."); Api::Result result = Api::CheckUpdate(options_.appKey, options_.clientVersion); if (!result.ok) { Finish(false, result.error); return; } UpdateInfo& info = result.info; if (!info.hasUpdate) { Finish(true, L"当前已是最新版本,无需更新"); return; } // 先把版本信息交给界面,更新日志可以趁下载的时候显示 if (onInfo_) onInfo_(info); // 更新包同时包含多个 EXE,正在运行的无法被覆盖。 // 手动运行更新器时这些进程可能还在跑,必须先让它们退出 std::vector closeNames = SplitProcessNames(UPDATER_CLOSE_PROCESSES); for (size_t i = 0; i < closeNames.size(); ++i) { if (cancel_.load()) { Finish(false, L"已取消"); return; } Emit(8, L"正在关闭 " + closeNames[i] + L"..."); if (!Utils::CloseProcesses(closeNames[i], UPDATER_CLOSE_TIMEOUT_SEC)) { Emit(8, L"无法关闭 " + closeNames[i] + L",更新可能无法完成"); } } // 选择要下载的包:全量模式取完整包,补丁模式优先取补丁包 std::wstring url; unsigned long long size = 0; std::wstring hash; std::wstring modeText; bool stripRoot = false; if (options_.fullMode) { url = info.fullPackageUrl; size = info.fullPackageSize; hash = info.fullPackageHash; modeText = L"完整包"; stripRoot = true; if (url.empty()) { url = info.downloadUrl; size = info.downloadSize; hash = info.downloadHash; } } else { if (info.isPatch && !info.patchUrl.empty()) { url = info.patchUrl; size = info.patchSize; hash = info.patchHash; modeText = L"补丁包"; } else { // 没有补丁包信息时,download_url 就是完整包(服务端 update_type 恒为 patch,不能用来判断) url = info.downloadUrl; size = info.downloadSize; hash = info.downloadHash; modeText = L"完整包"; stripRoot = true; } } if (url.empty()) { Finish(false, L"服务器没有返回下载地址"); return; } std::wstring versionText = info.latestVersion.empty() ? L"" : L" (" + info.latestVersion + L")"; Emit(8, L"开始下载" + modeText + versionText + L"..."); std::wstring tempDir = Utils::GetTempDir(); std::wstring package = Utils::MakeUniqueTempFile(tempDir, L"updater_pkg"); std::wstring err; int lastPercent = -1; unsigned long long lastTick = 0; bool ok = Http::Download(url, package, [this, &lastPercent, &lastTick, size](unsigned long long received, unsigned long long total) { if (cancel_.load()) return false; unsigned long long base = total > 0 ? total : size; int percent = 8; if (base > 0) { double ratio = static_cast(received) / static_cast(base); if (ratio > 1.0) ratio = 1.0; percent = 8 + static_cast(ratio * 62.0); } unsigned long long now = GetTickCount64(); if (percent != lastPercent || now - lastTick > 300) { lastPercent = percent; lastTick = now; Emit(percent, L"正在下载 " + Utils::FormatSize(received) + (base > 0 ? (L" / " + Utils::FormatSize(base)) : L"")); } return true; }, err); if (!ok) { Utils::DeleteFileForce(package); Finish(false, cancel_.load() ? L"已取消" : (L"下载失败:" + err)); return; } if (cancel_.load()) { Utils::DeleteFileForce(package); Finish(false, L"已取消"); return; } #if UPDATER_VERIFY_HASH if (!hash.empty()) { Emit(72, L"正在校验文件..."); std::string actual = Utils::Sha256HexFile(package); if (!SameHash(hash, actual)) { Utils::DeleteFileForce(package); Finish(false, L"文件校验失败,已中止更新"); return; } } #endif Emit(75, L"正在解压..."); std::wstring staging = Utils::MakeUniqueTempFile(tempDir, L"updater_dir"); DeleteFileW(staging.c_str()); if (!Utils::CreateDirRecursive(staging)) { Utils::DeleteFileForce(package); Finish(false, L"无法创建临时目录"); return; } Unzip unzip; std::vector written; std::wstring unzipErr; if (!unzip.Open(package, unzipErr)) { Utils::DeleteFileForce(package); Finish(false, unzipErr); return; } bool extracted = unzip.ExtractAll( staging, stripRoot, [this](unsigned long long done, unsigned long long total, const std::wstring& name) { if (cancel_.load()) return false; int percent = 75; if (total > 0) { double ratio = static_cast(done) / static_cast(total); percent = 75 + static_cast(ratio * 17.0); } Emit(percent, L"正在解压 " + name); return true; }, written, unzipErr); unzip.Close(); Utils::DeleteFileForce(package); (void)written; if (!extracted) { Finish(false, cancel_.load() ? L"已取消" : unzipErr); return; } Emit(92, L"正在应用更新..."); std::wstring copyErr; if (!CopyToTarget(staging, targetDir, copyErr)) { Finish(false, copyErr); return; } Emit(98, L"正在清理临时文件..."); std::vector stagedFiles; std::vector stagedDirs; CollectFiles(staging, L"", stagedFiles, stagedDirs); for (size_t i = 0; i < stagedFiles.size(); ++i) { Utils::DeleteFileForce(Utils::JoinPath(staging, stagedFiles[i])); } for (size_t i = stagedDirs.size(); i > 0; --i) { RemoveDirectoryW(Utils::JoinPath(staging, stagedDirs[i - 1]).c_str()); } RemoveDirectoryW(staging.c_str()); Emit(100, L"更新完成"); // 后台可以给包里的文件勾选"创建快捷方式",装完后按配置在桌面生成 for (size_t i = 0; i < info.desktopShortcutFiles.size(); ++i) { std::wstring target = Utils::JoinPath(targetDir, info.desktopShortcutFiles[i]); if (!Utils::FileExists(target)) continue; Emit(100, L"正在创建快捷方式 " + StemOf(info.desktopShortcutFiles[i]) + L"..."); Utils::CreateDesktopShortcut(target, StemOf(info.desktopShortcutFiles[i])); } // 启动项:命令行 --launch 优先,其次用后台勾选了"启动"的文件,都没有才回退到编译期配置 std::vector entries; if (!options_.launchExe.empty()) { entries.push_back(options_.launchExe); } else { entries = info.entryFiles; if (entries.empty() && !info.entryFile.empty()) entries.push_back(info.entryFile); #if defined(UPDATER_LAUNCH_EXE) if (entries.empty()) { std::wstring fallback = UPDATER_LAUNCH_EXE; if (!fallback.empty()) entries.push_back(fallback); } #endif } for (size_t i = 0; i < entries.size(); ++i) { std::wstring exe = Utils::JoinPath(targetDir, entries[i]); if (!Utils::FileExists(exe)) continue; Utils::LaunchProcess(exe, L"", targetDir); } Finish(true, L"更新完成" + versionText); } }