3 Commits
Author SHA1 Message Date
yuncishu 52aee3b5d5 fix: update installer never ran, app closed without updating (1.2.6)
The installer was spawned with DETACHED_PROCESS, which makes the
host process exit as soon as it starts, so the script body never
executed: no log, no file swap, no restart. Only CREATE_NO_WINDOW
is needed to keep the window hidden.

- stop both the bootloader and the Python child of a onefile build
- verify the script process is still alive before quitting the app
- write logs to updates/logs and always relaunch on failure
2026-10-31 23:52:53 +08:00
yuncishu 535e52d5f0 chore: add download availability notice (1.2.5) 2026-10-31 23:23:24 +08:00
yuncishu e0789d4a28 fix: make update installer atomic and Unicode-safe (1.2.4) 2026-10-31 23:05:59 +08:00
4 changed files with 229 additions and 21 deletions

No files matched your search

+4
View File
@@ -286,6 +286,10 @@ class MainWindow(QMainWindow):
self.nav_btns[key] = button
layout.addStretch()
client_notice = QLabel("客户端暂不提供直链下载", objectName="clientNotice")
client_notice.setContentsMargins(10, 0, 6, 4)
client_notice.setWordWrap(True)
layout.addWidget(client_notice)
version_row = QHBoxLayout()
version_row.setContentsMargins(10, 8, 2, 0)
self.version_label = QLabel("v%s" % APP_VERSION, objectName="versionLabel")
+1
View File
@@ -29,6 +29,7 @@ QPushButton#nav {
}
QPushButton#nav:hover { color: #f3f3f4; background: #28292e; }
QPushButton#nav[active="true"] { color: #ffffff; background: #323338; font-weight: 600; }
#clientNotice { color: #65676f; font-size: 9.5px; letter-spacing: .1px; }
#versionLabel { color: #666871; font-size: 9.5px; letter-spacing: .4px; }
QPushButton#versionBtn {
color: #8b8d95; background: transparent; border: none; border-radius: 5px;
+223 -20
View File
@@ -5,6 +5,7 @@ import re
import subprocess
import sys
import tempfile
import time
import urllib.parse
import requests
@@ -102,15 +103,169 @@ def _safe_suffix(url):
return suffix if suffix in (".exe", ".msi", ".zip") else ".exe"
def _offset_dir(version):
CREATE_NO_WINDOW = 0x08000000
def _offset_dir(sub=""):
base = os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()
path = os.path.join(base, "NeteasePlayer", "updates")
if sub:
path = os.path.join(path, sub)
os.makedirs(path, exist_ok=True)
return path
def _quote(path):
return '"' + str(path).replace('"', '""') + '"'
def _ps_quote(value):
return "'" + str(value).replace("'", "''") + "'"
def powershell_exe():
root = os.environ.get("SystemRoot") or os.environ.get("WINDIR") or r"C:\Windows"
path = os.path.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
return path if os.path.exists(path) else "powershell.exe"
def build_install_script(current, downloaded, pid, digest="", parent_pid=None):
"""生成 Unicode 安全的更新脚本:校验副本后再交换文件,任何失败路径都会重新拉起程序。"""
current = os.path.abspath(current)
downloaded = os.path.abspath(downloaded)
log_dir = _offset_dir("logs")
log_path = os.path.join(log_dir, "update.log")
pids = [int(pid)]
if parent_pid and int(parent_pid) > 100 and int(parent_pid) not in pids:
# PyInstaller 单文件有两个进程:bootloader 才是持有 exe 文件的那个
pids.append(int(parent_pid))
script = r"""
$ErrorActionPreference = 'Continue'
$src = __SRC__
$dst = __DST__
$expected = __EXPECTED__
$logDir = __LOG_DIR__
$log = __LOG__
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
function Write-UpdateLog($message) {
try {
Add-Content -LiteralPath $log -Encoding UTF8 -Value ("[" + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + "] " + $message)
} catch {}
}
function Start-App($path) {
if (-not $path) { return $false }
if (-not (Test-Path -LiteralPath $path)) {
Write-UpdateLog ("missing target: " + $path)
return $false
}
try {
Start-Process -FilePath $path -WorkingDirectory (Split-Path -Parent $path) -ErrorAction Stop
Write-UpdateLog ("started: " + $path)
return $true
} catch {
Write-UpdateLog ("start failed: " + $path + " :: " + $_.Exception.Message)
return $false
}
}
Write-UpdateLog "=== update begin; pids=__PIDS_TEXT__ ==="
Write-UpdateLog ("src=" + $src)
Write-UpdateLog ("dst=" + $dst)
Start-Sleep -Seconds 2
foreach ($p in @(__PIDS__)) {
try { Stop-Process -Id $p -Force -ErrorAction SilentlyContinue } catch {}
}
Start-Sleep -Milliseconds 1200
$staged = $dst + ".update"
$backup = $dst + ".bak"
Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue
$verified = $false
for ($i = 0; $i -lt 30; $i++) {
try {
Copy-Item -LiteralPath $src -Destination $staged -Force -ErrorAction Stop
if ($expected) {
$actual = (Get-FileHash -LiteralPath $staged -Algorithm SHA256).Hash
if ($actual -ne $expected) { throw "SHA256 mismatch" }
}
$verified = $true
Write-UpdateLog "staged copy verified"
break
} catch {
Write-UpdateLog ("stage attempt " + $i + " failed: " + $_.Exception.Message)
Start-Sleep -Milliseconds 500
}
}
if (-not $verified) {
Write-UpdateLog "stage failed; launching downloaded copy"
if (-not (Start-App $src)) { Start-App $dst }
Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
exit
}
$swapped = $false
for ($i = 0; $i -lt 30; $i++) {
try {
if (Test-Path -LiteralPath $dst) {
Move-Item -LiteralPath $dst -Destination $backup -Force -ErrorAction Stop
}
$swapped = $true
break
} catch {
Write-UpdateLog ("rename old attempt " + $i + " failed: " + $_.Exception.Message)
Start-Sleep -Milliseconds 500
}
}
if (-not $swapped) {
Write-UpdateLog "cannot rename running exe; starting downloaded copy"
if (-not (Start-App $src)) { Start-App $dst }
Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
exit
}
$installed = $false
try {
Move-Item -LiteralPath $staged -Destination $dst -Force -ErrorAction Stop
$installed = $true
Write-UpdateLog "new file in place"
} catch {
Write-UpdateLog ("swap failed: " + $_.Exception.Message)
if ((Test-Path -LiteralPath $backup) -and -not (Test-Path -LiteralPath $dst)) {
Move-Item -LiteralPath $backup -Destination $dst -Force -ErrorAction SilentlyContinue
Write-UpdateLog "rolled back from backup"
}
}
if ($installed) {
if (-not (Start-App $dst)) {
Write-UpdateLog "new version did not start; trying downloaded copy"
Start-App $src
}
} else {
if (-not (Start-App $dst)) { Start-App $src }
}
for ($i = 0; $i -lt 20; $i++) {
if (-not (Test-Path -LiteralPath $backup)) { break }
try {
[System.IO.File]::Delete($backup)
Write-UpdateLog "old backup cleaned"
break
} catch {
Start-Sleep -Milliseconds 500
}
}
Write-UpdateLog "=== update end ==="
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
""".replace("__SRC__", _ps_quote(downloaded)) \
.replace("__DST__", _ps_quote(current)) \
.replace("__EXPECTED__", _ps_quote(digest or "")) \
.replace("__LOG_DIR__", _ps_quote(log_dir)) \
.replace("__LOG__", _ps_quote(log_path)) \
.replace("__PIDS_TEXT__", ",".join(str(p) for p in pids)) \
.replace("__PIDS__", ", ".join(str(p) for p in pids))
return script, log_path
class UpdateDialog(QDialog):
@@ -352,8 +507,8 @@ class UpdateDialog(QDialog):
if action == "retry":
self.primary.setProperty("action", "")
self.start_download()
elif action == "install":
self.install()
elif action == "page":
self._open_page()
else:
self.install()
@@ -367,24 +522,72 @@ class UpdateDialog(QDialog):
self.status.setText("安装包已打开")
return
current = os.path.abspath(sys.executable)
script_path = os.path.join(tempfile.gettempdir(), "netease_player_update.cmd")
script = "\r\n".join([
"@echo off",
"chcp 65001 >nul",
"timeout /t 2 /nobreak >nul",
"taskkill /PID %d /F >nul 2>&1" % os.getpid(),
'copy /Y %s %s >nul 2>&1' % (_quote(path), _quote(current)),
'start "" %s' % _quote(current),
'del "%~f0" >nul 2>&1',
"",
])
with open(script_path, "w", encoding="utf-8") as handle:
parent_pid = None
try:
candidate = os.getppid()
if candidate and candidate > 100:
parent_pid = candidate
except Exception: # noqa: BLE001
parent_pid = None
script, log_path = build_install_script(
current, path, os.getpid(), self.info.get("sha256") or "", parent_pid)
# 放在更新目录而不是 Temp,避免脚本尚未启动就被系统清理
script_path = os.path.join(_offset_dir("logs"), "install.ps1")
try:
with open(script_path, "w", encoding="utf-8-sig") as handle:
handle.write(script)
subprocess.Popen(
["cmd.exe", "/c", script_path],
creationflags=0x08000000 | 0x00000008,
except OSError as exc:
self._manual_install(path, "无法写入更新脚本:%s" % exc)
return
try:
proc = subprocess.Popen(
[
powershell_exe(), "-NoProfile", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden",
"-File", script_path,
],
creationflags=CREATE_NO_WINDOW,
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception as exc: # noqa: BLE001
self._manual_install(path, "无法启动更新程序:%s" % exc)
return
# PowerShell 被安全策略或参数问题打断时会立刻退出,必须确认它真的活着
deadline = time.time() + 1.5
while time.time() < deadline:
if proc.poll() is not None:
break
time.sleep(0.1)
if proc.poll() is not None:
self._manual_install(path, "更新脚本未能运行")
return
self.status.setText("正在重启并安装,新版本会自动打开…")
self._notify("installing", "正在安装更新")
QApplication.quit()
def _manual_install(self, path, reason):
"""更新脚本无法代劳时,至少把新版本直接跑起来,不让用户只剩一个关掉的窗口。"""
try:
subprocess.Popen(
[path],
cwd=os.path.dirname(path),
creationflags=CREATE_NO_WINDOW,
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception as exc: # noqa: BLE001
self.status.setText("%s;请前往下载页手动安装" % reason)
self.primary.setText("前往下载页")
self.primary.setEnabled(True)
self.primary.setProperty("action", "page")
return
self.status.setText("%s,已直接启动新版本" % reason)
self._notify("installing", "已启动新版本")
QApplication.quit()
def _notify(self, state, text):
+1 -1
View File
@@ -1,7 +1,7 @@
"""应用版本与更新地址。"""
APP_NAME = "网易云播放器"
APP_VERSION = "1.2.3"
APP_VERSION = "1.2.6"
BUILD_DATE = "2026-10-31"
UPDATE_ENDPOINT = "https://music.yuncishu.xyz/api/app/update"
DOWNLOAD_PAGE = "https://music.yuncishu.xyz/download/"