|
| 1 | +"""Download a new release and swap it in, then relaunch. |
| 2 | +
|
| 3 | +A running application cannot reliably delete itself, so the actual swap is done |
| 4 | +by a small helper script: Sortero launches it detached, quits, and the helper |
| 5 | +waits for the process to disappear before moving anything. |
| 6 | +
|
| 7 | +The old copy is kept aside until the new one is in place, and restored if the |
| 8 | +move fails - a failed update must never leave the user with no application. |
| 9 | +""" |
| 10 | +import os, re, shutil, subprocess, sys, tempfile, time, urllib.request, zipfile |
| 11 | + |
| 12 | +from . import net, paths |
| 13 | +from .version import __version__ |
| 14 | + |
| 15 | +ASSET_PATTERNS = { |
| 16 | + "darwin": re.compile(r"(?i)macos"), |
| 17 | + "win32": re.compile(r"(?i)windows"), |
| 18 | + "linux": re.compile(r"(?i)linux"), |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +class UpdateError(Exception): |
| 23 | + pass |
| 24 | + |
| 25 | + |
| 26 | +# ---------------------------------------------------------------- discovery |
| 27 | +def running_frozen(): |
| 28 | + return bool(getattr(sys, "frozen", False)) |
| 29 | + |
| 30 | + |
| 31 | +def installed_path(): |
| 32 | + """The thing that would be replaced: the .app bundle, or the program dir.""" |
| 33 | + if not running_frozen(): |
| 34 | + return None |
| 35 | + exe = os.path.realpath(sys.executable) |
| 36 | + if paths.IS_MAC: |
| 37 | + # .../Sortero.app/Contents/MacOS/Sortero |
| 38 | + parts = exe.split(os.sep) |
| 39 | + for i in range(len(parts) - 1, -1, -1): |
| 40 | + if parts[i].endswith(".app"): |
| 41 | + return os.sep.join(parts[:i + 1]) |
| 42 | + return None |
| 43 | + return os.path.dirname(exe) |
| 44 | + |
| 45 | + |
| 46 | +def pick_asset(assets): |
| 47 | + pat = ASSET_PATTERNS.get(sys.platform, ASSET_PATTERNS["linux"]) |
| 48 | + for a in assets: |
| 49 | + name = a.get("name", "") |
| 50 | + if name.endswith(".zip") and pat.search(name): |
| 51 | + return a |
| 52 | + raise UpdateError("That release has no build for this platform.") |
| 53 | + |
| 54 | + |
| 55 | +def writable(target): |
| 56 | + """Can we actually replace it? /Applications may be protected by macOS.""" |
| 57 | + parent = os.path.dirname(target) |
| 58 | + try: |
| 59 | + probe = os.path.join(parent, f".sortero-write-test-{os.getpid()}") |
| 60 | + with open(probe, "w") as fh: |
| 61 | + fh.write("x") |
| 62 | + os.remove(probe) |
| 63 | + return True |
| 64 | + except OSError: |
| 65 | + return False |
| 66 | + |
| 67 | + |
| 68 | +# ---------------------------------------------------------------- download |
| 69 | +def download(url, dest_dir, progress=None, timeout=120): |
| 70 | + os.makedirs(dest_dir, exist_ok=True) |
| 71 | + dest = os.path.join(dest_dir, "update.zip") |
| 72 | + req = urllib.request.Request(url, headers={ |
| 73 | + "User-Agent": f"Sortero/{__version__}", |
| 74 | + "Accept": "application/octet-stream"}) |
| 75 | + with net.urlopen(req, timeout=timeout) as r, open(dest, "wb") as fh: |
| 76 | + total = int(r.headers.get("Content-Length") or 0) |
| 77 | + got = 0 |
| 78 | + while True: |
| 79 | + chunk = r.read(65536) |
| 80 | + if not chunk: |
| 81 | + break |
| 82 | + fh.write(chunk) |
| 83 | + got += len(chunk) |
| 84 | + if progress and total: |
| 85 | + progress(got, total) |
| 86 | + if os.path.getsize(dest) < 1_000_000: |
| 87 | + raise UpdateError("The download looks truncated; not installing it.") |
| 88 | + return dest |
| 89 | + |
| 90 | + |
| 91 | +def extract(zip_path, into): |
| 92 | + os.makedirs(into, exist_ok=True) |
| 93 | + if paths.IS_MAC: |
| 94 | + # ditto preserves bundle structure and symlinks that zipfile mangles |
| 95 | + subprocess.run(["ditto", "-x", "-k", zip_path, into], check=True, |
| 96 | + capture_output=True) |
| 97 | + else: |
| 98 | + with zipfile.ZipFile(zip_path) as z: |
| 99 | + z.extractall(into) |
| 100 | + |
| 101 | + for dirpath, dirnames, filenames in os.walk(into): |
| 102 | + if paths.IS_MAC: |
| 103 | + for d in dirnames: |
| 104 | + if d == "Sortero.app": |
| 105 | + return os.path.join(dirpath, d) |
| 106 | + else: |
| 107 | + for f in filenames: |
| 108 | + if f in ("Sortero", "Sortero.exe"): |
| 109 | + return dirpath |
| 110 | + raise UpdateError("Couldn't find Sortero inside the downloaded archive.") |
| 111 | + |
| 112 | + |
| 113 | +# ------------------------------------------------------------------- swap |
| 114 | +MAC_SCRIPT = r"""#!/bin/bash |
| 115 | +# Sortero self-update helper. Waits for the app to quit, swaps it, relaunches. |
| 116 | +set -u |
| 117 | +APP="$1"; NEW="$2"; PID="$3"; LOG="$4" |
| 118 | +exec >>"$LOG" 2>&1 |
| 119 | +echo "waiting for pid $PID" |
| 120 | +for _ in $(seq 1 200); do kill -0 "$PID" 2>/dev/null || break; sleep 0.3; done |
| 121 | +sleep 0.5 |
| 122 | +OLD="${APP}.old-$$" |
| 123 | +if ! mv "$APP" "$OLD"; then echo "could not move old app"; open "$APP"; exit 1; fi |
| 124 | +if ! mv "$NEW" "$APP"; then |
| 125 | + echo "install failed - restoring previous version" |
| 126 | + mv "$OLD" "$APP"; open "$APP"; exit 1 |
| 127 | +fi |
| 128 | +xattr -dr com.apple.quarantine "$APP" 2>/dev/null |
| 129 | +codesign --force --sign - "$APP" 2>/dev/null |
| 130 | +rm -rf "$OLD" |
| 131 | +echo "installed; relaunching" |
| 132 | +open "$APP" |
| 133 | +""" |
| 134 | + |
| 135 | +WIN_SCRIPT = r"""@echo off |
| 136 | +rem Sortero self-update helper. |
| 137 | +setlocal |
| 138 | +set APP=%~1 |
| 139 | +set NEW=%~2 |
| 140 | +set PID=%~3 |
| 141 | +:wait |
| 142 | +tasklist /FI "PID eq %PID%" | find "%PID%" >nul |
| 143 | +if not errorlevel 1 ( |
| 144 | + timeout /t 1 /nobreak >nul |
| 145 | + goto wait |
| 146 | +) |
| 147 | +timeout /t 1 /nobreak >nul |
| 148 | +move "%APP%" "%APP%.old" >nul 2>&1 |
| 149 | +move "%NEW%" "%APP%" >nul 2>&1 |
| 150 | +if errorlevel 1 ( |
| 151 | + move "%APP%.old" "%APP%" >nul 2>&1 |
| 152 | +) else ( |
| 153 | + rmdir /s /q "%APP%.old" >nul 2>&1 |
| 154 | +) |
| 155 | +start "" "%APP%\Sortero.exe" |
| 156 | +""" |
| 157 | + |
| 158 | +LINUX_SCRIPT = r"""#!/bin/bash |
| 159 | +set -u |
| 160 | +APP="$1"; NEW="$2"; PID="$3"; LOG="$4" |
| 161 | +exec >>"$LOG" 2>&1 |
| 162 | +for _ in $(seq 1 200); do kill -0 "$PID" 2>/dev/null || break; sleep 0.3; done |
| 163 | +sleep 0.5 |
| 164 | +OLD="${APP}.old-$$" |
| 165 | +if ! mv "$APP" "$OLD"; then exit 1; fi |
| 166 | +if ! mv "$NEW" "$APP"; then mv "$OLD" "$APP"; "$APP/Sortero" & exit 1; fi |
| 167 | +rm -rf "$OLD" |
| 168 | +"$APP/Sortero" & |
| 169 | +""" |
| 170 | + |
| 171 | + |
| 172 | +def log_path(): |
| 173 | + return os.path.join(paths.data_dir(), "update.log") |
| 174 | + |
| 175 | + |
| 176 | +def install(new_path, target=None): |
| 177 | + """Hand off to the helper and return. The caller must quit immediately.""" |
| 178 | + target = target or installed_path() |
| 179 | + if not target: |
| 180 | + raise UpdateError("Sortero is running from source, so it can't replace " |
| 181 | + "itself. Pull the latest code instead.") |
| 182 | + if not writable(target): |
| 183 | + raise UpdateError( |
| 184 | + f"Can't write to {os.path.dirname(target)}.\n\n" |
| 185 | + "macOS asks permission before one app may modify another in " |
| 186 | + "/Applications. Grant Sortero access under System Settings → " |
| 187 | + "Privacy & Security → App Management, or move Sortero somewhere " |
| 188 | + "like your home folder and try again.") |
| 189 | + |
| 190 | + tmp = tempfile.mkdtemp(prefix="sortero-update-") |
| 191 | + if paths.IS_WIN: |
| 192 | + script = os.path.join(tmp, "swap.bat") |
| 193 | + body, args = WIN_SCRIPT, ["cmd", "/c", script, target, new_path, str(os.getpid())] |
| 194 | + else: |
| 195 | + script = os.path.join(tmp, "swap.sh") |
| 196 | + body = MAC_SCRIPT if paths.IS_MAC else LINUX_SCRIPT |
| 197 | + args = ["/bin/bash", script, target, new_path, str(os.getpid()), log_path()] |
| 198 | + with open(script, "w") as fh: |
| 199 | + fh.write(body) |
| 200 | + os.chmod(script, 0o755) |
| 201 | + |
| 202 | + subprocess.Popen(args, start_new_session=True, |
| 203 | + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 204 | + return script |
| 205 | + |
| 206 | + |
| 207 | +def prepare(asset, progress=None): |
| 208 | + """Download and unpack; returns the path to the new application.""" |
| 209 | + tmp = tempfile.mkdtemp(prefix="sortero-dl-") |
| 210 | + zip_path = download(asset["browser_download_url"], tmp, progress=progress) |
| 211 | + return extract(zip_path, os.path.join(tmp, "unpacked")) |
0 commit comments