diff --git a/CHANGELOG.md b/CHANGELOG.md index b493fd1..659fb2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,12 @@ All notable changes to MapHide are documented here. or shut down while MapHide was running. - Added an installer, which adds MapHide to the Start menu and to Installed apps in Windows. Uninstalling asks whether to keep your settings. +- Added a Check for updates button under About in Settings. When a new + version is out, Update installs it and reopens MapHide with your settings + kept. +- Added a Check for updates switch under Behavior in Settings, on by default, + which looks for a new version when MapHide opens. The field log says when + one is out. ## v0.2.6 - 2026-10-27 diff --git a/README.md b/README.md index 43a1ce8..4daca66 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ This is normal behavior. MapHide hides to the system tray instead of fully closi ## Version -The latest release and its download are on the [Releases page](https://github.com/ColorDumper/MapHide/releases/latest). To update, run the newer setup file; your settings are kept. To remove MapHide, use **Settings > Apps > Installed apps** in Windows, where you can choose whether to keep your settings. What changed in each version is in the [changelog](CHANGELOG.md). +The latest release and its download are on the [Releases page](https://github.com/ColorDumper/MapHide/releases/latest). MapHide checks for a new version each time it opens (you can turn this off under `BEHAVIOR` in `SETTINGS`). When one is out, click `UPDATE` under `ABOUT`: MapHide closes, updates and opens again, and your settings are kept. You can also run the newer setup file yourself. To remove MapHide, use **Settings > Apps > Installed apps** in Windows, where you can choose whether to keep your settings. What changed in each version is in the [changelog](CHANGELOG.md). ## Credits diff --git a/config.example.json b/config.example.json index 468f1ff..586ff9e 100644 --- a/config.example.json +++ b/config.example.json @@ -10,5 +10,6 @@ "hide_hotkey": "H", "hide_delay_ms": 120, "log_enabled": false, - "theme": "field" + "theme": "field", + "check_updates": true } diff --git a/installer/MapHide.iss b/installer/MapHide.iss index 8c38a97..fd45d7b 100644 --- a/installer/MapHide.iss +++ b/installer/MapHide.iss @@ -75,6 +75,8 @@ Name: "{autodesktop}\MapHide"; Filename: "{app}\MapHide.exe"; AppUserModelID: "{ [Run] Filename: "{app}\MapHide.exe"; Description: "{cm:LaunchProgram,MapHide}"; Flags: nowait postinstall skipifsilent +; MapHide's own updater runs this setup with /RELAUNCH=1 to open it again after. +Filename: "{app}\MapHide.exe"; Flags: nowait; Check: RelaunchRequested [UninstallDelete] Type: filesandordirs; Name: "{app}\_internal" @@ -83,6 +85,11 @@ Type: filesandordirs; Name: "{app}\_internal" var RemoveSettings: Boolean; +function RelaunchRequested(): Boolean; +begin + Result := ExpandConstant('{param:RELAUNCH|0}') = '1'; +end; + // Close a running MapHide the same way Exit in the tray does, so the overlay // is hidden in OBS before its files are replaced or removed. procedure QuitMapHide(const ExePath: String); diff --git a/maphide/config.py b/maphide/config.py index 2dee8cf..c198d69 100644 --- a/maphide/config.py +++ b/maphide/config.py @@ -25,7 +25,7 @@ MAX_PORT = 65535 # Settings only the window uses. Changing these never needs the worker # restarted, so saving them leaves the OBS connection and the overlay alone. -WINDOW_ONLY_FIELDS = frozenset({"auto_connect", "theme"}) +WINDOW_ONLY_FIELDS = frozenset({"auto_connect", "theme", "check_updates"}) def clamp(value, low, high): @@ -58,6 +58,7 @@ class AppConfig: hide_delay_ms: int = DEFAULT_HIDE_DELAY_MS log_enabled: bool = False theme: str = DEFAULT_THEME + check_updates: bool = True @classmethod def from_dict(cls, data): @@ -95,6 +96,7 @@ def from_dict(cls, data): ), log_enabled=_flag(data, "log_enabled", False), theme=theme_name(data.get("theme") or DEFAULT_THEME), + check_updates=_flag(data, "check_updates", True), ) def to_dict(self): @@ -111,6 +113,7 @@ def to_dict(self): "hide_delay_ms": self.hide_delay_ms, "log_enabled": self.log_enabled, "theme": self.theme, + "check_updates": self.check_updates, } def to_loggable_dict(self): @@ -196,6 +199,7 @@ def config_from_form( auto_reconnect, log_enabled, theme=DEFAULT_THEME, + check_updates=True, ): """Build an AppConfig from what a settings form holds, as typed. @@ -227,6 +231,7 @@ def config_from_form( hide_delay_ms=clamp_hide_delay(hide_delay_ms), log_enabled=bool(log_enabled), theme=theme_name(theme), + check_updates=bool(check_updates), ) diff --git a/maphide/controller.py b/maphide/controller.py index ca1207e..c295be1 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -38,6 +38,8 @@ # EVENT_* codes. HISTORY_SETTINGS_SAVED = "settings_saved" HISTORY_DEFAULTS_RESTORED = "defaults_restored" +# A newer MapHide is out; `subject` is its version. +HISTORY_UPDATE_AVAILABLE = "update_available" # A message the window itself puts in the history, such as a setting it # can't use. HISTORY_NOTICE = "notice" diff --git a/maphide/fieldlog.py b/maphide/fieldlog.py index c729e17..e162b17 100644 --- a/maphide/fieldlog.py +++ b/maphide/fieldlog.py @@ -8,7 +8,12 @@ from dataclasses import dataclass -from .controller import HISTORY_DEFAULTS_RESTORED, HISTORY_NOTICE, HISTORY_SETTINGS_SAVED +from .controller import ( + HISTORY_DEFAULTS_RESTORED, + HISTORY_NOTICE, + HISTORY_SETTINGS_SAVED, + HISTORY_UPDATE_AVAILABLE, +) from .obs import OBS_BAD_PASSWORD, OBS_LINK_LOST, OBS_OVERLAY_MAY_REMAIN, OBS_UNREACHABLE from .overlay import ( EVENT_CONNECT_FAILED, @@ -91,6 +96,8 @@ def _wording(entry): return "> settings saved", PLAIN if code == HISTORY_DEFAULTS_RESTORED: return "> defaults restored", PLAIN + if code == HISTORY_UPDATE_AVAILABLE and entry.subject: + return f"> update available · v{entry.subject} · see settings", LINKED if code == HISTORY_NOTICE: return f"> {entry.message}", WARNING return f"> {entry.message}", PLAIN diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index b300181..24ec91e 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -622,10 +622,14 @@ Window { id: drawer width: 436 height: parent.height - x: win.drawerOpen ? parent.width - width : parent.width - visible: x < parent.width + // How far open, from 0 (hidden) to 1. The slide animates this, + // not x, so the window growing to its size as it first opens + // doesn't slide the drawer across it. + property real openness: win.drawerOpen ? 1 : 0 + x: parent.width - width * openness + visible: openness > 0 color: win.t.bg - Behavior on x { NumberAnimation { duration: 340; easing.type: Easing.Bezier; easing.bezierCurve: [0.2, 0.9, 0.25, 1, 1, 1] } } + Behavior on openness { NumberAnimation { duration: 340; easing.type: Easing.Bezier; easing.bezierCurve: [0.2, 0.9, 0.25, 1, 1, 1] } } Rectangle { width: 1; height: parent.height; color: win.t.border2 } MouseArea { anchors.fill: parent } diff --git a/maphide/qt/Settings.qml b/maphide/qt/Settings.qml index 12b32dd..18df944 100644 --- a/maphide/qt/Settings.qml +++ b/maphide/qt/Settings.qml @@ -1,7 +1,7 @@ import QtQuick import QtQuick.Shapes -// The settings drawer's contents: seven numbered sections, then Reset and +// The settings drawer's contents: numbered sections, then Reset and // Save. Edits stay in the form, unapplied, until Save. Item { id: settings @@ -425,6 +425,15 @@ Item { checked: settings.f.log_enabled onToggled: (on) => backend.setField("log_enabled", on) } + Switch { + width: parent.width + visible: backend.updatesShown + divider: true + label: "Check for updates" + description: "Look for a new version when MapHide opens" + checked: settings.f.check_updates + onToggled: (on) => backend.setField("check_updates", on) + } } } } @@ -488,42 +497,140 @@ Item { // 07 ABOUT Column { + id: about width: parent.width spacing: 8 + readonly property string phase: backend.updateState + readonly property bool found: backend.updateVersion !== "" + // What the button does now: "check", "install", "page", or "" + // while busy. + readonly property string action: !backend.updatesShown ? "" + : phase === "checking" || phase === "downloading" || phase === "installing" ? "" + : found && (phase === "available" || phase === "failed") + ? (backend.canInstallUpdate ? "install" : "page") + : "check" + readonly property string status: ({ + checking: "Checking GitHub for a newer version…", + latest: "You're on the latest version", + available: backend.canInstallUpdate + ? "v" + backend.updateVersion + " is out. MapHide reopens after updating; settings stay." + : "v" + backend.updateVersion + " is out on GitHub.", + downloading: "Downloading v" + backend.updateVersion + "… " + backend.updatePercent + "%", + installing: "Installing. MapHide will open again.", + failed: backend.updateMessage + })[phase] || "" + // "You're on the latest version" shows for a moment, then the + // row goes back to normal. + Timer { + interval: 4000 + running: about.phase === "latest" + onTriggered: backend.clearUpdateResult() + } SectionHeading { number: "07"; title: "ABOUT" } Rectangle { width: parent.width - height: 54 + height: Math.max(54, aboutText.height + 20) color: settings.t.panel border.color: settings.t.border - Row { + Image { + id: aboutLogo x: 12 + width: 28 + height: 28 + anchors.verticalCenter: parent.verticalCenter + source: backend.assets + "/MapHide_Icon_64.png" + mipmap: true + } + Column { + id: aboutText + anchors.left: aboutLogo.right + anchors.leftMargin: 12 + anchors.right: updateButton.visible ? updateButton.left : parent.right + anchors.rightMargin: 12 anchors.verticalCenter: parent.verticalCenter - spacing: 12 - Image { - width: 28 - height: 28 - anchors.verticalCenter: parent.verticalCenter - source: backend.assets + "/MapHide_Icon_64.png" - mipmap: true + spacing: 2 + Mono { text: "MapHide " + backend.version; font.pixelSize: 13 } + Label { + width: parent.width + visible: about.status !== "" + text: about.status + wrapMode: Text.Wrap + font.pixelSize: 12 + color: about.phase === "failed" ? settings.t.warn + : about.phase === "latest" ? settings.t.ok + : about.phase === "available" ? settings.t.accent_text + : settings.t.muted } - Column { - anchors.verticalCenter: parent.verticalCenter - spacing: 2 - Mono { text: "MapHide " + backend.version; font.pixelSize: 13 } - Label { - text: "github.com/ColorDumper/MapHide" - font.pixelSize: 12 - font.underline: aboutLink.containsMouse - color: settings.t.accent_text - MouseArea { - id: aboutLink - anchors.fill: parent - hoverEnabled: true - cursorShape: Qt.PointingHandCursor - onClicked: Qt.openUrlExternally("https://github.com/ColorDumper/MapHide") + Label { + text: "github.com/ColorDumper/MapHide" + font.pixelSize: 12 + font.underline: aboutLink.containsMouse + color: settings.t.accent_text + MouseArea { + id: aboutLink + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: Qt.openUrlExternally("https://github.com/ColorDumper/MapHide") + } + } + } + PressButton { + id: updateButton + objectName: "updateButton" + visible: backend.updatesShown + anchors.right: parent.right + anchors.rightMargin: 12 + anchors.verticalCenter: parent.verticalCenter + width: Math.max(118, updateButtonRow.width + 24) + height: 36 + enabled: about.action !== "" + fill: about.action === "install" ? settings.t.accent : settings.t.panel2 + edge: about.action === "install" ? settings.t.accent_deep : settings.t.border2 + onClicked: { + if (about.action === "install") + backend.installUpdate() + else if (about.action === "page") + Qt.openUrlExternally(backend.releasesPage) + else if (about.action === "check") + backend.checkForUpdates() + } + Row { + id: updateButtonRow + anchors.centerIn: parent + spacing: 6 + Spinner { + anchors.verticalCenter: parent.verticalCenter + visible: about.action === "" && backend.updatesShown + } + // A tick once MapHide is up to date. + Shape { + anchors.verticalCenter: parent.verticalCenter + visible: about.phase === "latest" + width: 13 + height: 13 + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeColor: settings.t.ok + strokeWidth: 2 + fillColor: "transparent" + capStyle: ShapePath.RoundCap + joinStyle: ShapePath.RoundJoin + PathSvg { path: "M11 3.5 L5 10 L2 7" } } } + Condensed { + font.pixelSize: 14 + font.letterSpacing: 14 * 0.08 + color: about.action === "install" ? settings.t.on_accent : settings.t.text + text: about.action === "install" + ? (about.phase === "failed" ? "TRY AGAIN" : "UPDATE") + : about.action === "page" ? "GET IT" + : about.phase === "checking" ? "CHECKING" + : about.action === "" ? "UPDATING" + : about.phase === "latest" ? "UP TO DATE" + : "CHECK FOR UPDATES" + } } } } diff --git a/maphide/qt/app.py b/maphide/qt/app.py index d224df9..7c384f2 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -26,13 +26,14 @@ from shiboken6 import isValid from ..config import config_from_form -from ..controller import HISTORY_NOTICE, AppController +from ..controller import HISTORY_NOTICE, HISTORY_UPDATE_AVAILABLE, AppController from ..fieldlog import field_line from ..logs import plain_reason from ..overlay import human_ts from ..paths import APP_DIR, APP_NAME, APP_USER_MODEL_ID, ICON_ICO_PATH from ..single_instance import COMMAND_QUIT, COMMAND_SHOW, command_pipe_name from ..themes import THEMES, theme_name +from ..updates import RELEASES_PAGE, Updater, checks_for_updates from ..version import APP_VERSION from ..winutil import apply_dark_title_bar, set_app_id from .view import ( @@ -51,6 +52,8 @@ # scene, and whether the map is covered. POLL_INTERVAL_MS = 100 AUTO_CONNECT_DELAY_MS = 250 +# The startup update check waits a little, so it never slows MapHide opening. +UPDATE_CHECK_DELAY_MS = 3000 CONFIG_NOT_LOADED = "Settings couldn't be read, so the defaults are in use." NO_TRAY = "No notification area, so closing the window will exit MapHide." # How long to wait, when Windows is signing out or shutting down, for the @@ -101,11 +104,21 @@ class Backend(QObject): saved = Signal() # A reason to show in the drawer's footer. saveFailed = Signal(str) - - def __init__(self, quit_app=None, schedule=_schedule, **controller_options): - """`controller_options` go to the AppController - a test passes a - stand-in service, save or connection check there.""" + # The update check in Settings. + updateChanged = Signal() + + def __init__( + self, + quit_app=None, + schedule=_schedule, + updater_options=None, + update_checks=None, + **controller_options, + ): + """`controller_options` go to the AppController, `updater_options` + to the Updater - a test passes stand-ins there.""" super().__init__() + self._schedule = schedule self.controller = AppController( schedule=schedule, notify=self.notice, on_change=self.refresh, **controller_options ) @@ -125,6 +138,10 @@ def __init__(self, quit_app=None, schedule=_schedule, **controller_options): self._tested_source = None self._tested_count = None self._settings = self._settings_view() + # Whether this copy looks for updates at all; a Store copy doesn't. + self._update_checks = checks_for_updates() if update_checks is None else update_checks + self.updater = Updater(schedule, on_change=self.refresh, **(updater_options or {})) + self._update = self._update_view() self._poll_timer = QTimer(self, interval=POLL_INTERVAL_MS) self._poll_timer.timeout.connect(self._poll) @@ -139,6 +156,8 @@ def load(self, **load_options): self._poll_timer.start() if cfg.auto_connect: QTimer.singleShot(AUTO_CONNECT_DELAY_MS, self._start) + if cfg.check_updates and self._update_checks: + self._schedule(UPDATE_CHECK_DELAY_MS, self._check_quietly) # Keeping the window current. @@ -159,6 +178,10 @@ def refresh(self): if settings != self._settings: self._settings = settings self.settingsChanged.emit() + update = self._update_view() + if update != self._update: + self._update = update + self.updateChanged.emit() def _source_count(self): """How many scenes carry the source named in the form, if known: @@ -172,6 +195,12 @@ def _source_count(self): return self._tested_count return None + def _update_view(self): + updater = self.updater + version = updater.release.version if updater.release else "" + # Whole percent, so the window redraws only when the number moves. + return (updater.state, updater.message, version, round(updater.progress * 100)) + def _settings_view(self): text, warning = source_line(self._source_count()) return (text, warning, self._test_state, self._test_message) @@ -395,6 +424,65 @@ def resetDefaults(self): self._set_form(cfg) self.saved.emit() + # Updates. + + @Property(bool, constant=True) + def updatesShown(self): + return self._update_checks + + @Property(bool, constant=True) + def canInstallUpdate(self): + return self.updater.can_install + + @Property(str, constant=True) + def releasesPage(self): + return RELEASES_PAGE + + @Property(str, notify=updateChanged) + def updateState(self): + return self._update[0] + + @Property(str, notify=updateChanged) + def updateMessage(self): + return self._update[1] + + @Property(str, notify=updateChanged) + def updateVersion(self): + return self._update[2] + + @Property(int, notify=updateChanged) + def updatePercent(self): + return self._update[3] + + def _check_quietly(self): + """The check when MapHide opens: a new version is noted in the field + log, and a failure (no internet, say) says nothing.""" + self.updater.check(on_found=self._update_found, quiet=True) + + def _update_found(self, release): + self.controller.add_history( + human_ts(), + f"MapHide {release.version} is available.", + HISTORY_UPDATE_AVAILABLE, + release.version, + ) + self.refresh() + + @Slot() + def checkForUpdates(self): + if self._update_checks: + self.updater.check() + + @Slot() + def clearUpdateResult(self): + self.updater.clear_latest() + + @Slot() + def installUpdate(self): + """Download the new version and hand over to its installer, which + closes MapHide, updates it and opens it again.""" + self.updater.install(on_started=self.exitApp) + def load_fonts(): for font in sorted(FONTS_DIR.glob("*.ttf")): diff --git a/maphide/qt/view.py b/maphide/qt/view.py index 1919cff..2f79c91 100644 --- a/maphide/qt/view.py +++ b/maphide/qt/view.py @@ -122,6 +122,7 @@ def new_entries(history, last_shown): "auto_reconnect", "log_enabled", "theme", + "check_updates", ) diff --git a/maphide/updates.py b/maphide/updates.py new file mode 100644 index 0000000..eaa6d82 --- /dev/null +++ b/maphide/updates.py @@ -0,0 +1,317 @@ +"""Checking GitHub for a newer MapHide, and installing it. + +Only the GitHub download updates itself this way. A Store copy is updated by +the Store. A copy unzipped by hand has no installer to update it with, so it +points to the download page instead. + +Nothing here touches a widget. Network work runs on its own thread, and +results come back through the `schedule` callable, as in the controller. +""" + +import hashlib +import json +import re +import subprocess +import sys +import tempfile +import threading +import urllib.error +import urllib.request +from dataclasses import dataclass +from pathlib import Path + +from .version import CHANNEL, CHANNEL_GITHUB, CHANNEL_SOURCE, VERSION + +REPO = "ColorDumper/MapHide" +LATEST_RELEASE_API = f"https://api.github.com/repos/{REPO}/releases/latest" +RELEASES_PAGE = f"https://github.com/{REPO}/releases/latest" +# Setup files are only ever downloaded from this repository's own releases. +DOWNLOAD_PREFIX = f"https://github.com/{REPO}/releases/download/" +SETUP_NAME = re.compile(r"MapHide-v(\d+\.\d+\.\d+)-setup\.exe") +TIMEOUT_SECONDS = 20 +CHUNK_BYTES = 64 * 1024 +POLL_INTERVAL_MS = 100 +# Runs the installer showing only its progress, then reopens MapHide. +INSTALLER_ARGUMENTS = ("/SILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/RELAUNCH=1") +UNINSTALLER_NAME = "unins000.exe" + +NO_CONNECTION = "Couldn't reach GitHub. Check your internet connection." +GITHUB_UNAVAILABLE = "GitHub couldn't be checked right now. Try again later." +UNEXPECTED_REPLY = "GitHub sent a reply MapHide couldn't read. Try again later." +DOWNLOAD_FAILED = "The download didn't finish. Try again." +DOWNLOAD_DAMAGED = "The download was damaged. Try again." +INSTALLER_DIDNT_START = "The installer couldn't start." +CHECK_FAILED = "Couldn't check for updates." + +# Updater states. +IDLE = "idle" +CHECKING = "checking" +LATEST = "latest" +AVAILABLE = "available" +DOWNLOADING = "downloading" +INSTALLING = "installing" +FAILED = "failed" + + +class UpdateError(Exception): + """Something went wrong, with a message fit to show the user.""" + + +@dataclass(frozen=True) +class Release: + version: str + # The setup file, when this release has one MapHide can install. + setup_url: str | None = None + setup_size: int = 0 + setup_sha256: str | None = None + + +def parse_version(text): + """ "v1.2.3" or "1.2.3" as (1, 2, 3); None for anything else.""" + match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)", str(text).strip()) + return tuple(int(part) for part in match.groups()) if match else None + + +def is_newer(candidate, current=VERSION): + new, old = parse_version(candidate), parse_version(current) + return new is not None and old is not None and new > old + + +def release_from_json(data): + """A Release from GitHub's description of the latest release. Raises + UpdateError if it isn't one MapHide understands.""" + if not isinstance(data, dict): + raise UpdateError(UNEXPECTED_REPLY) + version = parse_version(data.get("tag_name", "")) + if version is None: + raise UpdateError(UNEXPECTED_REPLY) + version = ".".join(map(str, version)) + for asset in data.get("assets") or (): + if not isinstance(asset, dict): + continue + match = SETUP_NAME.fullmatch(str(asset.get("name", ""))) + url = str(asset.get("browser_download_url", "")) + digest = str(asset.get("digest") or "") + if not match or match.group(1) != version or not url.startswith(DOWNLOAD_PREFIX): + continue + # Without a checksum to compare against, MapHide won't run the file. + if not re.fullmatch(r"sha256:[0-9a-f]{64}", digest): + continue + return Release(version, url, int(asset.get("size") or 0), digest.split(":", 1)[1]) + return Release(version) + + +def _request(url): + # Only ever https: the release API above, or a download checked against + # DOWNLOAD_PREFIX. + if not url.startswith("https://"): + raise UpdateError(DOWNLOAD_FAILED) + return urllib.request.Request( # noqa: S310 - https only, checked above + url, + headers={"User-Agent": f"MapHide/{VERSION}", "Accept": "application/vnd.github+json"}, + ) + + +def fetch_latest(opener=urllib.request.urlopen): + """The latest release on GitHub. Raises UpdateError.""" + try: + with opener(_request(LATEST_RELEASE_API), timeout=TIMEOUT_SECONDS) as reply: + data = json.load(reply) + except urllib.error.HTTPError as exc: + # GitHub answered, but not with a release: none published yet, or + # too many checks from this network in the last hour. + raise UpdateError(GITHUB_UNAVAILABLE) from exc + except (urllib.error.URLError, TimeoutError, ConnectionError) as exc: + raise UpdateError(NO_CONNECTION) from exc + except (ValueError, OSError) as exc: + raise UpdateError(UNEXPECTED_REPLY) from exc + return release_from_json(data) + + +def download_setup(release, folder, progress=None, opener=urllib.request.urlopen): + """Download `release`'s setup file into `folder` and check it against + GitHub's checksum. `progress(fraction)` is called as it arrives. + Returns the file's path. Raises UpdateError.""" + if release.setup_url is None or not release.setup_url.startswith(DOWNLOAD_PREFIX): + raise UpdateError(DOWNLOAD_FAILED) + folder = Path(folder) + target = folder / f"MapHide-v{release.version}-setup.exe" + partial = target.with_suffix(".part") + digest = hashlib.sha256() + received = 0 + try: + folder.mkdir(parents=True, exist_ok=True) + with opener(_request(release.setup_url), timeout=TIMEOUT_SECONDS) as reply: + with open(partial, "wb") as file: + while chunk := reply.read(CHUNK_BYTES): + file.write(chunk) + digest.update(chunk) + received += len(chunk) + if progress is not None and release.setup_size: + progress(min(received / release.setup_size, 1.0)) + if digest.hexdigest() != release.setup_sha256: + partial.unlink(missing_ok=True) + raise UpdateError(DOWNLOAD_DAMAGED) + partial.replace(target) + except UpdateError: + raise + except (urllib.error.URLError, TimeoutError, OSError) as exc: + partial.unlink(missing_ok=True) + raise UpdateError(DOWNLOAD_FAILED) from exc + return target + + +def launch_installer(path, popen=subprocess.Popen): + """Start the setup file, which closes MapHide, installs over it and + reopens it. Raises UpdateError if it can't start.""" + try: + popen([str(path), *INSTALLER_ARGUMENTS], close_fds=True) + except OSError as exc: + raise UpdateError(INSTALLER_DIDNT_START) from exc + + +def checks_for_updates(channel=CHANNEL): + """Whether this copy looks for updates on GitHub at all: the GitHub + download does, and so does a copy run from source.""" + return channel in (CHANNEL_GITHUB, CHANNEL_SOURCE) + + +def installed_by_setup(channel=CHANNEL, frozen=None, exe_dir=None): + """Whether this copy was installed by MapHide's setup file, and so can + install an update itself.""" + frozen = getattr(sys, "frozen", False) if frozen is None else frozen + exe_dir = Path(sys.executable).parent if exe_dir is None else Path(exe_dir) + return channel == CHANNEL_GITHUB and bool(frozen) and (exe_dir / UNINSTALLER_NAME).exists() + + +def download_folder(): + return Path(tempfile.gettempdir()) / "MapHide-update" + + +class Updater: + """Checks for a new version and installs it, one step at a time. + + `schedule(milliseconds, callback)` runs `callback` later on the window's + thread. `on_change()` asks the window to redraw. + """ + + def __init__( + self, + schedule, + on_change=lambda: None, + current=VERSION, + fetch=fetch_latest, + download=download_setup, + launch=launch_installer, + can_install=None, + folder=None, + ): + self._schedule = schedule + self._on_change = on_change + self._current = current + self._fetch = fetch + self._download = download + self._launch = launch + self.can_install = installed_by_setup() if can_install is None else can_install + self._folder = download_folder() if folder is None else folder + self.state = IDLE + self.message = "" + self.release = None + self.progress = 0.0 + self.thread = None + + @property + def busy(self): + return self.state in (CHECKING, DOWNLOADING, INSTALLING) + + def _set(self, state, message=""): + self.state = state + self.message = message + self._on_change() + + def _run(self, work, on_done): + """Run `work()` off the window's thread, then `on_done(result, + error)` back on it.""" + outcome = [] + + def run(): + try: + outcome.append((work(), None)) + except UpdateError as exc: + outcome.append((None, str(exc))) + except Exception: + # A bug here must still end the wait in the window. + outcome.append((None, CHECK_FAILED)) + + def wait(): + if not outcome: + self._on_change() + self._schedule(POLL_INTERVAL_MS, wait) + return + self.thread = None + on_done(*outcome[0]) + + self.thread = threading.Thread(target=run, name="Updater", daemon=True) + self.thread.start() + self._schedule(POLL_INTERVAL_MS, wait) + + def check(self, on_found=None, quiet=False): + """Ask GitHub for the latest version. `on_found(release)` runs if it + is newer than this one. A quiet check, as at startup, goes back to + idle instead of showing that it failed. Returns False while busy.""" + if self.busy: + return False + + def done(release, error): + if error is not None: + self._set(IDLE if quiet else FAILED, "" if quiet else error) + elif is_newer(release.version, self._current): + self.release = release + self._set(AVAILABLE) + if on_found is not None: + on_found(release) + else: + # Only a check someone asked for says MapHide is up to date. + self._set(IDLE if quiet else LATEST) + + self._set(CHECKING) + self._run(self._fetch, done) + return True + + def clear_latest(self): + """Stop saying MapHide is up to date, a few seconds after a check.""" + if self.state == LATEST: + self._set(IDLE) + + def install(self, on_started): + """Download the new version and start its installer, then call + `on_started()`, which should close MapHide. Returns False if there + is nothing to install or this copy can't install it.""" + release = self.release + if ( + self.busy + or self.state not in (AVAILABLE, FAILED) + or release is None + or release.setup_url is None + or not self.can_install + ): + return False + + def report(fraction): + self.progress = fraction + + def work(): + path = self._download(release, self._folder, report) + self._launch(path) + + def done(_result, error): + if error is not None: + self._set(FAILED, error) + return + self._set(INSTALLING) + on_started() + + self.progress = 0.0 + self._set(DOWNLOADING) + self._run(work, done) + return True diff --git a/tests/test_config.py b/tests/test_config.py index 68bfad9..c4e739c 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -262,11 +262,25 @@ def test_a_form_without_a_theme_picker_keeps_the_default_theme(): assert config_from_form(**FORM, theme="Legacy").theme == "legacy" +# --- the update check setting --- + + +def test_checking_for_updates_is_on_unless_turned_off(tmp_path): + assert AppConfig.from_dict(BASE).check_updates is True + assert config_from_form(**FORM).check_updates is True + + path = tmp_path / "config.json" + save_config(AppConfig.from_dict({**BASE, "check_updates": False}), path) + + assert load_config(path).check_updates is False + + @pytest.mark.parametrize( ("change", "differs"), [ ({"theme": "legacy"}, False), ({"auto_connect": True}, False), + ({"check_updates": False}, False), ({"hotkey": "M"}, True), ({"host": "10.0.0.9"}, True), ({"log_enabled": True}, True), diff --git a/tests/test_controller.py b/tests/test_controller.py index 42e32ff..4423435 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -494,8 +494,8 @@ def broken_check(*_args): @pytest.mark.parametrize( "change", - [{"theme": "legacy"}, {"auto_connect": True}, {}], - ids=["theme", "connect on startup", "nothing"], + [{"theme": "legacy"}, {"auto_connect": True}, {"check_updates": False}, {}], + ids=["theme", "connect on startup", "update check", "nothing"], ) def test_saving_a_change_the_worker_does_not_use_leaves_it_running(h, change): h.controller.start(make_config()) diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index 4eaeb5e..ac1e011 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -13,6 +13,7 @@ from maphide.overlay import CONNECTED, CONNECTING, ServiceStatus # noqa: E402 from maphide.qt.app import WM_ENDSESSION, Backend, ends_session # noqa: E402 from maphide.qt.view import QT_KEY_ESCAPE, SCREEN_CONNECTING, SOURCE_FOLLOWS # noqa: E402 +from maphide.updates import Release # noqa: E402 @pytest.fixture(autouse=True) @@ -43,9 +44,19 @@ def __init__(self): self.checks = [] self.check_result = ConnectionCheck(ok=True, source_scene_count=3) self.quits = 0 + self.latest = Release("0.2.0") + self.installers = [] self.backend = Backend( quit_app=self._quit, schedule=self.schedule, + update_checks=True, + updater_options={ + "current": "0.2.6", + "fetch": lambda: self.latest, + "download": lambda release, folder, progress: "setup.exe", + "launch": self.installers.append, + "can_install": True, + }, service=self.service, save=self.saved.append, check=self._check, @@ -70,6 +81,14 @@ def load(self, load): self.backend.load(load=load) self.backend._poll_timer.stop() + def run_updater(self): + """Run what's scheduled, letting the updater's thread finish each + time it has one running, until nothing is left.""" + while self.schedule.pending: + if self.backend.updater.thread is not None: + self.backend.updater.thread.join(timeout=5) + self.schedule.run_next() + def run_check(self): """Let the connection check's thread finish and its result land.""" self.backend.controller._check_thread.join(timeout=5) @@ -340,3 +359,64 @@ def test_only_a_real_session_end_counts(): # Windows sends it with wParam 0 when the sign-out was cancelled. assert not ends_session(WM_ENDSESSION, 0) assert not ends_session(0x0011, 1) # WM_QUERYENDSESSION only asks + + +# Updates. + +NEW_RELEASE = Release( + "0.3.0", "https://github.com/ColorDumper/MapHide/releases/download/x", 1, "0" * 64 +) + + +def test_opening_maphide_checks_for_updates_and_notes_a_new_one(h): + h.latest = NEW_RELEASE + h.load(lambda: make_config()) + + h.run_updater() + + assert h.backend.updateState == "available" + assert h.backend.updateVersion == "0.3.0" + assert h.lines[-1][1] == "> update available · v0.3.0 · see settings" + + +def test_no_check_at_startup_when_it_is_turned_off(h): + h.latest = NEW_RELEASE + h.load(lambda: make_config(check_updates=False)) + + while h.schedule.pending: + h.schedule.run_next() + + assert h.backend.updateState == "idle" + + +def test_a_store_copy_never_checks(): + harness = Harness() + harness.backend._update_checks = False + harness.load(lambda: make_config()) + + while harness.schedule.pending: + harness.schedule.run_next() + harness.backend.checkForUpdates() + + assert harness.backend.updateState == "idle" + + +def test_check_now_says_when_maphide_is_up_to_date(h): + h.backend.checkForUpdates() + h.run_updater() + + assert h.backend.updateState == "latest" + + +def test_update_runs_the_installer_and_closes_maphide(h): + h.latest = NEW_RELEASE + h.backend.checkForUpdates() + h.run_updater() + + h.backend.installUpdate() + h.run_updater() + + assert h.installers == ["setup.exe"] + assert h.backend.updateState == "installing" + assert h.hides == [True] + assert h.quits == 1 diff --git a/tests/test_updates.py b/tests/test_updates.py new file mode 100644 index 0000000..8bb318f --- /dev/null +++ b/tests/test_updates.py @@ -0,0 +1,406 @@ +"""Checking for and installing a newer MapHide, without the internet.""" + +import hashlib +import io +import json +import urllib.error + +import pytest +from test_controller import ManualScheduler + +from maphide import updates +from maphide.updates import ( + AVAILABLE, + CHECKING, + DOWNLOADING, + FAILED, + IDLE, + INSTALLING, + LATEST, + Release, + UpdateError, + Updater, + download_setup, + fetch_latest, + installed_by_setup, + is_newer, + launch_installer, + release_from_json, +) + +SETUP_BYTES = b"pretend installer" * 1000 +SETUP_SHA = hashlib.sha256(SETUP_BYTES).hexdigest() +SETUP_URL = ( + "https://github.com/ColorDumper/MapHide/releases/download/v0.3.0/MapHide-v0.3.0-setup.exe" +) + + +def release_json(tag="v0.3.0", **asset): + version = tag.lstrip("v") + return { + "tag_name": tag, + "assets": [ + {"name": f"MapHide-{tag}-win64.zip", "browser_download_url": "https://x/zip"}, + { + "name": f"MapHide-v{version}-setup.exe", + "browser_download_url": SETUP_URL.replace("0.3.0", version), + "size": len(SETUP_BYTES), + "digest": f"sha256:{SETUP_SHA}", + **asset, + }, + ], + } + + +class Reply(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + +def opener_returning(body): + requests = [] + + def opener(request, timeout): + requests.append(request) + return Reply(body) + + opener.requests = requests + return opener + + +def opener_raising(exc): + def opener(request, timeout): + raise exc + + return opener + + +# Versions. + + +@pytest.mark.parametrize( + ("candidate", "current", "newer"), + [ + ("0.3.0", "0.2.6", True), + ("v0.10.0", "0.9.0", True), + ("0.2.6", "0.2.6", False), + ("0.2.5", "0.2.6", False), + ("1.0.0", "0.99.99", True), + ("nonsense", "0.2.6", False), + ], +) +def test_version_numbers_compare_as_counters(candidate, current, newer): + assert is_newer(candidate, current) is newer + + +# Reading GitHub's reply. + + +def test_a_release_with_a_setup_file_can_be_installed(): + release = release_from_json(release_json()) + + assert release == Release("0.3.0", SETUP_URL, len(SETUP_BYTES), SETUP_SHA) + + +@pytest.mark.parametrize( + "asset", + [ + {"digest": None}, + {"digest": "md5:abc"}, + {"browser_download_url": "https://example.com/MapHide-v0.3.0-setup.exe"}, + {"name": "MapHide-v0.2.0-setup.exe"}, + ], + ids=["no checksum", "wrong checksum kind", "elsewhere", "other version"], +) +def test_a_setup_file_maphide_cant_trust_is_not_offered(asset): + release = release_from_json(release_json(**asset)) + + assert release.version == "0.3.0" + assert release.setup_url is None + + +@pytest.mark.parametrize("data", [[], {"tag_name": "latest"}, {}]) +def test_a_reply_that_isnt_a_release_is_an_error(data): + with pytest.raises(UpdateError): + release_from_json(data) + + +def test_fetching_asks_github_and_names_maphide(): + opener = opener_returning(json.dumps(release_json()).encode()) + + release = fetch_latest(opener) + + assert release.version == "0.3.0" + request = opener.requests[0] + assert request.full_url == updates.LATEST_RELEASE_API + assert request.get_header("User-agent").startswith("MapHide/") + + +@pytest.mark.parametrize( + ("exc", "message"), + [ + (urllib.error.URLError("offline"), updates.NO_CONNECTION), + (TimeoutError(), updates.NO_CONNECTION), + ( + urllib.error.HTTPError(updates.LATEST_RELEASE_API, 403, "", {}, None), + updates.GITHUB_UNAVAILABLE, + ), + ], +) +def test_fetch_failures_are_explained(exc, message): + with pytest.raises(UpdateError, match=message.split(".")[0]): + fetch_latest(opener_raising(exc)) + + +def test_a_garbled_reply_is_explained(): + with pytest.raises(UpdateError, match="couldn't read"): + fetch_latest(opener_returning(b"")) + + +# Downloading. + + +def test_a_download_is_kept_once_its_checksum_matches(tmp_path): + progress = [] + release = release_from_json(release_json()) + + path = download_setup(release, tmp_path, progress.append, opener_returning(SETUP_BYTES)) + + assert path.read_bytes() == SETUP_BYTES + assert path.name == "MapHide-v0.3.0-setup.exe" + assert progress[-1] == 1.0 + + +def test_a_damaged_download_is_thrown_away(tmp_path): + release = release_from_json(release_json()) + + with pytest.raises(UpdateError, match="damaged"): + download_setup(release, tmp_path, opener=opener_returning(b"not it")) + + assert list(tmp_path.iterdir()) == [] + + +def test_a_broken_download_is_thrown_away(tmp_path): + release = release_from_json(release_json()) + + with pytest.raises(UpdateError, match="didn't finish"): + download_setup(release, tmp_path, opener=opener_raising(ConnectionResetError())) + + assert list(tmp_path.iterdir()) == [] + + +def test_only_this_projects_releases_are_downloaded(tmp_path): + release = Release("0.3.0", "https://example.com/setup.exe", 1, SETUP_SHA) + + with pytest.raises(UpdateError): + download_setup(release, tmp_path, opener=opener_returning(SETUP_BYTES)) + + +def test_the_installer_runs_with_progress_only_and_reopens_maphide(tmp_path): + launched = [] + + launch_installer(tmp_path / "setup.exe", lambda args, **_: launched.append(args)) + + assert launched == [[str(tmp_path / "setup.exe"), *updates.INSTALLER_ARGUMENTS]] + assert "/SILENT" in launched[0] and "/RELAUNCH=1" in launched[0] + + +def test_an_installer_that_wont_start_is_explained(tmp_path): + def popen(args, **_): + raise FileNotFoundError + + with pytest.raises(UpdateError, match="couldn't start"): + launch_installer(tmp_path / "setup.exe", popen) + + +# Which copies can install an update themselves. + + +def test_only_an_installed_github_copy_installs_updates(tmp_path): + (tmp_path / updates.UNINSTALLER_NAME).touch() + + assert installed_by_setup("github", True, tmp_path) is True + assert installed_by_setup("store", True, tmp_path) is False + assert installed_by_setup("github", False, tmp_path) is False + assert installed_by_setup("github", True, tmp_path / "unzipped") is False + + +# The Updater, one step at a time. + + +class Steps: + def __init__(self, release=None, error=None, can_install=True): + self.schedule = ManualScheduler() + self.changes = 0 + self.downloads = [] + self.launched = [] + self.download_error = None + self.release = release or release_from_json(release_json()) + self.error = error + self.updater = Updater( + self.schedule, + on_change=self._changed, + current="0.2.6", + fetch=self._fetch, + download=self._download, + launch=self.launched.append, + can_install=can_install, + folder="downloads", + ) + + def _changed(self): + self.changes += 1 + + def _fetch(self): + if self.error: + raise UpdateError(self.error) + return self.release + + def _download(self, release, folder, progress): + if self.download_error: + raise UpdateError(self.download_error) + self.downloads.append((release.version, folder)) + progress(1.0) + return "setup.exe" + + def finish(self): + self.updater.thread.join(timeout=5) + while self.schedule.pending: + self.schedule.run_next() + + +def test_a_newer_version_is_found_and_reported(): + s = Steps() + found = [] + + assert s.updater.check(on_found=found.append) is True + assert s.updater.state == CHECKING + s.finish() + + assert s.updater.state == AVAILABLE + assert found == [s.release] + + +def test_the_same_version_reads_as_up_to_date(): + s = Steps(release=Release("0.2.6")) + + s.updater.check() + s.finish() + + assert s.updater.state == LATEST + assert s.updater.release is None + + +def test_a_quiet_check_says_nothing_when_maphide_is_up_to_date(): + s = Steps(release=Release("0.2.6")) + + s.updater.check(quiet=True) + s.finish() + + assert s.updater.state == IDLE + + +def test_up_to_date_is_only_said_for_a_moment(): + s = Steps(release=Release("0.2.6")) + s.updater.check() + s.finish() + + s.updater.clear_latest() + + assert s.updater.state == IDLE + + +def test_clearing_leaves_a_found_update_alone(): + s = Steps() + s.updater.check() + s.finish() + + s.updater.clear_latest() + + assert s.updater.state == AVAILABLE + + +def test_a_failed_check_says_why(): + s = Steps(error=updates.NO_CONNECTION) + + s.updater.check() + s.finish() + + assert (s.updater.state, s.updater.message) == (FAILED, updates.NO_CONNECTION) + + +def test_a_quiet_check_that_fails_says_nothing(): + s = Steps(error=updates.NO_CONNECTION) + + s.updater.check(quiet=True) + s.finish() + + assert (s.updater.state, s.updater.message) == (IDLE, "") + + +def test_a_second_check_while_one_runs_does_nothing(): + s = Steps() + s.updater.check() + + assert s.updater.check() is False + s.finish() + + +def test_installing_downloads_runs_the_installer_then_closes_maphide(): + s = Steps() + s.updater.check() + s.finish() + closed = [] + + assert s.updater.install(on_started=lambda: closed.append(True)) is True + assert s.updater.state == DOWNLOADING + s.finish() + + assert s.downloads == [("0.3.0", "downloads")] + assert s.launched == ["setup.exe"] + assert s.updater.state == INSTALLING + assert closed == [True] + + +def test_a_failed_download_keeps_maphide_open_and_can_be_retried(): + s = Steps() + s.updater.check() + s.finish() + s.download_error = updates.DOWNLOAD_FAILED + closed = [] + + s.updater.install(on_started=lambda: closed.append(True)) + s.finish() + + assert (s.updater.state, s.updater.message) == (FAILED, updates.DOWNLOAD_FAILED) + assert closed == [] + s.download_error = None + assert s.updater.install(on_started=lambda: closed.append(True)) is True + s.finish() + assert closed == [True] + + +@pytest.mark.parametrize( + "steps", + [ + lambda: Steps(can_install=False), + lambda: Steps(release=Release("0.3.0")), + ], + ids=["unzipped copy", "no setup file"], +) +def test_nothing_is_installed_when_it_cant_be(steps): + s = steps() + s.updater.check() + s.finish() + + assert s.updater.install(on_started=lambda: None) is False + assert s.downloads == [] + + +def test_nothing_is_installed_before_a_check_finds_something(): + s = Steps() + + assert s.updater.install(on_started=lambda: None) is False