diff --git a/steam_backlog_enforcer/_budget_resolve.py b/steam_backlog_enforcer/_budget_resolve.py index eba3eed..1864e60 100644 --- a/steam_backlog_enforcer/_budget_resolve.py +++ b/steam_backlog_enforcer/_budget_resolve.py @@ -141,21 +141,19 @@ def resolve_budget(config: Config) -> BudgetResolution: ) total = base + workout_seconds + leetcode_seconds - reason = "{:.1f}h: {}, {}".format( - total / _SECONDS_PER_HOUR, - _describe( - answer=workout, - earned="workout counted", - missed="no counted workout", - unknown="workout unknown (screen-locker unreachable)", - ), - _describe( - answer=leetcode, - earned="LeetCode solve recorded", - missed="no LeetCode solve recorded", - unknown="LeetCode unknown (ledger and status API both unreadable)", - ), + workout_part = _describe( + answer=workout, + earned="workout counted", + missed="no counted workout", + unknown="workout unknown (screen-locker unreachable)", ) + leetcode_part = _describe( + answer=leetcode, + earned="LeetCode solve recorded", + missed="no LeetCode solve recorded", + unknown="LeetCode unknown (ledger and status API both unreadable)", + ) + reason = f"{total / _SECONDS_PER_HOUR:.1f}h: {workout_part}, {leetcode_part}" logger.info("Gaming budget %s", reason) return BudgetResolution( seconds=total, diff --git a/steam_backlog_enforcer/_cmd_done.py b/steam_backlog_enforcer/_cmd_done.py index 14d83ef..10867a8 100644 --- a/steam_backlog_enforcer/_cmd_done.py +++ b/steam_backlog_enforcer/_cmd_done.py @@ -11,6 +11,7 @@ from steam_backlog_enforcer._hltb_confidence import fetch_hltb_confidence_cached from steam_backlog_enforcer._hltb_types import ( load_hltb_cache, load_hltb_polls_cache, + restore_prior_hours, save_hltb_cache, ) from steam_backlog_enforcer._snapshot import load_snapshot @@ -93,9 +94,7 @@ def _backfill_polls_for_finished( refreshed_hours = load_hltb_cache() refreshed_polls = load_hltb_polls_cache() - for aid, prior_hours in preserved_hours.items(): - if prior_hours > 0 and refreshed_hours.get(aid, -1) <= 0: - refreshed_hours[aid] = prior_hours + restore_prior_hours(refreshed_hours, preserved_hours) save_hltb_cache(refreshed_hours, refreshed_polls) return refreshed_polls diff --git a/steam_backlog_enforcer/_enforce_loop.py b/steam_backlog_enforcer/_enforce_loop.py index 3609e35..aeb7f58 100644 --- a/steam_backlog_enforcer/_enforce_loop.py +++ b/steam_backlog_enforcer/_enforce_loop.py @@ -70,21 +70,21 @@ def _allowed_names(state: State) -> str: return ", ".join(names) if names else "your assigned game" -def _guard_installed_games(allowed_app_ids: set[int]) -> int: +def _guard_installed_games(allowed: set[int]) -> int: """Remove any unauthorized game manifests + files. Runs every loop. Args: - allowed_app_ids: Every app id that may stay installed — the assignment - plus any concurrent manual picks. + allowed: Every app id that may stay installed — the assignment plus + any concurrent manual picks. Returns number of games removed this pass. """ - if not allowed_app_ids: + if not allowed: return 0 installed = get_installed_games() count = 0 for app_id, name in installed: - if app_id in allowed_app_ids: + if app_id in allowed: continue if is_protected_app(app_id): continue diff --git a/steam_backlog_enforcer/_game_names.py b/steam_backlog_enforcer/_game_names.py index 156f344..a67bcf3 100644 --- a/steam_backlog_enforcer/_game_names.py +++ b/steam_backlog_enforcer/_game_names.py @@ -69,7 +69,7 @@ def _protected_name_stems() -> list[str]: """ try: return [name for _, name in allowed_games(State.load()) if name] - except Exception: + except Exception: # pylint: disable=broad-exception-caught logger.exception("Could not load allowed games for the deletion safety net") return [] diff --git a/steam_backlog_enforcer/_hltb_confidence.py b/steam_backlog_enforcer/_hltb_confidence.py index dd150ad..3ae3381 100644 --- a/steam_backlog_enforcer/_hltb_confidence.py +++ b/steam_backlog_enforcer/_hltb_confidence.py @@ -19,6 +19,7 @@ from steam_backlog_enforcer._hltb_types import ( load_hltb_leisure_100h_cache, load_hltb_polls_cache, load_hltb_rush_cache, + restore_prior_hours, save_hltb_cache, ) from steam_backlog_enforcer.hltb import ( @@ -152,10 +153,7 @@ def fetch_hltb_detail_missing( ) elapsed = time.monotonic() - t0 - # Restore prior hours for games the detail fetch didn't re-find. - for app_id, old_hours in prior_hours.items(): - if old_hours > 0 and cache.get(app_id, -1.0) <= 0: - cache[app_id] = old_hours + restore_prior_hours(cache, prior_hours) save_hltb_cache(cache, polls, extras) diff --git a/steam_backlog_enforcer/_hltb_matching.py b/steam_backlog_enforcer/_hltb_matching.py index dfaacb6..2bba01b 100644 --- a/steam_backlog_enforcer/_hltb_matching.py +++ b/steam_backlog_enforcer/_hltb_matching.py @@ -182,10 +182,13 @@ def _find_best_extended( entry_name = (entry.get("game_name") or "").lower() if entry_name.startswith((lower + ":", lower + " -")): suffix = entry_name[len(lower) :].lstrip(" :-") - if not any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES) and ( - best is None or entry.get("comp_100", 0) > best[0].get("comp_100", 0) + if any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES): + continue + if best is not None and entry.get("comp_100", 0) <= best[0].get( + "comp_100", 0 ): - best = (entry, sim) + continue + best = (entry, sim) return best diff --git a/steam_backlog_enforcer/_hltb_search_api.py b/steam_backlog_enforcer/_hltb_search_api.py index 11d838d..227bbea 100644 --- a/steam_backlog_enforcer/_hltb_search_api.py +++ b/steam_backlog_enforcer/_hltb_search_api.py @@ -42,20 +42,19 @@ _EXTENDED_MIN_CONFIDENCE = 3 # ────────────────────────────────────────────────────────────── +_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0" + + def _get_hltb_search_url() -> str: """Discover the current HLTB search API endpoint. - Scrapes the homepage for JS bundles containing the fetch URL. - Falls back to ``/api/finder`` if extraction fails. + Scrapes the homepage for JS bundles containing the fetch URL, walking + every bundle until one names it (howlongtobeatpy >= 1.0.23 does that + itself; the older ``parse_all_scripts`` two-step is gone). Falls back to + ``/api/finder`` if extraction fails. """ try: - search_info = HTMLRequests.send_website_request_getcode( - parse_all_scripts=False, - ) - if search_info is None: - search_info = HTMLRequests.send_website_request_getcode( - parse_all_scripts=True, - ) + search_info = HTMLRequests.send_website_request_getcode(_USER_AGENT) if search_info and search_info.search_url: url: str = HTMLRequests.BASE_URL + search_info.search_url return url @@ -72,9 +71,7 @@ async def _get_auth_info( init_url = search_url + "/init" ts = int(time.time() * 1000) headers = { - "User-Agent": ( - "Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0" - ), + "User-Agent": _USER_AGENT, "referer": "https://howlongtobeat.com/", } try: diff --git a/steam_backlog_enforcer/_hltb_types.py b/steam_backlog_enforcer/_hltb_types.py index 6ae8dd1..3ba4e65 100644 --- a/steam_backlog_enforcer/_hltb_types.py +++ b/steam_backlog_enforcer/_hltb_types.py @@ -136,6 +136,17 @@ def _read_raw_cache() -> dict[int, dict[str, Any]]: return out +def restore_prior_hours(refreshed: dict[int, float], prior: dict[int, float]) -> None: + """Put back known hours a refetch replaced with nothing. + + A refetch that finds no (or a zero-hour) match must not erase an estimate + we already had -- prior leisure/DLC figures are trusted over a miss. + """ + for app_id, old_hours in prior.items(): + if old_hours > 0 and refreshed.get(app_id, -1.0) <= 0: + refreshed[app_id] = old_hours + + def load_hltb_cache() -> dict[int, float]: """Load the hours portion of the HLTB cache. diff --git a/steam_backlog_enforcer/_hosts_protection.py b/steam_backlog_enforcer/_hosts_protection.py index 3bc5653..1ba7db8 100644 --- a/steam_backlog_enforcer/_hosts_protection.py +++ b/steam_backlog_enforcer/_hosts_protection.py @@ -7,10 +7,13 @@ introduces no cycle. Split to keep both files under the 250-line cap. from __future__ import annotations import logging -from pathlib import Path -import shutil import subprocess +from steam_backlog_enforcer._store_tools import ( + GUARDCTL, + SUDO, + TEE, +) from steam_backlog_enforcer.config import ( BLOCKED_DOMAINS, HOSTS_FILE, @@ -18,33 +21,6 @@ from steam_backlog_enforcer.config import ( logger = logging.getLogger(__name__) -# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this -# module lives two levels below it); the script itself is in the -# linux_configuration checkout under testsAndMisc, not directly under $HOME. -_REPO_ROOT = Path(__file__).resolve().parents[2] -HOSTS_INSTALL_SCRIPT = ( - _REPO_ROOT - / "testsAndMisc" - / "linux_configuration" - / "scripts" - / "periodic_background" - / "hosts" - / "install.sh" -) - -# iptables chain name for our blocking rules. -IPTABLES_CHAIN = "STEAM_ENFORCER" - -# Resolved absolute paths for executables (avoids S607 partial-path warnings). -_SUDO = shutil.which("sudo") or "/usr/bin/sudo" -_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables" -_BASH = shutil.which("bash") or "/usr/bin/bash" -_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl" -_TEE = shutil.which("tee") or "/usr/bin/tee" - -# IP address used in /etc/hosts for blocking domains. -_HOSTS_REDIRECT_IP = ".".join(["0"] * 4) - def _disable_hosts_protection() -> None: """Temporarily unlock /etc/hosts so its content can be edited. @@ -52,7 +28,7 @@ def _disable_hosts_protection() -> None: Guard-lib: stop watcher, collapse bind mount, chattr -i. """ subprocess.run( - [_SUDO, _GUARDCTL, "file-guard", "pacman-unlock", "hosts"], + [SUDO, GUARDCTL, "file-guard", "pacman-unlock", "hosts"], capture_output=True, timeout=10, check=False, @@ -65,7 +41,7 @@ def _enable_hosts_protection() -> None: Guard-lib: chattr +i, reapply bind mount, restart watcher. """ subprocess.run( - [_SUDO, _GUARDCTL, "file-guard", "sync", "hosts"], + [SUDO, GUARDCTL, "file-guard", "sync", "hosts"], capture_output=True, timeout=10, check=False, @@ -75,7 +51,7 @@ def _enable_hosts_protection() -> None: def _sudo_write_hosts(content: str) -> None: """Write *content* to /etc/hosts via ``sudo tee``.""" subprocess.run( - [_SUDO, _TEE, str(HOSTS_FILE)], + [SUDO, TEE, str(HOSTS_FILE)], input=content.encode(), stdout=subprocess.DEVNULL, timeout=10, @@ -110,5 +86,4 @@ def _reblock_hosts() -> bool: except OSError: logger.exception("Failed to modify /etc/hosts") return False - else: - return True + return True diff --git a/steam_backlog_enforcer/_owned_apps_cache.py b/steam_backlog_enforcer/_owned_apps_cache.py index 7cf9540..61d490e 100644 --- a/steam_backlog_enforcer/_owned_apps_cache.py +++ b/steam_backlog_enforcer/_owned_apps_cache.py @@ -106,8 +106,7 @@ def get_all_owned_app_ids(config: Config) -> list[int]: return snapshot_ids logger.warning("Could not fetch owned game list for hiding.") return [] - else: - return merged_ids + return merged_ids # ────────────────────────────────────────────────────────────── diff --git a/steam_backlog_enforcer/_playtime_state.py b/steam_backlog_enforcer/_playtime_state.py index 60b31d5..59446a7 100644 --- a/steam_backlog_enforcer/_playtime_state.py +++ b/steam_backlog_enforcer/_playtime_state.py @@ -7,7 +7,7 @@ which is what lets the enforcer survive a restart mid-session. from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass, field, fields from datetime import datetime, timedelta import json import logging @@ -220,8 +220,8 @@ def load_state(*, demo: bool) -> PlaytimeState | None: if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION: logger.warning("Playtime state at %s has an unknown schema.", path) return None - fields = PlaytimeState.__dataclass_fields__ - return PlaytimeState(**{k: v for k, v in data.items() if k in fields}) + known = {f.name for f in fields(PlaytimeState)} + return PlaytimeState(**{k: v for k, v in data.items() if k in known}) def save_state(state: PlaytimeState, *, demo: bool) -> None: diff --git a/steam_backlog_enforcer/_polls_reporting.py b/steam_backlog_enforcer/_polls_reporting.py index e66185a..b9d4329 100644 --- a/steam_backlog_enforcer/_polls_reporting.py +++ b/steam_backlog_enforcer/_polls_reporting.py @@ -13,6 +13,7 @@ from steam_backlog_enforcer._hltb_confidence import fetch_hltb_confidence_cached from steam_backlog_enforcer._hltb_types import ( load_hltb_cache, load_hltb_polls_cache, + restore_prior_hours, save_hltb_cache, ) @@ -62,9 +63,7 @@ def _backfill_polls_for_finished( # with a worse match (we trust prior leisure+dlc estimates). refreshed_hours = load_hltb_cache() refreshed_polls = load_hltb_polls_cache() - for aid, prior_hours in preserved_hours.items(): - if prior_hours > 0 and refreshed_hours.get(aid, -1) <= 0: - refreshed_hours[aid] = prior_hours + restore_prior_hours(refreshed_hours, preserved_hours) save_hltb_cache(refreshed_hours, refreshed_polls) return refreshed_polls diff --git a/steam_backlog_enforcer/_scanning_candidates.py b/steam_backlog_enforcer/_scanning_candidates.py index 79e05dd..694762b 100644 --- a/steam_backlog_enforcer/_scanning_candidates.py +++ b/steam_backlog_enforcer/_scanning_candidates.py @@ -32,7 +32,7 @@ def _sort_key(g: GameInfo) -> tuple[int, float]: """Sort by known HLTB time (shortest first), then unknown games.""" if g.completionist_hours > 0: return (0, g.completionist_hours) - return (1, g.name.lower().encode().hex().__hash__()) + return (1, hash(g.name.lower().encode().hex())) def _pick_playable_candidate( diff --git a/steam_backlog_enforcer/_scanning_confidence.py b/steam_backlog_enforcer/_scanning_confidence.py index 8eeb9c2..ebdf1d6 100644 --- a/steam_backlog_enforcer/_scanning_confidence.py +++ b/steam_backlog_enforcer/_scanning_confidence.py @@ -11,18 +11,18 @@ from steam_backlog_enforcer._hltb_types import ( load_hltb_cache, load_hltb_count_comp_cache, load_hltb_polls_cache, + restore_prior_hours, save_hltb_cache, ) +from steam_backlog_enforcer._polls_reporting import ( + _backfill_polls_for_finished, + _report_poll_confidence, +) from steam_backlog_enforcer.game_install import _echo if TYPE_CHECKING: from steam_backlog_enforcer.steam_api import GameInfo -from steam_backlog_enforcer._polls_reporting import ( - _backfill_polls_for_finished, - _report_poll_confidence, -) - logger = logging.getLogger(__name__) __all__ = [ @@ -123,9 +123,7 @@ def _refresh_candidate_confidence_batch( refreshed_hours = load_hltb_cache() refreshed_polls = load_hltb_polls_cache() refreshed_count_comp = load_hltb_count_comp_cache() - for aid, old_hours in prior_hours.items(): - if old_hours > 0 and refreshed_hours.get(aid, -1) <= 0: - refreshed_hours[aid] = old_hours + restore_prior_hours(refreshed_hours, prior_hours) save_hltb_cache( refreshed_hours, refreshed_polls, _HLTBExtras(count_comp=refreshed_count_comp) ) diff --git a/steam_backlog_enforcer/_steam_api_client.py b/steam_backlog_enforcer/_steam_api_client.py index b850453..62a2669 100644 --- a/steam_backlog_enforcer/_steam_api_client.py +++ b/steam_backlog_enforcer/_steam_api_client.py @@ -77,8 +77,7 @@ class SteamAPIClient: except requests.RequestException as e: msg = f"Steam API request failed: {e}" raise SteamAPIError(msg) from e - else: - return result + return result def get_owned_games(self) -> list[dict[str, Any]]: """Fetch all games owned by the user.""" diff --git a/steam_backlog_enforcer/_steam_client.py b/steam_backlog_enforcer/_steam_client.py index 0304d67..c1cb206 100644 --- a/steam_backlog_enforcer/_steam_client.py +++ b/steam_backlog_enforcer/_steam_client.py @@ -20,6 +20,7 @@ from steam_backlog_enforcer._desktop_env import ( resolve_desktop_user, ) from steam_backlog_enforcer._steam_launch import steam_is_installed +from steam_backlog_enforcer._steam_process import spawn_detached from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH logger = logging.getLogger(__name__) @@ -42,8 +43,7 @@ def _get_uid_gid_for_user(username: str) -> tuple[int, int]: pw = pwd.getpwnam(username) except KeyError: return 1000, 1000 - else: - return pw.pw_uid, pw.pw_gid + return pw.pw_uid, pw.pw_gid def is_game_installed(app_id: int) -> bool: @@ -106,11 +106,7 @@ def _ensure_steam_running() -> None: else: cmd = ["steam", "-silent"] - subprocess.Popen( - cmd, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) + spawn_detached(cmd) # Give Steam time to initialize and start scanning manifests. time.sleep(15) except FileNotFoundError: diff --git a/steam_backlog_enforcer/_steam_process.py b/steam_backlog_enforcer/_steam_process.py index 6a30a9d..c7c4a7e 100644 --- a/steam_backlog_enforcer/_steam_process.py +++ b/steam_backlog_enforcer/_steam_process.py @@ -19,6 +19,20 @@ logger = logging.getLogger(__name__) _SPAWNED: list[subprocess.Popen[bytes]] = [] +def spawn_detached(cmd: list[str]) -> subprocess.Popen[bytes]: + """Start ``cmd`` and hand back the process, output discarded. + + Fire-and-forget on purpose: the process must outlive the calling scope + (Steam itself, a desktop notifier), so it is polled or reaped later rather + than waited on in a ``with`` block here. + """ + return subprocess.Popen( + cmd, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + def _reap_spawned() -> None: """Clear out previously launched processes that have since exited. @@ -49,10 +63,4 @@ def _run_as_user(cmd: list[str], user: str | None) -> None: return full_cmd = desktop_user_cmd(cmd, user) - _SPAWNED.append( - subprocess.Popen( - full_cmd, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) - ) + _SPAWNED.append(spawn_detached(full_cmd)) diff --git a/steam_backlog_enforcer/_store_iptables.py b/steam_backlog_enforcer/_store_iptables.py index faef20e..c3d7b16 100644 --- a/steam_backlog_enforcer/_store_iptables.py +++ b/steam_backlog_enforcer/_store_iptables.py @@ -9,50 +9,26 @@ from __future__ import annotations import contextlib import logging -from pathlib import Path -import shutil import socket import subprocess +from steam_backlog_enforcer._store_tools import ( + IPTABLES, + IPTABLES_CHAIN, + SUDO, +) from steam_backlog_enforcer.config import ( BLOCKED_DOMAINS, ) logger = logging.getLogger(__name__) -# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this -# module lives two levels below it); the script itself is in the -# linux_configuration checkout under testsAndMisc, not directly under $HOME. -_REPO_ROOT = Path(__file__).resolve().parents[2] -HOSTS_INSTALL_SCRIPT = ( - _REPO_ROOT - / "testsAndMisc" - / "linux_configuration" - / "scripts" - / "periodic_background" - / "hosts" - / "install.sh" -) - -# iptables chain name for our blocking rules. -IPTABLES_CHAIN = "STEAM_ENFORCER" - -# Resolved absolute paths for executables (avoids S607 partial-path warnings). -_SUDO = shutil.which("sudo") or "/usr/bin/sudo" -_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables" -_BASH = shutil.which("bash") or "/usr/bin/bash" -_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl" -_TEE = shutil.which("tee") or "/usr/bin/tee" - -# IP address used in /etc/hosts for blocking domains. -_HOSTS_REDIRECT_IP = ".".join(["0"] * 4) - def _is_iptables_blocked() -> bool: """Check if our iptables chain exists and has rules.""" try: result = subprocess.run( - [_SUDO, _IPTABLES, "-L", IPTABLES_CHAIN, "-n"], + [SUDO, IPTABLES, "-L", IPTABLES_CHAIN, "-n"], capture_output=True, text=True, timeout=5, @@ -60,8 +36,7 @@ def _is_iptables_blocked() -> bool: ) except OSError, subprocess.SubprocessError: return False - else: - return result.returncode == 0 and "DROP" in result.stdout + return result.returncode == 0 and "DROP" in result.stdout def _block_store_iptables() -> bool: @@ -69,14 +44,14 @@ def _block_store_iptables() -> bool: try: # Create chain if it doesn't exist. subprocess.run( - [_SUDO, _IPTABLES, "-N", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-N", IPTABLES_CHAIN], capture_output=True, timeout=5, check=False, ) # Flush existing rules in our chain. subprocess.run( - [_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-F", IPTABLES_CHAIN], capture_output=True, timeout=5, check=True, @@ -93,8 +68,8 @@ def _block_store_iptables() -> bool: for ip in blocked_ips: subprocess.run( [ - _SUDO, - _IPTABLES, + SUDO, + IPTABLES, "-A", IPTABLES_CHAIN, "-d", @@ -109,14 +84,14 @@ def _block_store_iptables() -> bool: # Hook our chain into OUTPUT if not already there. result = subprocess.run( - [_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN], capture_output=True, timeout=5, check=False, ) if result.returncode != 0: subprocess.run( - [_SUDO, _IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN], capture_output=True, timeout=5, check=True, @@ -124,28 +99,27 @@ def _block_store_iptables() -> bool: except OSError, subprocess.SubprocessError: logger.exception("Failed to block store via iptables") return False - else: - logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips)) - return True + logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips)) + return True def _unblock_store_iptables() -> bool: """Remove iptables-based block.""" try: subprocess.run( - [_SUDO, _IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN], capture_output=True, timeout=5, check=False, ) subprocess.run( - [_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-F", IPTABLES_CHAIN], capture_output=True, timeout=5, check=False, ) subprocess.run( - [_SUDO, _IPTABLES, "-X", IPTABLES_CHAIN], + [SUDO, IPTABLES, "-X", IPTABLES_CHAIN], capture_output=True, timeout=5, check=False, @@ -153,9 +127,8 @@ def _unblock_store_iptables() -> bool: except OSError, subprocess.SubprocessError: logger.exception("Failed to unblock iptables") return False - else: - logger.info("Steam Store unblocked from iptables.") - return True + logger.info("Steam Store unblocked from iptables.") + return True def flush_dns_cache() -> None: diff --git a/steam_backlog_enforcer/_store_tools.py b/steam_backlog_enforcer/_store_tools.py new file mode 100644 index 0000000..60584ee --- /dev/null +++ b/steam_backlog_enforcer/_store_tools.py @@ -0,0 +1,38 @@ +"""The executables and paths every store-blocking layer shells out to. + +One copy, imported by the hosts, iptables and orchestration modules alike -- +each used to carry its own after the 250-line split, three blocks that had +to be kept identical by hand. +""" + +from __future__ import annotations + +from pathlib import Path +import shutil + +# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this +# module lives two levels below it); the script itself is in the +# linux_configuration checkout under testsAndMisc, not directly under $HOME. +_REPO_ROOT = Path(__file__).resolve().parents[2] +HOSTS_INSTALL_SCRIPT = ( + _REPO_ROOT + / "testsAndMisc" + / "linux_configuration" + / "scripts" + / "periodic_background" + / "hosts" + / "install.sh" +) + +# iptables chain name for our blocking rules. +IPTABLES_CHAIN = "STEAM_ENFORCER" + +# Resolved absolute paths for executables (avoids S607 partial-path warnings). +SUDO = shutil.which("sudo") or "/usr/bin/sudo" +IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables" +BASH = shutil.which("bash") or "/usr/bin/bash" +GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl" +TEE = shutil.which("tee") or "/usr/bin/tee" + +# IP address used in /etc/hosts for blocking domains. +HOSTS_REDIRECT_IP = ".".join(["0"] * 4) diff --git a/steam_backlog_enforcer/_total_block_iptables.py b/steam_backlog_enforcer/_total_block_iptables.py index 6f05228..c0fad81 100644 --- a/steam_backlog_enforcer/_total_block_iptables.py +++ b/steam_backlog_enforcer/_total_block_iptables.py @@ -159,11 +159,8 @@ def apply_total_block_iptables() -> bool: except OSError, subprocess.SubprocessError: logger.exception("Failed to apply total-block iptables rules") return False - else: - logger.info( - "Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips) - ) - return True + logger.info("Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips)) + return True def remove_total_block_iptables() -> bool: @@ -190,6 +187,5 @@ def remove_total_block_iptables() -> bool: except OSError, subprocess.SubprocessError: logger.exception("Failed to remove total-block iptables rules") return False - else: - _IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True) - return True + _IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True) + return True diff --git a/steam_backlog_enforcer/_web_server.py b/steam_backlog_enforcer/_web_server.py index 4fc958f..1eea8ec 100644 --- a/steam_backlog_enforcer/_web_server.py +++ b/steam_backlog_enforcer/_web_server.py @@ -61,7 +61,7 @@ _STALE_MSG = ( class _Handler(BaseHTTPRequestHandler): """Serve the dataset JSON and the static frontend bundle (read-only).""" - def log_message(self, fmt: str, *args: object) -> None: + def log_message(self, fmt: str, /, *args: object) -> None: """Route the default request log to ``logging`` at debug level.""" logger.debug("%s - %s", self.address_string(), fmt % args) diff --git a/steam_backlog_enforcer/config.py b/steam_backlog_enforcer/config.py index 4587359..1214321 100644 --- a/steam_backlog_enforcer/config.py +++ b/steam_backlog_enforcer/config.py @@ -3,7 +3,7 @@ from __future__ import annotations import contextlib -from dataclasses import dataclass, field +from dataclasses import dataclass, field, fields from datetime import UTC, datetime, timedelta import json import logging @@ -66,6 +66,11 @@ def _atomic_write(path: Path, data: str, *, mode: int | None = None) -> None: raise +def _field_names(cls: type) -> frozenset[str]: + """The dataclass's own field names, for filtering a loaded JSON object.""" + return frozenset(f.name for f in fields(cls)) + + @dataclass class Config: """User configuration.""" @@ -132,9 +137,7 @@ class Config: """Load config from disk, or return defaults.""" if CONFIG_FILE.exists(): data = json.loads(CONFIG_FILE.read_text(encoding="utf-8")) - return cls( - **{k: v for k, v in data.items() if k in cls.__dataclass_fields__} - ) + return cls(**{k: v for k, v in data.items() if k in _field_names(cls)}) return cls() @@ -146,14 +149,14 @@ class State: current_game_name: str = "" finished_app_ids: list[int] = field(default_factory=list) skipped_until: dict[str, str] = field(default_factory=dict) - enforcement_started_at: str = "" - """ISO-8601 UTC timestamp set on the first game assignment.""" """Map of ``str(app_id)`` → ISO-8601 UTC timestamp when the skip expires. Games in this map are excluded from auto-assignment until the timestamp elapses. Populated when the user declines a freshly-picked game via the interactive prompt in ``cmd_done``. """ + enforcement_started_at: str = "" + """ISO-8601 UTC timestamp set on the first game assignment.""" manual_pick_app_id: int | None = None manual_pick_game_name: str = "" manual_pick_started_at: str = "" @@ -214,9 +217,7 @@ class State: except json.JSONDecodeError, OSError, ValueError: logger.warning("Corrupt state file, using defaults.") return cls() - state = cls( - **{k: v for k, v in data.items() if k in cls.__dataclass_fields__} - ) + state = cls(**{k: v for k, v in data.items() if k in _field_names(cls)}) state._migrate_legacy_manual_pick() return state return cls() diff --git a/steam_backlog_enforcer/enforcer.py b/steam_backlog_enforcer/enforcer.py index c8d2188..2f596c9 100644 --- a/steam_backlog_enforcer/enforcer.py +++ b/steam_backlog_enforcer/enforcer.py @@ -99,8 +99,7 @@ def _kill_pid_by_name(pid: int, name: str) -> bool: except PermissionError: logger.exception("No permission to kill PID %d (%s).", pid, name) return False - else: - return True + return True def enforce_allowed_game( diff --git a/steam_backlog_enforcer/game_install.py b/steam_backlog_enforcer/game_install.py index e5b0abd..667f9b1 100644 --- a/steam_backlog_enforcer/game_install.py +++ b/steam_backlog_enforcer/game_install.py @@ -89,9 +89,8 @@ def _trigger_steam_install(app_id: int, label: str) -> bool: ) except FileNotFoundError, OSError, subprocess.TimeoutExpired: return False - else: - logger.info("Triggered Steam install for %s via protocol handler", label) - return True + logger.info("Triggered Steam install for %s via protocol handler", label) + return True # ────────────────────────────────────────────────────────────── diff --git a/steam_backlog_enforcer/protondb.py b/steam_backlog_enforcer/protondb.py index c3ba23c..a8ec318 100644 --- a/steam_backlog_enforcer/protondb.py +++ b/steam_backlog_enforcer/protondb.py @@ -90,7 +90,6 @@ class ProtonDBRating: return "" tier_rank = TIER_ORDER.get(self.tier, 99) - TIER_ORDER[MIN_PLAYABLE_TIER] silver_rank = TIER_ORDER["silver"] if not self.trending_tier: diff --git a/steam_backlog_enforcer/scanning.py b/steam_backlog_enforcer/scanning.py index 6b38f42..56056ad 100644 --- a/steam_backlog_enforcer/scanning.py +++ b/steam_backlog_enforcer/scanning.py @@ -95,9 +95,9 @@ def do_scan(config: Config, state: State) -> list[GameInfo]: pct = done * 100 // total bar_w = 30 filled = bar_w * done // total - bar = "█" * filled + "░" * (bar_w - filled) + meter = "█" * filled + "░" * (bar_w - filled) _echo( - f"\r HLTB [{bar}] {done}/{total} ({pct}%) " + f"\r HLTB [{meter}] {done}/{total} ({pct}%) " f"| {found} found | {name[:30]:<30s}", end="", flush=True, diff --git a/steam_backlog_enforcer/store_blocker.py b/steam_backlog_enforcer/store_blocker.py index c314ce7..047b174 100644 --- a/steam_backlog_enforcer/store_blocker.py +++ b/steam_backlog_enforcer/store_blocker.py @@ -12,8 +12,6 @@ blocks via iptables. from __future__ import annotations import logging -from pathlib import Path -import shutil import subprocess from steam_backlog_enforcer._hosts_protection import ( @@ -28,6 +26,12 @@ from steam_backlog_enforcer._store_iptables import ( _unblock_store_iptables, flush_dns_cache, ) +from steam_backlog_enforcer._store_tools import ( + BASH, + HOSTS_INSTALL_SCRIPT, + HOSTS_REDIRECT_IP, + SUDO, +) from steam_backlog_enforcer.config import ( BLOCKED_DOMAINS, HOSTS_FILE, @@ -35,33 +39,6 @@ from steam_backlog_enforcer.config import ( logger = logging.getLogger(__name__) -# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this -# module lives two levels below it); the script itself is in the -# linux_configuration checkout under testsAndMisc, not directly under $HOME. -_REPO_ROOT = Path(__file__).resolve().parents[2] -HOSTS_INSTALL_SCRIPT = ( - _REPO_ROOT - / "testsAndMisc" - / "linux_configuration" - / "scripts" - / "periodic_background" - / "hosts" - / "install.sh" -) - -# iptables chain name for our blocking rules. -IPTABLES_CHAIN = "STEAM_ENFORCER" - -# Resolved absolute paths for executables (avoids S607 partial-path warnings). -_SUDO = shutil.which("sudo") or "/usr/bin/sudo" -_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables" -_BASH = shutil.which("bash") or "/usr/bin/bash" -_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl" -_TEE = shutil.which("tee") or "/usr/bin/tee" - -# IP address used in /etc/hosts for blocking domains. -_HOSTS_REDIRECT_IP = ".".join(["0"] * 4) - def is_store_blocked() -> bool: """Check if Steam Store domains are blocked in /etc/hosts.""" @@ -75,7 +52,7 @@ def is_store_blocked() -> bool: if ( not stripped.startswith("#") and "store.steampowered.com" in stripped - and stripped.startswith(_HOSTS_REDIRECT_IP) + and stripped.startswith(HOSTS_REDIRECT_IP) ): return True except OSError: @@ -128,7 +105,7 @@ def _block_via_hosts_install() -> bool: try: logger.info("Running hosts install script to block Steam Store...") result = subprocess.run( - [_SUDO, _BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"], + [SUDO, BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"], capture_output=True, text=True, timeout=120, @@ -137,16 +114,15 @@ def _block_via_hosts_install() -> bool: except OSError, subprocess.SubprocessError: logger.exception("Failed to run hosts install script") return False - else: - if result.returncode == 0: - logger.info("hosts install script succeeded.") - return True - logger.error( - "hosts install script failed (rc=%d): %s", - result.returncode, - result.stderr[-500:] if result.stderr else result.stdout[-500:], - ) - return False + if result.returncode == 0: + logger.info("hosts install script succeeded.") + return True + logger.error( + "hosts install script failed (rc=%d): %s", + result.returncode, + result.stderr[-500:] if result.stderr else result.stdout[-500:], + ) + return False def unblock_store() -> bool: @@ -194,7 +170,7 @@ def _unblock_hosts() -> bool: stripped = line.strip() if ( not stripped.startswith("#") - and stripped.startswith(_HOSTS_REDIRECT_IP) + and stripped.startswith(HOSTS_REDIRECT_IP) and any(d in stripped for d in BLOCKED_DOMAINS) ): new_lines.append(f"# {line}" if line.endswith("\n") else f"# {line}\n") @@ -210,5 +186,4 @@ def _unblock_hosts() -> bool: except OSError: logger.exception("Failed to modify /etc/hosts") return False - else: - return True + return True diff --git a/steam_backlog_enforcer/tests/test_hltb.py b/steam_backlog_enforcer/tests/test_hltb.py index 39e1353..0741c2c 100644 --- a/steam_backlog_enforcer/tests/test_hltb.py +++ b/steam_backlog_enforcer/tests/test_hltb.py @@ -107,15 +107,16 @@ class TestGetHltbSearchUrl: url = _get_hltb_search_url() assert url == "https://howlongtobeat.com/api/finder" - def test_first_returns_none_second_returns_info(self) -> None: - """Test first returns none second returns info.""" + def test_passes_the_user_agent_the_library_now_requires(self) -> None: + """howlongtobeatpy 1.0.23 takes a user agent, not a parse-all flag.""" mock_info = MagicMock() mock_info.search_url = "/api/search/xyz" with patch("steam_backlog_enforcer._hltb_search_api.HTMLRequests") as mock_html: - mock_html.send_website_request_getcode.side_effect = [None, mock_info] + mock_html.send_website_request_getcode.return_value = mock_info mock_html.BASE_URL = "https://howlongtobeat.com" - url = _get_hltb_search_url() - assert url == "https://howlongtobeat.com/api/search/xyz" + _get_hltb_search_url() + (agent,) = mock_html.send_website_request_getcode.call_args.args + assert agent.startswith("Mozilla/5.0") def test_exception_fallback(self) -> None: """Test exception fallback.""" diff --git a/steam_backlog_enforcer/tests/test_hltb_pick_best_hltb_entry.py b/steam_backlog_enforcer/tests/test_hltb_pick_best_hltb_entry.py index 5662f65..4d29cb8 100644 --- a/steam_backlog_enforcer/tests/test_hltb_pick_best_hltb_entry.py +++ b/steam_backlog_enforcer/tests/test_hltb_pick_best_hltb_entry.py @@ -32,6 +32,17 @@ class TestPickBestHltbEntry: assert result is not None assert result[0]["game_name"] == "FAITH: The Unholy Trinity" + def test_keeps_the_longer_extended_edition(self) -> None: + """Two extended editions: the one with more completionist hours wins.""" + base: dict[str, Any] = {"game_name": "FAITH", "comp_100": 1800} + longer: dict[str, Any] = {"game_name": "FAITH: Chapter III", "comp_100": 9000} + shorter: dict[str, Any] = {"game_name": "FAITH: Chapter I", "comp_100": 3000} + result = _pick_best_hltb_entry( + "FAITH", [(base, 1.0), (longer, 0.7), (shorter, 0.9)] + ) + assert result is not None + assert result[0]["game_name"] == "FAITH: Chapter III" + def test_prefers_full_edition_dash(self) -> None: """Test prefers full edition dash.""" demo: dict[str, Any] = {"game_name": "FAITH", "comp_100": 1800}