mirror of
https://github.com/mikumifa/biliTickerBuy.git
synced 2026-11-16 05:23:02 -08:00
feat: 更加方便的安装
This commit is contained in:
1 parent
74f32790e8
commit
842fdfe99e
9 files changed
+496
-272
No files matched your search
@@ -85,11 +85,36 @@ jobs:
|
||||
run: |
|
||||
pyinstaller main.spec
|
||||
|
||||
- name: Stage updater scripts
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ matrix.config.os.filename }}" = "windows_amd64" ]; then
|
||||
cp assets/updater/update.bat dist/update.bat
|
||||
cp assets/updater/.env.install dist/.env.install
|
||||
else
|
||||
cp assets/updater/update.sh dist/biliTickerBuy/update.sh
|
||||
cp assets/updater/.env.install dist/biliTickerBuy/.env.install
|
||||
chmod +x dist/biliTickerBuy/update.sh
|
||||
fi
|
||||
|
||||
- name: Verify updater scripts in package root
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ matrix.config.os.filename }}" = "windows_amd64" ]; then
|
||||
test -f dist/biliTicKerBuy.exe
|
||||
test -f dist/update.bat
|
||||
test -f dist/.env.install
|
||||
else
|
||||
test -d dist/biliTickerBuy
|
||||
test -f dist/biliTickerBuy/update.sh
|
||||
test -f dist/biliTickerBuy/.env.install
|
||||
fi
|
||||
|
||||
- name: Zip the Build-windows
|
||||
if: matrix.config.os.filename == 'windows_amd64'
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path ./dist/biliTicKerBuy.exe -DestinationPath tmp.zip -Force
|
||||
Compress-Archive -Path ./dist/biliTicKerBuy.exe,./dist/update.bat,./dist/.env.install -DestinationPath tmp.zip -Force
|
||||
|
||||
- name: Zip the Build-linux-macos
|
||||
if: matrix.config.os.filename != 'windows_amd64'
|
||||
|
||||
@@ -31,6 +31,11 @@
|
||||
## 💻 快速安装
|
||||
|
||||
方法一: 从 github 上[下载](https://github.com/mikumifa/biliTickerBuy/releases)
|
||||
Linux / macOS 也可以直接远程安装:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/mikumifa/biliTickerBuy/main/install.sh | sh
|
||||
```
|
||||
|
||||
方法二: 如果没有您使用系统的已构建版本,请前往[指南](https://github.com/mikumifa/biliTickerBuy/wiki/Docker%E8%BF%90%E8%A1%8C%E6%96%B9%E6%B3%95)
|
||||
|
||||
|
||||
+1
-110
@@ -1,13 +1,8 @@
|
||||
"""GitHub release discovery and verified update-package downloads."""
|
||||
"""GitHub release discovery for update notifications."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
import requests
|
||||
@@ -132,107 +127,3 @@ def fetch_update(
|
||||
if not isinstance(payload, list):
|
||||
raise UpdateError("GitHub 返回了无法识别的版本列表。")
|
||||
return select_update(payload, current_version, channel)
|
||||
|
||||
|
||||
def platform_asset_key() -> str:
|
||||
system = platform.system().lower()
|
||||
machine = platform.machine().lower()
|
||||
if system == "windows" and machine in {"amd64", "x86_64"}:
|
||||
return "windows_amd64"
|
||||
if system == "linux" and machine in {"amd64", "x86_64"}:
|
||||
return "linux_amd64"
|
||||
if system == "linux" and machine in {"arm64", "aarch64"}:
|
||||
return "linux_arm64"
|
||||
if system == "darwin" and machine in {"arm64", "aarch64"}:
|
||||
return "macos_arm64"
|
||||
if system == "darwin" and machine in {"amd64", "x86_64"}:
|
||||
return "macos_intel"
|
||||
raise UpdateError(f"当前平台暂不支持自动下载:{system}/{machine}")
|
||||
|
||||
|
||||
def _find_asset(release: ReleaseInfo, name: str) -> dict[str, Any]:
|
||||
for asset in release.assets:
|
||||
if asset.get("name") == name:
|
||||
return asset
|
||||
raise UpdateError(f"GitHub Release 中缺少文件:{name}")
|
||||
|
||||
|
||||
def _download_json(
|
||||
url: str, *, session: requests.Session, user_agent: str
|
||||
) -> dict[str, Any]:
|
||||
response = session.get(
|
||||
url,
|
||||
headers={"Accept": "application/octet-stream", "User-Agent": user_agent},
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
if not isinstance(payload, dict):
|
||||
raise UpdateError("版本校验清单格式错误。")
|
||||
return payload
|
||||
|
||||
|
||||
def download_update_package(
|
||||
release: ReleaseInfo,
|
||||
destination: str | os.PathLike[str],
|
||||
*,
|
||||
session: requests.Session | None = None,
|
||||
) -> Path:
|
||||
client = session or requests.Session()
|
||||
user_agent = f"biliTickerBuy/{release.version}"
|
||||
manifest_asset = _find_asset(release, "version-info.json")
|
||||
manifest = _download_json(
|
||||
str(manifest_asset["browser_download_url"]),
|
||||
session=client,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
|
||||
manifest_version = str(manifest.get("version") or "")
|
||||
if normalize_version(manifest_version) != normalize_version(release.tag_name):
|
||||
raise UpdateError("版本校验清单与 GitHub Release 版本不一致。")
|
||||
|
||||
key = platform_asset_key()
|
||||
file_info = (manifest.get("files") or {}).get(key)
|
||||
if not isinstance(file_info, dict):
|
||||
raise UpdateError(f"版本校验清单中缺少当前平台:{key}")
|
||||
|
||||
filename = str(file_info.get("name") or "")
|
||||
expected_sha256 = str(file_info.get("sha256") or "").lower()
|
||||
if not filename or not re.fullmatch(r"[0-9a-f]{64}", expected_sha256):
|
||||
raise UpdateError("版本校验清单缺少有效的文件名或 SHA-256。")
|
||||
|
||||
package_asset = _find_asset(release, filename)
|
||||
expected_size = int(file_info.get("size") or 0)
|
||||
if expected_size and int(package_asset.get("size") or 0) not in {0, expected_size}:
|
||||
raise UpdateError("版本校验清单中的文件大小与 GitHub Release 不一致。")
|
||||
|
||||
destination_path = Path(destination).expanduser().resolve()
|
||||
destination_path.mkdir(parents=True, exist_ok=True)
|
||||
output_path = destination_path / Path(filename).name
|
||||
partial_path = output_path.with_suffix(output_path.suffix + ".part")
|
||||
|
||||
digest = hashlib.sha256()
|
||||
try:
|
||||
with client.get(
|
||||
str(package_asset["browser_download_url"]),
|
||||
headers={"Accept": "application/octet-stream", "User-Agent": user_agent},
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
stream=True,
|
||||
) as response:
|
||||
response.raise_for_status()
|
||||
with partial_path.open("wb") as output:
|
||||
for chunk in response.iter_content(chunk_size=1024 * 1024):
|
||||
if chunk:
|
||||
output.write(chunk)
|
||||
digest.update(chunk)
|
||||
if expected_size and partial_path.stat().st_size != expected_size:
|
||||
raise UpdateError("更新包大小校验失败,文件可能不完整,已取消更新。")
|
||||
actual_sha256 = digest.hexdigest()
|
||||
if actual_sha256 != expected_sha256:
|
||||
raise UpdateError("更新包 SHA-256 校验失败,文件可能不完整,已取消更新。")
|
||||
partial_path.replace(output_path)
|
||||
except Exception:
|
||||
partial_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
return output_path
|
||||
@@ -0,0 +1,3 @@
|
||||
# github 加速前缀
|
||||
# 留空:下载依赖时不走代理
|
||||
GH_PROXY=https://gh-proxy.org
|
||||
@@ -0,0 +1,118 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
setlocal EnableExtensions EnableDelayedExpansion
|
||||
|
||||
set "REPO=mikumifa/biliTickerBuy"
|
||||
set "PLATFORM_KEY=windows_amd64"
|
||||
set "INSTALL_DIR=%~dp0"
|
||||
if "%INSTALL_DIR:~-1%"=="\" set "INSTALL_DIR=%INSTALL_DIR:~0,-1%"
|
||||
set "WORK_DIR=%INSTALL_DIR%\updates"
|
||||
set "TEMP_ZIP=%WORK_DIR%\update.zip"
|
||||
set "TEMP_EXTRACT=%WORK_DIR%\extract"
|
||||
set "META_FILE=%WORK_DIR%\release-meta.txt"
|
||||
set "API_URL=https://api.github.com/repos/%REPO%/releases/latest"
|
||||
set "ENV_INSTALL_FILE=%INSTALL_DIR%\.env.install"
|
||||
|
||||
if exist "%ENV_INSTALL_FILE%" (
|
||||
for /f "usebackq tokens=1,* delims==" %%A in (`findstr /r /v "^[ ]*# ^[ ]*$" "%ENV_INSTALL_FILE%"`) do (
|
||||
if /i "%%A"=="GH_PROXY" set "GH_PROXY=%%B"
|
||||
)
|
||||
)
|
||||
|
||||
if defined GH_PROXY (
|
||||
if "!GH_PROXY:~-1!"=="/" (
|
||||
set "API_URL=!GH_PROXY!!API_URL!"
|
||||
) else (
|
||||
set "API_URL=!GH_PROXY!/!API_URL!"
|
||||
)
|
||||
)
|
||||
|
||||
echo [biliTickerBuy] Checking latest release for %PLATFORM_KEY%...
|
||||
where powershell >nul 2>nul || (
|
||||
echo 未找到 PowerShell,无法执行更新。
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
mkdir "%WORK_DIR%" >nul 2>nul
|
||||
if exist "%TEMP_EXTRACT%" rmdir /s /q "%TEMP_EXTRACT%"
|
||||
mkdir "%TEMP_EXTRACT%" >nul 2>nul
|
||||
if exist "%META_FILE%" del /f /q "%META_FILE%" >nul 2>nul
|
||||
|
||||
set "RELEASE_TAG="
|
||||
set "ASSET_URL="
|
||||
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
|
||||
"$ErrorActionPreference='Stop';" ^
|
||||
"$headers = @{ 'User-Agent'='biliTickerBuy-updater' };" ^
|
||||
"$apiUrl = '%API_URL%';" ^
|
||||
"try { $release = Invoke-RestMethod -Headers $headers -Uri $apiUrl } catch { $release = Invoke-RestMethod -Headers $headers -Uri 'https://api.github.com/repos/%REPO%/releases/latest' };" ^
|
||||
"$asset = $release.assets | Where-Object { $_.name -like '*_%PLATFORM_KEY%_*' } | Select-Object -First 1;" ^
|
||||
"if (-not $asset) { throw 'Latest release does not contain the expected Windows package.' }" ^
|
||||
"$assetUrl = $asset.browser_download_url;" ^
|
||||
"$proxy = $env:GH_PROXY;" ^
|
||||
"if ($proxy) { if (-not $proxy.EndsWith('/')) { $proxy += '/' }; $assetUrl = $proxy + $assetUrl }" ^
|
||||
"$content = 'RELEASE_TAG=' + $release.tag_name + '|' + 'ASSET_URL=' + $assetUrl;" ^
|
||||
"[System.IO.File]::WriteAllText('%META_FILE%', $content, [System.Text.Encoding]::ASCII)"
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
if not exist "%META_FILE%" (
|
||||
echo 生成版本信息失败。
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
for /f "usebackq tokens=1,2 delims=|" %%A in ("%META_FILE%") do (
|
||||
for /f "tokens=1,* delims==" %%C in ("%%A") do (
|
||||
if /i "%%C"=="RELEASE_TAG" set "RELEASE_TAG=%%D"
|
||||
)
|
||||
for /f "tokens=1,* delims==" %%C in ("%%B") do (
|
||||
if /i "%%C"=="ASSET_URL" set "ASSET_URL=%%D"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined ASSET_URL (
|
||||
echo 未能解析到可用的更新包地址。
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if exist "%TEMP_ZIP%" (
|
||||
echo [biliTickerBuy] 检测到已下载的更新包,跳过下载:"%TEMP_ZIP%"
|
||||
) else (
|
||||
echo [biliTickerBuy] 正在下载 !RELEASE_TAG!...
|
||||
where curl.exe >nul 2>nul
|
||||
if not errorlevel 1 (
|
||||
curl.exe -L --progress-bar -H "User-Agent: biliTickerBuy-updater" -o "%TEMP_ZIP%" "%ASSET_URL%"
|
||||
if errorlevel 1 exit /b 1
|
||||
) else (
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
|
||||
"$ErrorActionPreference='Stop'; Invoke-WebRequest -Headers @{ 'User-Agent'='biliTickerBuy-updater' } -Uri '%ASSET_URL%' -OutFile '%TEMP_ZIP%'"
|
||||
if errorlevel 1 exit /b 1
|
||||
)
|
||||
)
|
||||
|
||||
echo [biliTickerBuy] 正在解压更新包...
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
|
||||
"$ErrorActionPreference='Stop'; Expand-Archive -Path '%TEMP_ZIP%' -DestinationPath '%TEMP_EXTRACT%' -Force"
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
if not exist "%TEMP_EXTRACT%\biliTickerBuy.exe" (
|
||||
echo 解压后的更新包中缺少 biliTickerBuy.exe
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [biliTickerBuy] 正在替换本地文件...
|
||||
copy /y "%TEMP_EXTRACT%\biliTickerBuy.exe" "%INSTALL_DIR%\biliTickerBuy.exe" >nul
|
||||
if errorlevel 1 (
|
||||
echo 无法替换 biliTickerBuy.exe。
|
||||
echo 请先关闭正在运行的 biliTickerBuy,然后重新执行 update.bat。
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
if exist "%TEMP_EXTRACT%\update.bat" copy /y "%TEMP_EXTRACT%\update.bat" "%INSTALL_DIR%\update.bat" >nul
|
||||
if exist "%TEMP_EXTRACT%\.env.install" copy /y "%TEMP_EXTRACT%\.env.install" "%INSTALL_DIR%\.env.install" >nul
|
||||
if exist "%TEMP_ZIP%" del /f /q "%TEMP_ZIP%" >nul 2>nul
|
||||
if exist "%META_FILE%" del /f /q "%META_FILE%" >nul 2>nul
|
||||
if exist "%TEMP_EXTRACT%" rmdir /s /q "%TEMP_EXTRACT%" >nul 2>nul
|
||||
|
||||
echo [biliTickerBuy] 已更新到 !RELEASE_TAG!。
|
||||
echo 请手动重新启动程序。
|
||||
pause
|
||||
@@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
REPO="mikumifa/biliTickerBuy"
|
||||
UNAME_S="$(uname -s)"
|
||||
UNAME_M="$(uname -m)"
|
||||
|
||||
case "$UNAME_S:$UNAME_M" in
|
||||
Linux:x86_64|Linux:amd64) PLATFORM_KEY="linux_amd64" ;;
|
||||
Linux:aarch64|Linux:arm64) PLATFORM_KEY="linux_arm64" ;;
|
||||
Darwin:arm64|Darwin:aarch64) PLATFORM_KEY="macos_arm64" ;;
|
||||
Darwin:x86_64|Darwin:amd64) PLATFORM_KEY="macos_intel" ;;
|
||||
*)
|
||||
echo "当前平台暂不支持自动更新:$UNAME_S/$UNAME_M" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
INSTALL_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||||
WORK_DIR="$INSTALL_DIR/updates"
|
||||
TEMP_ZIP="$WORK_DIR/update.zip"
|
||||
TEMP_EXTRACT="$WORK_DIR/extract"
|
||||
API_URL="https://api.github.com/repos/$REPO/releases/latest"
|
||||
ENV_INSTALL_FILE="$INSTALL_DIR/.env.install"
|
||||
|
||||
[ -f "$ENV_INSTALL_FILE" ] && . "$ENV_INSTALL_FILE"
|
||||
GH_PROXY="${GH_PROXY:-}"
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || {
|
||||
echo "缺少必要命令:$1" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
resolve_url() {
|
||||
case "${GH_PROXY}" in
|
||||
"")
|
||||
printf '%s\n' "$1"
|
||||
;;
|
||||
*/)
|
||||
printf '%s%s\n' "${GH_PROXY}" "$1"
|
||||
;;
|
||||
*)
|
||||
printf '%s/%s\n' "${GH_PROXY}" "$1"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
http_get() {
|
||||
url="$1"
|
||||
output="${2:-}"
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
if [ -n "$output" ]; then
|
||||
curl --fail --location --progress-bar -H 'User-Agent: biliTickerBuy-updater' -o "$output" "$url"
|
||||
else
|
||||
curl --fail --location --silent --show-error -H 'User-Agent: biliTickerBuy-updater' "$url"
|
||||
fi
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
if [ -n "$output" ]; then
|
||||
wget -O "$output" --header='User-Agent: biliTickerBuy-updater' "$url"
|
||||
else
|
||||
wget -qO- --header='User-Agent: biliTickerBuy-updater' "$url"
|
||||
fi
|
||||
else
|
||||
echo "缺少必要命令:curl 或 wget" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
require_cmd unzip
|
||||
mkdir -p "$WORK_DIR"
|
||||
rm -rf "$TEMP_EXTRACT"
|
||||
mkdir -p "$TEMP_EXTRACT"
|
||||
|
||||
RELEASE_JSON="$(http_get "$(resolve_url "$API_URL")")"
|
||||
ASSET_URL="$(printf '%s' "$RELEASE_JSON" | tr -d '\n' | sed 's/},{/},\
|
||||
{/g' | grep "\"name\":\"[^\"]*_${PLATFORM_KEY}_[^\"]*\"" | sed -n 's/.*"browser_download_url":"\([^"]*\)".*/\1/p' | head -n 1)"
|
||||
RELEASE_TAG="$(printf '%s' "$RELEASE_JSON" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' | head -n 1)"
|
||||
|
||||
[ -n "$ASSET_URL" ] || {
|
||||
echo "最新版本中未找到当前平台 ${PLATFORM_KEY} 对应的更新包" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
[ -n "$RELEASE_TAG" ] || {
|
||||
echo "解析最新版本号失败" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ -f "$TEMP_ZIP" ]; then
|
||||
echo "[biliTickerBuy] 检测到已下载的更新包,跳过下载:$TEMP_ZIP"
|
||||
else
|
||||
echo "[biliTickerBuy] 正在下载 ${RELEASE_TAG}..."
|
||||
http_get "$(resolve_url "$ASSET_URL")" "$TEMP_ZIP"
|
||||
fi
|
||||
|
||||
echo "[biliTickerBuy] 正在解压更新包..."
|
||||
unzip -oq "$TEMP_ZIP" -d "$TEMP_EXTRACT"
|
||||
|
||||
if [ -d "$TEMP_EXTRACT/biliTickerBuy" ]; then
|
||||
if ! cp -R "$TEMP_EXTRACT/biliTickerBuy/." "$INSTALL_DIR/"; then
|
||||
echo "替换文件失败,请先关闭正在运行的 biliTickerBuy,然后重新执行 update.sh。" >&2
|
||||
exit 1
|
||||
fi
|
||||
elif [ -f "$TEMP_EXTRACT/biliTickerBuy.exe" ]; then
|
||||
if ! cp "$TEMP_EXTRACT/biliTickerBuy.exe" "$INSTALL_DIR/"; then
|
||||
echo "替换文件失败,请先关闭正在运行的 biliTickerBuy,然后重新执行 update.sh。" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "解压后的更新包中缺少预期文件。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$TEMP_EXTRACT/update.sh" ]; then
|
||||
cp "$TEMP_EXTRACT/update.sh" "$INSTALL_DIR/"
|
||||
chmod +x "$INSTALL_DIR/update.sh"
|
||||
fi
|
||||
if [ -f "$TEMP_EXTRACT/.env.install" ]; then
|
||||
cp "$TEMP_EXTRACT/.env.install" "$INSTALL_DIR/"
|
||||
fi
|
||||
rm -f "$TEMP_ZIP"
|
||||
rm -rf "$TEMP_EXTRACT"
|
||||
|
||||
echo "[biliTickerBuy] 更新完成。"
|
||||
echo "请手动重新启动程序。"
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
REPO="mikumifa/biliTickerBuy"
|
||||
UNAME_S="$(uname -s)"
|
||||
UNAME_M="$(uname -m)"
|
||||
GH_PROXY="${GH_PROXY:-}"
|
||||
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/share/biliTickerBuy}"
|
||||
BIN_DIR="${BIN_DIR:-$HOME/.local/bin}"
|
||||
LAUNCHER_PATH="$BIN_DIR/btb"
|
||||
API_URL="https://api.github.com/repos/$REPO/releases/latest"
|
||||
PATH_MARKER_BEGIN="# >>> biliTickerBuy PATH >>>"
|
||||
PATH_MARKER_END="# <<< biliTickerBuy PATH <<<"
|
||||
|
||||
case "$UNAME_S:$UNAME_M" in
|
||||
Linux:x86_64|Linux:amd64) PLATFORM_KEY="linux_amd64" ;;
|
||||
Linux:aarch64|Linux:arm64) PLATFORM_KEY="linux_arm64" ;;
|
||||
Darwin:arm64|Darwin:aarch64) PLATFORM_KEY="macos_arm64" ;;
|
||||
Darwin:x86_64|Darwin:amd64) PLATFORM_KEY="macos_intel" ;;
|
||||
*)
|
||||
echo "当前平台暂不支持该安装脚本:$UNAME_S/$UNAME_M" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || {
|
||||
echo "缺少必要命令:$1" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
resolve_url() {
|
||||
case "${GH_PROXY}" in
|
||||
"")
|
||||
printf '%s\n' "$1"
|
||||
;;
|
||||
*/)
|
||||
printf '%s%s\n' "${GH_PROXY}" "$1"
|
||||
;;
|
||||
*)
|
||||
printf '%s/%s\n' "${GH_PROXY}" "$1"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
http_get() {
|
||||
url="$1"
|
||||
output="${2:-}"
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
if [ -n "$output" ]; then
|
||||
curl --fail --location --progress-bar -H 'User-Agent: biliTickerBuy-installer' -o "$output" "$url"
|
||||
else
|
||||
curl --fail --location --silent --show-error -H 'User-Agent: biliTickerBuy-installer' "$url"
|
||||
fi
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
if [ -n "$output" ]; then
|
||||
wget -O "$output" --header='User-Agent: biliTickerBuy-installer' "$url"
|
||||
else
|
||||
wget -qO- --header='User-Agent: biliTickerBuy-installer' "$url"
|
||||
fi
|
||||
else
|
||||
echo "缺少必要命令:curl 或 wget" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
append_path_block() {
|
||||
rc_file="$1"
|
||||
shell_name="$2"
|
||||
[ -n "$rc_file" ] || return 0
|
||||
mkdir -p "$(dirname "$rc_file")"
|
||||
[ -f "$rc_file" ] || : >"$rc_file"
|
||||
|
||||
if grep -Fq "$PATH_MARKER_BEGIN" "$rc_file" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
{
|
||||
printf '\n%s\n' "$PATH_MARKER_BEGIN"
|
||||
printf '# biliTickerBuy installer (%s)\n' "$shell_name"
|
||||
printf 'export PATH="%s:$PATH"\n' "$BIN_DIR"
|
||||
printf '%s\n' "$PATH_MARKER_END"
|
||||
} >>"$rc_file"
|
||||
}
|
||||
|
||||
apply_shell_path() {
|
||||
append_path_block "${HOME}/.bashrc" "bash"
|
||||
append_path_block "${HOME}/.zshrc" "zsh"
|
||||
}
|
||||
|
||||
require_cmd unzip
|
||||
TMP_DIR="$(mktemp -d)"
|
||||
ZIP_PATH="$TMP_DIR/biliTickerBuy.zip"
|
||||
EXTRACT_DIR="$TMP_DIR/extract"
|
||||
mkdir -p "$EXTRACT_DIR"
|
||||
trap 'rm -rf "$TMP_DIR"' EXIT INT TERM
|
||||
|
||||
echo "[biliTickerBuy] 正在检查最新版本..."
|
||||
RELEASE_JSON="$(http_get "$(resolve_url "$API_URL")")"
|
||||
ASSET_URL="$(printf '%s' "$RELEASE_JSON" | tr -d '\n' | sed 's/},{/},\
|
||||
{/g' | grep "\"name\":\"[^\"]*_${PLATFORM_KEY}_[^\"]*\"" | sed -n 's/.*"browser_download_url":"\([^"]*\)".*/\1/p' | head -n 1)"
|
||||
RELEASE_TAG="$(printf '%s' "$RELEASE_JSON" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' | head -n 1)"
|
||||
|
||||
[ -n "$ASSET_URL" ] || {
|
||||
echo "最新版本中未找到当前平台 ${PLATFORM_KEY} 对应的安装包" >&2
|
||||
exit 1
|
||||
}
|
||||
[ -n "$RELEASE_TAG" ] || {
|
||||
echo "解析最新版本号失败" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "[biliTickerBuy] 正在下载 ${RELEASE_TAG}..."
|
||||
http_get "$(resolve_url "$ASSET_URL")" "$ZIP_PATH"
|
||||
|
||||
echo "[biliTickerBuy] 正在解压安装包..."
|
||||
unzip -oq "$ZIP_PATH" -d "$EXTRACT_DIR"
|
||||
|
||||
if [ ! -d "$EXTRACT_DIR/biliTickerBuy" ]; then
|
||||
echo "安装包内容不符合预期,缺少 biliTickerBuy 目录。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$INSTALL_DIR")" "$BIN_DIR"
|
||||
rm -rf "$INSTALL_DIR"
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
cp -R "$EXTRACT_DIR/biliTickerBuy/." "$INSTALL_DIR/"
|
||||
|
||||
if [ -f "$INSTALL_DIR/update.sh" ]; then
|
||||
chmod +x "$INSTALL_DIR/update.sh"
|
||||
fi
|
||||
if [ -f "$INSTALL_DIR/biliTickerBuy" ]; then
|
||||
chmod +x "$INSTALL_DIR/biliTickerBuy"
|
||||
fi
|
||||
|
||||
cat >"$LAUNCHER_PATH" <<EOF
|
||||
#!/usr/bin/env sh
|
||||
exec "$INSTALL_DIR/biliTickerBuy" "\$@"
|
||||
EOF
|
||||
chmod +x "$LAUNCHER_PATH"
|
||||
apply_shell_path
|
||||
|
||||
echo "[biliTickerBuy] 安装完成:$INSTALL_DIR"
|
||||
echo "[biliTickerBuy] 启动命令:$LAUNCHER_PATH"
|
||||
case ":$PATH:" in
|
||||
*":$BIN_DIR:"*) ;;
|
||||
*)
|
||||
echo "[biliTickerBuy] 已写入 PATH 到 ~/.bashrc 和 ~/.zshrc(如存在)。"
|
||||
echo "请重新打开终端,或执行:export PATH=\"$BIN_DIR:\$PATH\""
|
||||
;;
|
||||
esac
|
||||
+64
-34
@@ -3,6 +3,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import gradio as gr
|
||||
@@ -13,13 +16,13 @@ from app_update import (
|
||||
UPDATE_CHANNEL_STABLE,
|
||||
ReleaseInfo,
|
||||
UpdateError,
|
||||
download_update_package,
|
||||
fetch_update,
|
||||
)
|
||||
from app_version import get_app_version
|
||||
from util import ConfigDB, EXE_PATH
|
||||
|
||||
UPDATE_CHANNEL_KEY = "update_channel"
|
||||
PACKAGE_NAME = "bilitickerbuy"
|
||||
|
||||
|
||||
def _saved_channel() -> str:
|
||||
@@ -47,6 +50,62 @@ def _format_update(release: ReleaseInfo | None, channel: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _update_script_name() -> str:
|
||||
return "update.bat" if os.name == "nt" else "update.sh"
|
||||
|
||||
|
||||
def _runtime_mode() -> str:
|
||||
if getattr(sys, "frozen", False):
|
||||
return "bundled"
|
||||
if sys.argv and sys.argv[0].endswith(".py"):
|
||||
return "source"
|
||||
if (Path(EXE_PATH) / "pyproject.toml").exists():
|
||||
return "source"
|
||||
return "pip"
|
||||
|
||||
|
||||
def _source_update_hint() -> str:
|
||||
repo_dir = html.escape(EXE_PATH)
|
||||
return (
|
||||
"当前是源码运行。"
|
||||
f"<br>请先同步源码目录 <code>{repo_dir}</code>,再重新安装依赖或重新启动。"
|
||||
"<br>如果你是用 Git 拉取的仓库,通常执行 <code>git pull</code> 即可。"
|
||||
)
|
||||
|
||||
|
||||
def _pip_update_hint(channel: str) -> str:
|
||||
command = f"python -m pip install -U {PACKAGE_NAME}"
|
||||
if channel != UPDATE_CHANNEL_STABLE:
|
||||
command += " --pre"
|
||||
return (
|
||||
f"当前是 `pip` 安装版本。<br>请在终端执行:<code>{html.escape(command)}</code>"
|
||||
)
|
||||
|
||||
|
||||
def _bundled_update_hint() -> str:
|
||||
script_name = _update_script_name()
|
||||
script_path = html.escape(os.path.join(EXE_PATH, script_name))
|
||||
system = platform.system().lower()
|
||||
if system == "windows":
|
||||
usage = "关闭程序后,双击运行该 bat,它会自动下载最新版本并覆盖当前目录。"
|
||||
else:
|
||||
usage = "关闭程序后,在终端执行该脚本,它会自动下载最新版本并覆盖当前目录。"
|
||||
return (
|
||||
"当前是打包版。"
|
||||
f"<br>请使用安装目录中的 <code>{script_path}</code> 完成更新。"
|
||||
f"<br>{usage}"
|
||||
)
|
||||
|
||||
|
||||
def _update_hint(channel: str) -> str:
|
||||
mode = _runtime_mode()
|
||||
if mode == "bundled":
|
||||
return _bundled_update_hint()
|
||||
if mode == "source":
|
||||
return _source_update_hint()
|
||||
return _pip_update_hint(channel)
|
||||
|
||||
|
||||
def check_updates(channel: str):
|
||||
ConfigDB.insert(UPDATE_CHANNEL_KEY, channel)
|
||||
try:
|
||||
@@ -58,30 +117,12 @@ def check_updates(channel: str):
|
||||
f"<span>{html.escape(str(exc))}</span>"
|
||||
"</div>"
|
||||
)
|
||||
return message, None, gr.update(visible=False)
|
||||
return message, None, gr.update(value=_update_hint(channel))
|
||||
|
||||
return (
|
||||
_format_update(release, channel),
|
||||
release.to_dict() if release else None,
|
||||
gr.update(visible=release is not None),
|
||||
)
|
||||
|
||||
|
||||
def download_update(release_data: dict | None):
|
||||
if not release_data:
|
||||
return gr.update(value=None, visible=False), "请先检查更新。"
|
||||
|
||||
try:
|
||||
release = ReleaseInfo.from_dict(release_data)
|
||||
download_dir = Path(EXE_PATH) / "updates" / release.tag_name
|
||||
package_path = download_update_package(release, download_dir)
|
||||
except (UpdateError, requests.RequestException, OSError, ValueError) as exc:
|
||||
return gr.update(value=None, visible=False), f"下载失败:{exc}"
|
||||
|
||||
return (
|
||||
gr.update(value=str(package_path), visible=True),
|
||||
"更新包下载完成且 SHA-256 校验通过。程序不会自动退出或覆盖文件,"
|
||||
"请结束正在执行的任务后,再解压并替换旧版本。",
|
||||
gr.update(value=_update_hint(channel)),
|
||||
)
|
||||
|
||||
|
||||
@@ -99,21 +140,10 @@ def update_tab(demo: gr.Blocks):
|
||||
|
||||
with gr.Row():
|
||||
check_button = gr.Button("立即检查", variant="secondary")
|
||||
download_button = gr.Button(
|
||||
"下载并校验更新包", variant="primary", visible=False
|
||||
)
|
||||
|
||||
notice = gr.Markdown(
|
||||
"更新不会静默安装。只有点击下载后才会获取更新包,且校验通过后仍需由你确认并手动替换。"
|
||||
)
|
||||
package_file = gr.File(label="已验证的更新包", visible=False, interactive=False)
|
||||
notice = gr.Markdown(_update_hint(_saved_channel()))
|
||||
|
||||
check_outputs = [status, release_state, download_button]
|
||||
check_outputs = [status, release_state, notice]
|
||||
demo.load(check_updates, inputs=channel, outputs=check_outputs)
|
||||
check_button.click(check_updates, inputs=channel, outputs=check_outputs)
|
||||
channel.change(check_updates, inputs=channel, outputs=check_outputs)
|
||||
download_button.click(
|
||||
download_update,
|
||||
inputs=release_state,
|
||||
outputs=[package_file, notice],
|
||||
)
|
||||
@@ -1,15 +1,6 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app_update import (
|
||||
UPDATE_CHANNEL_PRERELEASE,
|
||||
UPDATE_CHANNEL_STABLE,
|
||||
ReleaseInfo,
|
||||
UpdateError,
|
||||
download_update_package,
|
||||
select_update,
|
||||
)
|
||||
|
||||
@@ -39,121 +30,3 @@ def test_prerelease_channel_selects_newest_version():
|
||||
update = select_update(releases, "2.14.16", UPDATE_CHANNEL_PRERELEASE)
|
||||
assert update is not None
|
||||
assert update.version == "2.15.0b1"
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self, *, payload=None, content=b""):
|
||||
self._payload = payload
|
||||
self._content = content
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def iter_content(self, chunk_size):
|
||||
yield self._content
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, traceback):
|
||||
return False
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, manifest, package):
|
||||
self.manifest = manifest
|
||||
self.package = package
|
||||
|
||||
def get(self, url, **kwargs):
|
||||
if url.endswith("version-info.json"):
|
||||
return FakeResponse(payload=self.manifest)
|
||||
return FakeResponse(content=self.package)
|
||||
|
||||
|
||||
def test_download_verifies_sha256(tmp_path: Path):
|
||||
package = b"verified update"
|
||||
filename = "btb_linux_amd64_v2.14.17.zip"
|
||||
manifest = {
|
||||
"version": "v2.14.17",
|
||||
"files": {
|
||||
"linux_amd64": {
|
||||
"name": filename,
|
||||
"sha256": hashlib.sha256(package).hexdigest(),
|
||||
"size": len(package),
|
||||
}
|
||||
},
|
||||
}
|
||||
release = ReleaseInfo(
|
||||
version="2.14.17",
|
||||
tag_name="v2.14.17",
|
||||
name="v2.14.17",
|
||||
html_url="https://example.test/release",
|
||||
body="",
|
||||
prerelease=False,
|
||||
published_at="",
|
||||
assets=(
|
||||
{
|
||||
"name": "version-info.json",
|
||||
"browser_download_url": "https://example.test/version-info.json",
|
||||
"size": 1,
|
||||
},
|
||||
{
|
||||
"name": filename,
|
||||
"browser_download_url": "https://example.test/package.zip",
|
||||
"size": len(package),
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
with patch("app_update.platform_asset_key", return_value="linux_amd64"):
|
||||
output = download_update_package(
|
||||
release, tmp_path, session=FakeSession(manifest, package)
|
||||
)
|
||||
|
||||
assert output.read_bytes() == package
|
||||
|
||||
|
||||
def test_download_rejects_bad_sha256(tmp_path: Path):
|
||||
filename = "btb_linux_amd64_v2.14.17.zip"
|
||||
manifest = {
|
||||
"version": "v2.14.17",
|
||||
"files": {
|
||||
"linux_amd64": {
|
||||
"name": filename,
|
||||
"sha256": "0" * 64,
|
||||
"size": len(b"tampered"),
|
||||
}
|
||||
},
|
||||
}
|
||||
release = ReleaseInfo(
|
||||
version="2.14.17",
|
||||
tag_name="v2.14.17",
|
||||
name="v2.14.17",
|
||||
html_url="https://example.test/release",
|
||||
body="",
|
||||
prerelease=False,
|
||||
published_at="",
|
||||
assets=(
|
||||
{
|
||||
"name": "version-info.json",
|
||||
"browser_download_url": "https://example.test/version-info.json",
|
||||
"size": 1,
|
||||
},
|
||||
{
|
||||
"name": filename,
|
||||
"browser_download_url": "https://example.test/package.zip",
|
||||
"size": len(b"tampered"),
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
with patch("app_update.platform_asset_key", return_value="linux_amd64"):
|
||||
with pytest.raises(UpdateError, match="SHA-256"):
|
||||
download_update_package(
|
||||
release, tmp_path, session=FakeSession(manifest, b"tampered")
|
||||
)
|
||||
|
||||
assert not list(tmp_path.iterdir())
|
||||
Reference in new issue
Block a user