Skip to content

The only downloader you need. 下载器的集大成者。

feat(linux): 新增一键安装脚本并收敛发布包

XiaoYouChR83aaefb67bc2
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index f77b9254..aabf3937 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -623,11 +623,9 @@ jobs:
include:
- architecture: x86_64
runner: ubuntu-22.04
- deb_arch: amd64
appimage_arch: x86_64
- architecture: arm64
runner: ubuntu-24.04-arm
- deb_arch: arm64
appimage_arch: aarch64
runs-on: ${{ matrix.runner }}
steps:
@@ -710,73 +708,49 @@ jobs:
fi
done
- - name: Build .deb and .AppImage
+ - name: Build .AppImage
run: |
DIST_DIR="dist/Ghost-Downloader-3.dist"
- DEB_ROOT="$RUNNER_TEMP/deb-root"
APPDIR="$RUNNER_TEMP/GhostDownloader.AppDir"
PACKAGE_NAME="ghost-downloader"
- INSTALL_DIR="/opt/Ghost-Downloader-3"
DESKTOP_FILE="com.xychr.ghostdownloader.desktop"
ICON_FILE="$PACKAGE_NAME.png"
- DEB_FILE="dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.deb"
APPIMAGE_FILE="dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.AppImage"
APPIMAGETOOL_FILE="appimagetool-${{ matrix.appimage_arch }}.AppImage"
APPIMAGETOOL_URL="https://github.com/AppImage/appimagetool/releases/latest/download/${APPIMAGETOOL_FILE}"
- rm -rf "$DEB_ROOT" "$APPDIR" "$RUNNER_TEMP/squashfs-root"
+ rm -rf "$APPDIR" "$RUNNER_TEMP/squashfs-root"
mkdir -p \
- "$DEB_ROOT/DEBIAN" \
- "$DEB_ROOT$INSTALL_DIR" \
- "$DEB_ROOT/usr/bin" \
- "$DEB_ROOT/usr/share/applications" \
- "$DEB_ROOT/usr/share/icons/hicolor/256x256/apps" \
"$APPDIR/usr/bin" \
"$APPDIR/usr/lib/$PACKAGE_NAME" \
"$APPDIR/usr/share/applications" \
"$APPDIR/usr/share/icons/hicolor/256x256/apps"
- cp -R "$DIST_DIR"/. "$DEB_ROOT$INSTALL_DIR/"
cp -R "$DIST_DIR"/. "$APPDIR/usr/lib/$PACKAGE_NAME/"
cp /usr/lib/*/libzstd.so.1 "$APPDIR/usr/lib/$PACKAGE_NAME/"
- ln -s "$INSTALL_DIR/Ghost-Downloader-3.bin" "$DEB_ROOT/usr/bin/$PACKAGE_NAME"
ln -s "../lib/$PACKAGE_NAME/Ghost-Downloader-3.bin" "$APPDIR/usr/bin/$PACKAGE_NAME"
ln -s "usr/bin/$PACKAGE_NAME" "$APPDIR/AppRun"
- cat > "$DEB_ROOT/DEBIAN/control" <<EOF
- Package: $PACKAGE_NAME
- Version: ${{ env.VERSION }}
- Section: net
- Priority: optional
- Architecture: ${{ matrix.deb_arch }}
- Maintainer: XiaoYouChR <[email protected]>
- Description: Ghost Downloader
- A multi-threading downloader based on PySide6.
- EOF
-
- cat > "$DEB_ROOT/usr/share/applications/$DESKTOP_FILE" <<EOF
+ cat > "$APPDIR/usr/share/applications/$DESKTOP_FILE" <<EOF
[Desktop Entry]
Type=Application
Name=Ghost Downloader
- Comment=A multi-threading downloader based on PySide6
- Exec=$PACKAGE_NAME
+ Comment=The only downloader you need
+ Exec=$PACKAGE_NAME %U
Icon=$PACKAGE_NAME
Terminal=false
Categories=Network;Utility;
StartupNotify=false
EOF
- cp "$DEB_ROOT/usr/share/applications/$DESKTOP_FILE" "$APPDIR/usr/share/applications/$DESKTOP_FILE"
- cp "app/assets/logo.png" "$DEB_ROOT/usr/share/icons/hicolor/256x256/apps/$ICON_FILE"
cp "app/assets/logo.png" "$APPDIR/usr/share/icons/hicolor/256x256/apps/$ICON_FILE"
ln -s "usr/share/applications/$DESKTOP_FILE" "$APPDIR/$DESKTOP_FILE"
ln -s "usr/share/icons/hicolor/256x256/apps/$ICON_FILE" "$APPDIR/$ICON_FILE"
ln -s "usr/share/icons/hicolor/256x256/apps/$ICON_FILE" "$APPDIR/.DirIcon"
- desktop-file-validate "$DEB_ROOT/usr/share/applications/$DESKTOP_FILE"
- dpkg-deb --build --root-owner-group "$DEB_ROOT" "$DEB_FILE"
+ desktop-file-validate "$APPDIR/usr/share/applications/$DESKTOP_FILE"
curl -fL "$APPIMAGETOOL_URL" -o "$RUNNER_TEMP/$APPIMAGETOOL_FILE"
chmod +x "$RUNNER_TEMP/$APPIMAGETOOL_FILE"
@@ -791,7 +765,6 @@ jobs:
)
chmod +x "$APPIMAGE_FILE"
- dpkg-deb --info "$DEB_FILE"
file "$APPIMAGE_FILE"
- name: Tar the contents of Ghost-Downloader
@@ -801,6 +774,7 @@ jobs:
$distPath = "dist/Ghost-Downloader-3.dist"
$tarFile = "Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.tar.xz"
+ Copy-Item "app/assets/logo.png" "$distPath/logo.png"
Write-Output "Creating tar.xz archive of $distPath..."
tar -cJf $tarFile -C $distPath .
Write-Output "Archive created at $tarFile"
@@ -812,7 +786,6 @@ jobs:
run: |
gh release upload "v${{ env.VERSION }}" \
"Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.tar.xz" \
- "dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.deb" \
"dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.AppImage" \
--clobber
@@ -823,7 +796,6 @@ jobs:
name: Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}
path: |
dist/Ghost-Downloader-3.dist
- dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.deb
dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.AppImage
android-libtorrent:
@@ -1055,7 +1027,7 @@ jobs:
finalize:
needs: [prepare, build-windows, build-macos, build-ubuntu, build-android]
- if: ${{ always() && github.event.inputs.create_release == 'true' && needs.build-windows.result == 'success' && needs.build-macos.result == 'success' }}
+ if: ${{ always() && github.event.inputs.create_release == 'true' && needs.prepare.result == 'success' && !contains(fromJSON('["failure","cancelled"]'), needs.build-windows.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-macos.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-ubuntu.result) && (needs.build-windows.result == 'success' || needs.build-macos.result == 'success' || needs.build-ubuntu.result == 'success') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
@@ -1078,7 +1050,7 @@ jobs:
PREV_VER: ${{ needs.prepare.outputs.patch_base }}
run: |
mkdir -p assets
- gh release download "v${VERSION}" --repo ${{ github.repository }} -p "*.hdiff" -p "*.zip" -p "*.dmg" -p "*.tar.xz" -p "*.deb" -p "*.AppImage" -p "*.apk" -p "*.exe" -D assets/ 2>/dev/null || true
+ gh release download "v${VERSION}" --repo ${{ github.repository }} -p "*.hdiff" -p "*.zip" -p "*.dmg" -p "*.tar.xz" -p "*.AppImage" -p "*.apk" -p "*.exe" -D assets/ 2>/dev/null || true
uv run --no-project python3 << 'PYEOF'
import hashlib, json, os
@@ -1094,7 +1066,12 @@ jobs:
h.update(chunk)
return h.hexdigest()
- platforms = ["Windows-x86_64", "Windows-arm64", "macOS-arm64", "macOS-x86_64"]
+ platforms = [
+ "Windows-x86_64", "Windows-arm64",
+ "macOS-arm64", "macOS-x86_64",
+ "Linux-x86_64", "Linux-arm64",
+ ]
+ full_ext = {"Windows": ".zip", "macOS": ".dmg", "Linux": ".tar.xz"}
patches = {}
full = {}
@@ -1102,10 +1079,12 @@ jobs:
for f in os.listdir(assets_dir):
if f.startswith(f"patch-{p}-") and f.endswith(".hdiff"):
path = os.path.join(assets_dir, f)
- patches[p] = {"from": prev_ver, "file": f, "sha256": sha256of(path), "size": os.path.getsize(path)}
+ prefix, suffix = f"patch-{p}-", f"-to-{version}.hdiff"
+ from_ver = f[len(prefix):-len(suffix)] if f.endswith(suffix) else prev_ver
+ patches[p] = {"from": from_ver, "file": f, "sha256": sha256of(path), "size": os.path.getsize(path)}
break
- ext = ".zip" if p.startswith("Windows") else ".dmg"
+ ext = full_ext[p.split("-", 1)[0]]
full_name = f"Ghost-Downloader-v{version}-{p}{ext}"
full_path = os.path.join(assets_dir, full_name)
if os.path.isfile(full_path):
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index 68ab10fc..d3ce928a 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -74,7 +74,7 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
from app.signal_bus import signalBus
from app.services.port_listener import ListenStatus
from app.services.update_service import UpdateService
- from app.startup import loadResources, setupThemeColor, createEngine, deleteBackupDir, deleteLegacyAppIdFiles, loadPacks, checkUpdateAtStartup
+ from app.startup import loadResources, setupThemeColor, createEngine, deleteBackupDir, loadPacks, checkUpdateAtStartup
from app.view.windows.main_window import MainWindow
def exceptionHook(exceptionType, value, tb):
@@ -105,13 +105,6 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
browserService, speedMeter = engine.browserService, engine.speedMeter
deleteBackupDir()
- if deleteLegacyAppIdFiles():
- from app.platform.file_association import registerUrlScheme
- from app.platform.run_at_login import setRunAtLogin
- if cfg.isUrlSchemeRegistered.value:
- registerUrlScheme()
- if cfg.shouldRunAtLogin.value:
- setRunAtLogin(True)
setupThemeColor(application)
diff --git a/app/platform/file_association.py b/app/platform/file_association.py
index 213792a1..829c44cc 100644
--- a/app/platform/file_association.py
+++ b/app/platform/file_association.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import os
import subprocess
import sys
from pathlib import Path
@@ -127,60 +128,89 @@ def _registerLinux(fileTypes: list[FileType]) -> None:
saveMimeTypes(schemes | {ft.mimeType for ft in fileTypes})
+HANDLER_DESKTOP_NAME = f"{DESKTOP_ID}.handler.desktop"
+DESKTOP_FILE = (
+ Path(os.environ["XDG_DATA_HOME"])
+ if os.environ.get("XDG_DATA_HOME", "").startswith("/")
+ else Path.home() / ".local/share"
+) / "applications" / HANDLER_DESKTOP_NAME
+MIMEAPPS_FILE = (
+ Path(os.environ["XDG_CONFIG_HOME"])
+ if os.environ.get("XDG_CONFIG_HOME", "").startswith("/")
+ else Path.home() / ".config"
+) / "mimeapps.list"
+
+
def loadMimeTypes() -> set[str]:
- desktopFile = Path.home() / ".local/share/applications" / f"{DESKTOP_ID}.desktop"
- if not desktopFile.exists():
+ if not DESKTOP_FILE.exists():
return set()
- for line in desktopFile.read_text(encoding="utf-8").splitlines():
+ for line in DESKTOP_FILE.read_text(encoding="utf-8").splitlines():
if line.startswith("MimeType="):
return {m for m in line[9:].split(";") if m}
return set()
-def saveMimeTypes(mimes: set[str]) -> None:
- desktopDir = Path.home() / ".local/share/applications"
- serviceDir = Path.home() / ".local/share/dbus-1/services"
- desktopFile = desktopDir / f"{DESKTOP_ID}.desktop"
- serviceFile = serviceDir / f"{DESKTOP_ID}.service"
+def deleteMimeDefaults(mimes: set[str]) -> None:
+ if not MIMEAPPS_FILE.exists():
+ return
+ lines: list[str] = []
+ isInDefaults = False
+ hasChanged = False
+ for line in MIMEAPPS_FILE.read_text(encoding="utf-8").splitlines(keepends=True):
+ stripped = line.strip()
+ if stripped.startswith("["):
+ isInDefaults = stripped == "[Default Applications]"
+ elif isInDefaults and "=" in line:
+ mime, rawValue = line.split("=", 1)
+ if mime.strip() in mimes:
+ entries = [e for e in rawValue.strip().split(";") if e]
+ remaining = [e for e in entries if e != HANDLER_DESKTOP_NAME]
+ if len(remaining) != len(entries):
+ hasChanged = True
+ if remaining:
+ lines.append(f"{mime}={';'.join(remaining)};\n")
+ continue
+ lines.append(line)
+
+ if hasChanged:
+ MIMEAPPS_FILE.write_text("".join(lines), encoding="utf-8")
+
+
+def saveMimeTypes(mimes: set[str]) -> None:
desktopText = (
"[Desktop Entry]\n"
"Type=Application\n"
"Name=Ghost Downloader\n"
+ "Comment=The only downloader you need\n"
f'Exec="{EXECUTABLE_PATH}" %U\n'
"Icon=ghost-downloader\n"
+ "NoDisplay=true\n"
"Terminal=false\n"
- "Categories=Network;Utility;\n"
- "DBusActivatable=true\n"
f"MimeType={';'.join(sorted(mimes))};\n"
)
- oldText = desktopFile.read_text(encoding="utf-8") if desktopFile.exists() else None
+ oldText = DESKTOP_FILE.read_text(encoding="utf-8") if DESKTOP_FILE.exists() else None
# 每次改写都会让桌面重建缓存,反复改写会卡住 KWin #1045
if oldText == (desktopText if mimes else None):
return
+ removed = loadMimeTypes() - mimes
if mimes:
- desktopDir.mkdir(parents=True, exist_ok=True)
- serviceDir.mkdir(parents=True, exist_ok=True)
- desktopFile.write_text(desktopText, encoding="utf-8")
- serviceFile.write_text(
- "[D-BUS Service]\n"
- f"Name={DESKTOP_ID}\n"
- f'Exec="{EXECUTABLE_PATH}"\n',
- encoding="utf-8",
- )
+ DESKTOP_FILE.parent.mkdir(parents=True, exist_ok=True)
+ DESKTOP_FILE.write_text(desktopText, encoding="utf-8")
else:
- desktopFile.unlink(missing_ok=True)
- serviceFile.unlink(missing_ok=True)
+ DESKTOP_FILE.unlink(missing_ok=True)
+ if removed:
+ deleteMimeDefaults(removed)
try:
- subprocess.run(["update-desktop-database", str(desktopDir)], check=False, capture_output=True)
+ subprocess.run(["update-desktop-database", str(DESKTOP_FILE.parent)], check=False, capture_output=True)
except FileNotFoundError:
logger.warning("缺少 update-desktop-database, 跳过")
for mime in mimes:
try:
- subprocess.run(["xdg-mime", "default", f"{DESKTOP_ID}.desktop", mime], check=False, capture_output=True)
+ subprocess.run(["xdg-mime", "default", HANDLER_DESKTOP_NAME, mime], check=False, capture_output=True)
except FileNotFoundError:
logger.warning("缺少 xdg-mime, 跳过文件关联")
break
diff --git a/app/platform/run_at_login.py b/app/platform/run_at_login.py
index fecb096c..4af7e2ef 100644
--- a/app/platform/run_at_login.py
+++ b/app/platform/run_at_login.py
@@ -58,9 +58,10 @@ def _setMacOS(enabled: bool) -> None:
def _setLinux(enabled: bool) -> None:
- from app.config.constants import DESKTOP_ID, VERSION
+ from app.config.constants import DESKTOP_ID
- autoStartDir = Path.home() / ".config/autostart"
+ configHome = Path(v) if (v := os.environ.get("XDG_CONFIG_HOME", "")).startswith("/") else Path.home() / ".config"
+ autoStartDir = configHome / "autostart"
desktopFile = autoStartDir / f"{DESKTOP_ID}.desktop"
if enabled:
@@ -68,10 +69,10 @@ def _setLinux(enabled: bool) -> None:
desktopFile.write_text(
"[Desktop Entry]\n"
"Type=Application\n"
- f"Version={VERSION}\n"
- "Name=Ghost Downloader 3\n"
- "Comment=A multi-threading downloader with QThread based on PySide6\n"
+ "Name=Ghost Downloader\n"
+ "Comment=The only downloader you need\n"
f'Exec="{EXECUTABLE_PATH}" --silence\n'
+ "Icon=ghost-downloader\n"
"StartupNotify=false\n"
"Terminal=false\n",
encoding="utf-8",
diff --git a/app/startup.py b/app/startup.py
index 462dba90..dbf38600 100644
--- a/app/startup.py
+++ b/app/startup.py
@@ -93,27 +93,6 @@ def deleteBackupDir() -> None:
shutil.rmtree(backupDir, ignore_errors=True)
-def deleteLegacyAppIdFiles() -> bool:
- import sys
- from pathlib import Path
-
- if sys.platform == "linux":
- legacyId = "io.github.xiaoyouchr.GhostDownloader"
- paths = [
- Path.home() / ".local/share/applications" / f"{legacyId}.desktop",
- Path.home() / ".local/share/dbus-1/services" / f"{legacyId}.service",
- Path.home() / ".config/autostart" / f"{legacyId}.desktop",
- ]
- elif sys.platform == "darwin":
- paths = [Path.home() / "Library/LaunchAgents/com.xiaoyouchr.ghostdownloader.plist"]
- else:
- return False
- existing = [path for path in paths if path.exists()]
- for path in existing:
- path.unlink()
- return bool(existing)
-
-
def loadPacks(featureService: FeatureService, coroutineRunner: CoroutineRunner, speedMeter: SpeedMeter) -> None:
from app.models.pack import PackServices
from app.services.update_service import installPendingPacks
diff --git a/scripts/install.sh b/scripts/install.sh
new file mode 100755
index 00000000..a97ccc7e
--- /dev/null
+++ b/scripts/install.sh
@@ -0,0 +1,378 @@
+#!/bin/sh
+set -eu
+
+REPO="XiaoYouChR/Ghost-Downloader-3"
+DESKTOP_ID="com.xychr.ghostdownloader"
+ICON_NAME="ghost-downloader"
+APP_BIN="Ghost-Downloader-3.bin"
+ICON_REL="logo.png"
+
+GITHUB_RAW="https://raw.githubusercontent.com/${REPO}/main"
+GITHUB_DL="https://github.com/${REPO}/releases/download"
+GITCODE_RAW="https://cnb.cool/${REPO}/-/git/raw/main"
+GITCODE_DL="https://gitcode.com/${REPO}/releases/download"
+
+# Only these two paths stay global so trap cleanup can delete them.
+WORK_DIR=""
+STAGE_DIR=""
+
+die() {
+ printf 'Error: %s\n' "$*" >&2
+ exit 1
+}
+
+cleanup() {
+ if [ -n "$WORK_DIR" ]; then
+ rm -rf "$WORK_DIR"
+ fi
+ if [ -n "$STAGE_DIR" ]; then
+ rm -rf "$STAGE_DIR"
+ fi
+}
+
+fetchFile() {
+ # $1=url $2=dest [$3=connectTimeoutSec] [$4=maxTimeSec]
+ if command -v curl >/dev/null 2>&1; then
+ if [ -n "${4:-}" ]; then
+ curl -fsSL --connect-timeout "${3:-10}" --max-time "$4" -o "$2" "$1"
+ else
+ curl -fsSL --connect-timeout "${3:-10}" -o "$2" "$1"
+ fi
+ else
+ wget -q -T "${3:-10}" -O "$2" "$1"
+ fi
+}
+
+toSha256() {
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "$1" | awk '{print tolower($1)}'
+ else
+ shasum -a 256 "$1" | awk '{print tolower($1)}'
+ fi
+}
+
+parseRelease() {
+ # $1=versionsJson $2=platformKey -> "version|file|sha256"
+ # versions.json uses json.dump(indent=2), so line matching finds app.version and app.full.<platformKey>.
+ awk -v platform="$2" '
+ function val(line) {
+ sub(/^[^:]*:[ \t]*"/, "", line)
+ sub(/".*$/, "", line)
+ return line
+ }
+ /"app":/ && !/\{\}/ { inApp = 1 }
+ inApp && /"version":/ && !ver { ver = val($0) }
+ inApp && /"full":/ && !/\{\}/ { inFull = 1; depth = 1; next }
+ inFull {
+ if (index($0, "{")) depth++
+ if (index($0, "}")) {
+ depth--
+ if (depth == 1) inPlat = 0
+ if (depth == 0) inFull = 0
+ }
+ if (depth == 2 && index($0, "\"" platform "\":")) {
+ inPlat = 1
+ next
+ }
+ if (inPlat && /"file":/) file = val($0)
+ if (inPlat && /"sha256":/) sha = val($0)
+ }
+ END { printf "%s|%s|%s\n", ver, file, tolower(sha) }
+ ' "$1"
+}
+
+installAppDir() {
+ # $1=archivePath $2=appDir
+ if [ -e "$2" ]; then
+ if [ ! -d "$2" ]; then
+ die "refusing to overwrite ${2}: not a directory"
+ fi
+ entries=$(ls -A "$2")
+ if [ ! -f "$2/$APP_BIN" ] && [ -n "$entries" ]; then
+ # Allow reinstalling into an App Dir that only keeps a Portable Folder from --uninstall.
+ if [ "$entries" != "GhostDownloader" ] || [ ! -d "$2/GhostDownloader" ]; then
+ die "refusing to overwrite non-empty directory ${2}: ${APP_BIN} not found"
+ fi
+ fi
+ fi
+
+ parentDir=$(dirname "$2")
+ mkdir -p "$parentDir"
+ # Put the staging folder next to App Dir so mv stays on the same filesystem.
+ STAGE_DIR=$(mktemp -d "${parentDir}/.gd3-stage.XXXXXX")
+ chmod 755 "$STAGE_DIR"
+
+ tar -xJf "$1" -C "$STAGE_DIR"
+ [ -f "$STAGE_DIR/$APP_BIN" ] || die "archive missing ${APP_BIN}"
+ chmod +x "$STAGE_DIR/$APP_BIN"
+
+ backupDir="${2}_backup"
+ rm -rf "$backupDir"
+ if [ -e "$2" ]; then
+ mv "$2" "$backupDir"
+ fi
+ if ! mv "$STAGE_DIR" "$2"; then
+ if [ -e "$backupDir" ] && [ ! -e "$2" ]; then
+ mv "$backupDir" "$2" || true
+ fi
+ die "failed to install into $2"
+ fi
+ STAGE_DIR=""
+ # Keep Portable Folder when upgrading an existing install.
+ if [ -d "$backupDir/GhostDownloader" ]; then
+ mv "$backupDir/GhostDownloader" "$2/GhostDownloader" \
+ || die "failed to restore Portable Folder from ${backupDir}"
+ fi
+ rm -rf "$backupDir" || true
+}
+
+refreshDesktopCaches() {
+ if command -v update-desktop-database >/dev/null 2>&1; then
+ update-desktop-database "$1/applications" 2>/dev/null || true
+ fi
+ if command -v gtk-update-icon-cache >/dev/null 2>&1; then
+ gtk-update-icon-cache -f -t "$1/icons/hicolor" 2>/dev/null || true
+ fi
+}
+
+runInstall() {
+ sourceMode="$1"
+ appDir="$2"
+ dataHome="$3"
+ binDir="$4"
+
+ [ "$(uname -s)" = "Linux" ] || die "this installer only supports Linux"
+ case "$(uname -m)" in
+ x86_64|amd64) platformKey="Linux-x86_64" ;;
+ aarch64|arm64) platformKey="Linux-arm64" ;;
+ *) die "unsupported architecture: $(uname -m)" ;;
+ esac
+
+ command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1 || die "curl or wget is required"
+ command -v tar >/dev/null 2>&1 || die "tar is required"
+ command -v xz >/dev/null 2>&1 || die "xz is required"
+ command -v awk >/dev/null 2>&1 || die "awk is required"
+ command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 || die "sha256sum or shasum is required"
+
+ WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/gd3-install.XXXXXX")
+ versionsFile="$WORK_DIR/versions.json"
+
+ printf 'Fetching version metadata (%s)...\n' "$platformKey"
+ if [ "$sourceMode" = "gitcode" ]; then
+ rawBase="$GITCODE_RAW"
+ fallbackRawBase=""
+ dlBase="$GITCODE_DL"
+ fallbackDlBase=""
+ fetchFile "${rawBase}/versions.json" "$versionsFile" 10 15 || die "failed to fetch versions.json"
+ elif [ "$sourceMode" = "github" ]; then
+ rawBase="$GITHUB_RAW"
+ fallbackRawBase=""
+ dlBase="$GITHUB_DL"
+ fallbackDlBase=""
+ fetchFile "${rawBase}/versions.json" "$versionsFile" 10 15 || die "failed to fetch versions.json"
+ elif fetchFile "${GITHUB_RAW}/versions.json" "$versionsFile" 5 15 2>/dev/null; then
+ rawBase="$GITHUB_RAW"
+ fallbackRawBase="$GITCODE_RAW"
+ dlBase="$GITHUB_DL"
+ fallbackDlBase="$GITCODE_DL"
+ elif fetchFile "${GITCODE_RAW}/versions.json" "$versionsFile" 10 15; then
+ rawBase="$GITCODE_RAW"
+ fallbackRawBase="$GITHUB_RAW"
+ dlBase="$GITCODE_DL"
+ fallbackDlBase="$GITHUB_DL"
+ else
+ die "failed to fetch versions.json"
+ fi
+
+ IFS='|' read -r version assetFile expectedSha <<EOF
+$(parseRelease "$versionsFile" "$platformKey")
+EOF
+ [ -n "$version" ] && [ -n "$assetFile" ] && [ -n "$expectedSha" ] \
+ || die "no Linux release entry for ${platformKey} in versions.json"
+ case "$assetFile" in
+ */*|*..*) die "unsafe asset filename: ${assetFile}" ;;
+ esac
+ [ "${#expectedSha}" -eq 64 ] || die "invalid sha256 in versions.json: ${expectedSha}"
+ case "$expectedSha" in
+ *[!0-9a-f]*) die "invalid sha256 in versions.json: ${expectedSha}" ;;
+ esac
+
+ archiveFile="$WORK_DIR/$assetFile"
+ printf 'Downloading Ghost Downloader v%s (%s)...\n' "$version" "$assetFile"
+ if ! fetchFile "${dlBase}/v${version}/${assetFile}" "$archiveFile" 30; then
+ if [ -n "$fallbackDlBase" ]; then
+ fetchFile "${fallbackDlBase}/v${version}/${assetFile}" "$archiveFile" 30 \
+ || die "failed to download ${assetFile}"
+ else
+ die "failed to download ${assetFile}"
+ fi
+ fi
+
+ actualSha=$(toSha256 "$archiveFile")
+ [ "$actualSha" = "$expectedSha" ] || die "sha256 mismatch (expected ${expectedSha}, got ${actualSha})"
+
+ printf 'Installing to %s...\n' "$appDir"
+ installAppDir "$archiveFile" "$appDir"
+
+ mkdir -p "$binDir"
+ ln -sfn "$appDir/$APP_BIN" "$binDir/ghost-downloader"
+ ln -sfn "$appDir/$APP_BIN" "$binDir/ghd"
+
+ desktopDir="$dataHome/applications"
+ iconDir="$dataHome/icons/hicolor/256x256/apps"
+ desktopFile="$desktopDir/${DESKTOP_ID}.desktop"
+ mkdir -p "$desktopDir" "$iconDir"
+ if [ -f "$appDir/$ICON_REL" ]; then
+ cp -f "$appDir/$ICON_REL" "$iconDir/${ICON_NAME}.png"
+ else
+ # Fetch logo.png from the repository when the archive does not include it.
+ iconTmp="$WORK_DIR/${ICON_NAME}.png"
+ if fetchFile "${rawBase}/app/assets/logo.png" "$iconTmp" 10 15 2>/dev/null \
+ || { [ -n "$fallbackRawBase" ] && fetchFile "${fallbackRawBase}/app/assets/logo.png" "$iconTmp" 10 15 2>/dev/null; }; then
+ cp -f "$iconTmp" "$iconDir/${ICON_NAME}.png"
+ fi
+ fi
+
+ {
+ printf '[Desktop Entry]\n'
+ printf 'Type=Application\n'
+ printf 'Name=Ghost Downloader\n'
+ printf 'Comment=The only downloader you need\n'
+ printf 'Exec="%s/%s" %%U\n' "$appDir" "$APP_BIN"
+ printf 'Icon=%s\n' "$ICON_NAME"
+ printf 'Terminal=false\n'
+ printf 'Categories=Network;Utility;\n'
+ } > "$desktopFile"
+ refreshDesktopCaches "$dataHome"
+
+ case ":${PATH:-}:" in
+ *":${binDir}:"*) ;;
+ *) printf 'Note: %s is not in PATH. Add it to your shell profile to use ghost-downloader / ghd.\n' "$binDir" >&2 ;;
+ esac
+ printf 'Ghost Downloader v%s installed.\n' "$version"
+}
+
+runUninstall() {
+ appDir="$1"
+ dataHome="$2"
+ configHome="$3"
+ binDir="$4"
+
+ # Do not delete anything if App Dir does not exist or points to an unrelated folder.
+ [ -e "$appDir" ] || die "${appDir} does not exist"
+ if [ ! -d "$appDir" ] || [ ! -f "$appDir/$APP_BIN" ]; then
+ die "refusing to delete ${appDir}: ${APP_BIN} not found"
+ fi
+
+ # Resolve physical App Dir so symlinks created via Path.resolve() match on symlinked $HOME.
+ realAppDir=$(cd -P -- "$appDir" && pwd)
+
+ # Delete only links that point into App Dir so another Command Line Tool install stays intact.
+ for name in ghost-downloader ghd; do
+ linkPath="$binDir/$name"
+ [ -L "$linkPath" ] || continue
+ case "$(readlink "$linkPath" || true)" in
+ "${appDir}/"*|"${realAppDir}/"*) rm -f "$linkPath" ;;
+ esac
+ done
+
+ rm -f "$dataHome/applications/${DESKTOP_ID}.desktop"
+ rm -f "$dataHome/applications/${DESKTOP_ID}.handler.desktop"
+ rm -f "$dataHome/dbus-1/services/${DESKTOP_ID}.service"
+ rm -f "$dataHome/icons/hicolor/256x256/apps/${ICON_NAME}.png"
+ rm -f "$configHome/autostart/${DESKTOP_ID}.desktop"
+ rm -rf "${appDir}_backup"
+
+ if [ -d "$appDir/GhostDownloader" ]; then
+ # Keep Portable Folder intact; delete only the application files beside it.
+ for entry in "$appDir"/* "$appDir"/.[!.]* "$appDir"/..?*; do
+ if [ ! -e "$entry" ] && [ ! -L "$entry" ]; then
+ continue
+ fi
+ if [ "$entry" = "$appDir/GhostDownloader" ]; then
+ continue
+ fi
+ rm -rf "$entry"
+ done
+ refreshDesktopCaches "$dataHome"
+ printf 'Ghost Downloader uninstalled. Portable Folder preserved in %s/GhostDownloader.\n' "$appDir"
+ return 0
+ fi
+
+ rm -rf "$appDir"
+ refreshDesktopCaches "$dataHome"
+
+ printf 'Ghost Downloader uninstalled. Data Folder preserved in %s/GhostDownloader.\n' "$dataHome"
+}
+
+main() {
+ trap cleanup EXIT
+ trap 'trap - EXIT; cleanup; exit 130' INT
+ trap 'trap - EXIT; cleanup; exit 143' TERM
+
+ action="install"
+ sourceMode="auto"
+ appDir=""
+
+ while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --source)
+ [ "$#" -ge 2 ] || die "--source requires a value"
+ case "$2" in
+ auto|github|gitcode) sourceMode="$2" ;;
+ *) die "unknown source: $2" ;;
+ esac
+ shift 2
+ ;;
+ --dir)
+ [ "$#" -ge 2 ] && [ -n "$2" ] || die "--dir requires a non-empty path"
+ appDir="$2"
+ shift 2
+ ;;
+ --uninstall)
+ action="uninstall"
+ shift
+ ;;
+ --help|-h)
+ cat <<'EOF'
+Usage: install.sh [--source auto|github|gitcode] [--dir <path>] [--uninstall] [--help]
+EOF
+ exit 0
+ ;;
+ *)
+ die "unknown option: $1 (try --help)"
+ ;;
+ esac
+ done
+
+ case "${HOME:-}" in
+ /*) ;;
+ *) die "HOME must be an absolute path" ;;
+ esac
+ case "${XDG_DATA_HOME:-}" in
+ /*) dataHome="$XDG_DATA_HOME" ;;
+ *) dataHome="$HOME/.local/share" ;;
+ esac
+ case "${XDG_CONFIG_HOME:-}" in
+ /*) configHome="$XDG_CONFIG_HOME" ;;
+ *) configHome="$HOME/.config" ;;
+ esac
+
+ binDir="$HOME/.local/bin"
+ [ -n "$appDir" ] || appDir="$HOME/.local/lib/ghost-downloader"
+ while [ "${appDir%/}" != "$appDir" ]; do
+ appDir="${appDir%/}"
+ done
+ case "$appDir" in
+ /*) ;;
+ *) die "--dir must be a non-root absolute path" ;;
+ esac
+
+ if [ "$action" = "uninstall" ]; then
+ runUninstall "$appDir" "$dataHome" "$configHome" "$binDir"
+ else
+ runInstall "$sourceMode" "$appDir" "$dataHome" "$binDir"
+ fi
+}
+
+main "$@"
diff --git a/versions.json b/versions.json
index e3e145ba..3d7dadd6 100644
--- a/versions.json
+++ b/versions.json
@@ -47,6 +47,16 @@
"file": "Ghost-Downloader-v4.5.11-macOS-x86_64.dmg",
"sha256": "20c0db4e0d0a48a184d99d39a69f9dc27d856aed1d4e3350077fa2e4919d4d6c",
"size": 71660159
+ },
+ "Linux-x86_64": {
+ "file": "Ghost-Downloader-v4.5.11-Linux-x86_64.tar.xz",
+ "sha256": "55ea6a137fa66885229061853858086a0e195f2dcfe874e945eac3addbb82af8",
+ "size": 71800912
+ },
+ "Linux-arm64": {
+ "file": "Ghost-Downloader-v4.5.11-Linux-arm64.tar.xz",
+ "sha256": "214297ee95828d6d2589fc9468adfbfaa140de7fd91312cf4ca01cd8bf510760",
+ "size": 66224860
}
}
},