mirror of
https://github.com/Flowseal/tg-ws-proxy.git
synced 2026-11-22 07:26:31 +03:00
Не зависать при самообновлении в папке без прав записи (#1531)
This commit is contained in:
@@ -27,6 +27,18 @@ class AssetNameTest(unittest.TestCase):
|
||||
self.assertEqual(windows_update.asset_name(), expected)
|
||||
|
||||
|
||||
class CanSelfUpdateTest(unittest.TestCase):
|
||||
def test_writable_folder_leaves_no_files_behind(self):
|
||||
with tempfile.TemporaryDirectory() as directory, \
|
||||
mock.patch.object(sys, 'executable', str(Path(directory) / 'app.exe')):
|
||||
self.assertTrue(windows_update.can_self_update())
|
||||
self.assertEqual(list(Path(directory).iterdir()), [])
|
||||
|
||||
def test_unwritable_folder_is_reported(self):
|
||||
with mock.patch.object(windows_update.os, 'open', side_effect=PermissionError('denied')):
|
||||
self.assertFalse(windows_update.can_self_update())
|
||||
|
||||
|
||||
class ApplyUpdateTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
stack = ExitStack()
|
||||
@@ -61,6 +73,15 @@ class ApplyUpdateTest(unittest.TestCase):
|
||||
self.assertEqual(self.launch.call_args[0][0], [str(self.exe), '--portable'])
|
||||
self.assertEqual(self.launch.call_args[1]['creationflags'], 520)
|
||||
|
||||
def test_unwritable_folder_fails_before_downloading_or_touching_files(self):
|
||||
with mock.patch.object(windows_update, 'can_self_update', return_value=False):
|
||||
with self.assertRaises(PermissionError):
|
||||
windows_update.apply_update(self.asset, self.prepare)
|
||||
self.opener.open.assert_not_called()
|
||||
self.assertEqual(list(self.exe.parent.iterdir()), [self.exe])
|
||||
self.prepare.assert_not_called()
|
||||
self.launch.assert_not_called()
|
||||
|
||||
def test_missing_or_corrupt_checksum_does_not_replace_or_launch(self):
|
||||
for digest in ('', 'sha256:' + '0' * 64):
|
||||
with self.subTest(digest=digest):
|
||||
@@ -132,6 +153,28 @@ class UpdateFlowTest(unittest.TestCase):
|
||||
app.update_ctk_form('update', asset=asset)
|
||||
update.assert_called_once_with(asset)
|
||||
|
||||
def _offered_asset(self, writable):
|
||||
app = self.windows
|
||||
asset = {'url': 'https://example.invalid/new.exe', 'digest': 'sha256:' + '0' * 64}
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(mock.patch.object(app, 'IS_FROZEN', True))
|
||||
stack.enter_context(mock.patch.object(app, '_exiting', False))
|
||||
stack.enter_context(mock.patch.object(app, '_tray_icon', None))
|
||||
stack.enter_context(mock.patch.object(app, 'get_status', return_value={'has_update': True}))
|
||||
stack.enter_context(mock.patch.object(app, 'asset_name', return_value='app.exe'))
|
||||
stack.enter_context(mock.patch.object(app, 'find_asset', return_value=asset))
|
||||
stack.enter_context(mock.patch.object(app, 'can_self_update', return_value=writable))
|
||||
form = stack.enter_context(mock.patch.object(app, 'update_ctk_form', return_value='close'))
|
||||
thread = stack.enter_context(mock.patch.object(app.threading, 'Thread'))
|
||||
app._trigger_update_flow()
|
||||
thread.call_args.kwargs['target']()
|
||||
return asset, form.call_args.kwargs['asset']
|
||||
|
||||
def test_update_button_is_offered_only_when_the_folder_is_writable(self):
|
||||
asset, offered = self._offered_asset(writable=True)
|
||||
self.assertEqual(offered, asset)
|
||||
self.assertIsNone(self._offered_asset(writable=False)[1])
|
||||
|
||||
def test_failed_launch_recovers_proxy_and_lock_instead_of_exiting(self):
|
||||
app = self.windows
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import sysconfig
|
||||
import uuid
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
@@ -24,10 +26,29 @@ def asset_name() -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def can_self_update() -> bool:
|
||||
"""Whether the executable's folder is writable.
|
||||
|
||||
Neither os.access nor tempfile.mkstemp can be used here: on Windows the
|
||||
former ignores ACLs and the latter keeps retrying on PermissionError, so
|
||||
in a folder without write access it hangs instead of failing.
|
||||
"""
|
||||
probe = Path(sys.executable).parent / f"TgWsProxy_probe_{uuid.uuid4().hex}"
|
||||
try:
|
||||
os.close(os.open(probe, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
|
||||
except OSError:
|
||||
return False
|
||||
with suppress(OSError):
|
||||
probe.unlink()
|
||||
return True
|
||||
|
||||
|
||||
def apply_update(asset: dict, before_restart: Callable[[], None]) -> None:
|
||||
"""Verify, replace and launch; keep the old executable if any step fails."""
|
||||
exe = Path(sys.executable)
|
||||
backup = exe.with_name(exe.stem + "_oldtgws.exe")
|
||||
if not can_self_update():
|
||||
raise PermissionError(f"No write access to {exe.parent}")
|
||||
downloaded = download_asset(asset["url"], exe.parent, digest=asset["digest"])
|
||||
try:
|
||||
backup.unlink(missing_ok=True)
|
||||
|
||||
+2
-2
@@ -45,7 +45,7 @@ from utils.tray_common import (
|
||||
save_config, start_proxy, stop_proxy, tg_proxy_url,
|
||||
)
|
||||
from utils.update_check import find_asset, get_status, RELEASES_PAGE_URL
|
||||
from utils.windows_update import apply_update, asset_name
|
||||
from utils.windows_update import apply_update, asset_name, can_self_update
|
||||
from ui.ctk_tray_ui import (
|
||||
install_tray_config_buttons, install_tray_config_form,
|
||||
populate_first_run_window, tray_settings_scroll_and_footer,
|
||||
@@ -276,7 +276,7 @@ def _trigger_update_flow(icon=None, item=None) -> None:
|
||||
_tray_icon.menu = _build_menu()
|
||||
url = (st.get("html_url") or "").strip() or RELEASES_PAGE_URL
|
||||
ver = st.get("latest") or "?"
|
||||
asset = find_asset(asset_name()) if IS_FROZEN else None
|
||||
asset = find_asset(asset_name()) if IS_FROZEN and can_self_update() else None
|
||||
|
||||
choice = update_ctk_form(
|
||||
t("update.available", version=ver),
|
||||
|
||||
Reference in New Issue
Block a user