mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-29 18:23:24 +01:00
Compare commits
No commits in common. "f38332527629c68c50af1b599d08cd85f4f3d45d" and "7323c896f60cd8f4c3c3a8e199da1b6b1a9daa83" have entirely different histories.
f383325276
...
7323c896f6
@ -16,15 +16,6 @@ Environment=STEAM_ENFORCER_DESKTOP_USER=__DESKTOP_USER__
|
|||||||
Environment=DISPLAY=:0
|
Environment=DISPLAY=:0
|
||||||
# Hardening: enforcer must not be easily killed.
|
# Hardening: enforcer must not be easily killed.
|
||||||
OOMScoreAdjust=-900
|
OOMScoreAdjust=-900
|
||||||
# Journal backstop. Steam's srt-logger runs in this unit's cgroup and mirrors
|
|
||||||
# Steam's console into journald; 2026-09-12 it wrote 481k "joystick FFB"
|
|
||||||
# lines in one boot (99% of the journal) and evicted two weeks of history.
|
|
||||||
# SRT_LOGGER_USE_JOURNAL=0 in the spawn env is the fix at source; these two
|
|
||||||
# make sure a future Steam that ignores it still cannot flood the journal.
|
|
||||||
LogFilterPatterns=~Failed to get joystick[0-9]+ FFB effect status
|
|
||||||
LogFilterPatterns=~FFBInterface
|
|
||||||
LogRateLimitIntervalSec=1min
|
|
||||||
LogRateLimitBurst=2000
|
|
||||||
#
|
#
|
||||||
# DO NOT ADD PrivateMounts=, PrivateTmp=, ProtectSystem= OR ProtectHome= HERE.
|
# DO NOT ADD PrivateMounts=, PrivateTmp=, ProtectSystem= OR ProtectHome= HERE.
|
||||||
# The daily gaming budget enforces its cutoff by bind-mounting a refusal stub
|
# The daily gaming budget enforces its cutoff by bind-mounting a refusal stub
|
||||||
|
|||||||
@ -141,19 +141,21 @@ def resolve_budget(config: Config) -> BudgetResolution:
|
|||||||
)
|
)
|
||||||
total = base + workout_seconds + leetcode_seconds
|
total = base + workout_seconds + leetcode_seconds
|
||||||
|
|
||||||
workout_part = _describe(
|
reason = "{:.1f}h: {}, {}".format(
|
||||||
|
total / _SECONDS_PER_HOUR,
|
||||||
|
_describe(
|
||||||
answer=workout,
|
answer=workout,
|
||||||
earned="workout counted",
|
earned="workout counted",
|
||||||
missed="no counted workout",
|
missed="no counted workout",
|
||||||
unknown="workout unknown (screen-locker unreachable)",
|
unknown="workout unknown (screen-locker unreachable)",
|
||||||
)
|
),
|
||||||
leetcode_part = _describe(
|
_describe(
|
||||||
answer=leetcode,
|
answer=leetcode,
|
||||||
earned="LeetCode solve recorded",
|
earned="LeetCode solve recorded",
|
||||||
missed="no LeetCode solve recorded",
|
missed="no LeetCode solve recorded",
|
||||||
unknown="LeetCode unknown (ledger and status API both unreadable)",
|
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)
|
logger.info("Gaming budget %s", reason)
|
||||||
return BudgetResolution(
|
return BudgetResolution(
|
||||||
seconds=total,
|
seconds=total,
|
||||||
|
|||||||
@ -7,11 +7,11 @@ import sys
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from steam_backlog_enforcer._hltb_cached import fetch_hltb_times_cached
|
from steam_backlog_enforcer._hltb_cached import fetch_hltb_times_cached
|
||||||
from steam_backlog_enforcer._hltb_confidence import (
|
from steam_backlog_enforcer._hltb_confidence import fetch_hltb_confidence_cached
|
||||||
refetch_poll_counts,
|
|
||||||
)
|
|
||||||
from steam_backlog_enforcer._hltb_types import (
|
from steam_backlog_enforcer._hltb_types import (
|
||||||
|
load_hltb_cache,
|
||||||
load_hltb_polls_cache,
|
load_hltb_polls_cache,
|
||||||
|
save_hltb_cache,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._snapshot import load_snapshot
|
from steam_backlog_enforcer._snapshot import load_snapshot
|
||||||
from steam_backlog_enforcer.game_install import (
|
from steam_backlog_enforcer.game_install import (
|
||||||
@ -83,7 +83,21 @@ def _backfill_polls_for_finished(
|
|||||||
return polls_cache
|
return polls_cache
|
||||||
|
|
||||||
_echo(f" Backfilling HLTB poll counts for {len(missing)} game(s)...")
|
_echo(f" Backfilling HLTB poll counts for {len(missing)} game(s)...")
|
||||||
return refetch_poll_counts(missing)
|
cache = load_hltb_cache()
|
||||||
|
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
|
||||||
|
for aid, _name in missing:
|
||||||
|
cache.pop(aid, None)
|
||||||
|
save_hltb_cache(cache, polls_cache)
|
||||||
|
|
||||||
|
fetch_hltb_confidence_cached(missing)
|
||||||
|
|
||||||
|
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
|
||||||
|
save_hltb_cache(refreshed_hours, refreshed_polls)
|
||||||
|
return refreshed_polls
|
||||||
|
|
||||||
|
|
||||||
def _report_assigned_confidence(
|
def _report_assigned_confidence(
|
||||||
|
|||||||
@ -70,13 +70,6 @@ def desktop_env_args(user: str, uid: int) -> list[str]:
|
|||||||
f"XAUTHORITY={xauth}",
|
f"XAUTHORITY={xauth}",
|
||||||
f"DBUS_SESSION_BUS_ADDRESS={dbus_addr}",
|
f"DBUS_SESSION_BUS_ADDRESS={dbus_addr}",
|
||||||
f"XDG_RUNTIME_DIR={runtime_dir}",
|
f"XDG_RUNTIME_DIR={runtime_dir}",
|
||||||
# Steam Runtime's srt-logger opts INTO the journal when it finds one
|
|
||||||
# (it inherits this unit's JOURNAL_STREAM), regardless of the DEVNULL
|
|
||||||
# stderr the spawn already uses. That wrote 481k "joystick FFB" lines
|
|
||||||
# in one boot and evicted two weeks of history from a 300M journal.
|
|
||||||
# Steam still keeps its own logs/console-linux.txt; this only stops
|
|
||||||
# the copy into journald.
|
|
||||||
"SRT_LOGGER_USE_JOURNAL=0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -70,21 +70,21 @@ def _allowed_names(state: State) -> str:
|
|||||||
return ", ".join(names) if names else "your assigned game"
|
return ", ".join(names) if names else "your assigned game"
|
||||||
|
|
||||||
|
|
||||||
def _guard_installed_games(allowed: set[int]) -> int:
|
def _guard_installed_games(allowed_app_ids: set[int]) -> int:
|
||||||
"""Remove any unauthorized game manifests + files. Runs every loop.
|
"""Remove any unauthorized game manifests + files. Runs every loop.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
allowed: Every app id that may stay installed — the assignment plus
|
allowed_app_ids: Every app id that may stay installed — the assignment
|
||||||
any concurrent manual picks.
|
plus any concurrent manual picks.
|
||||||
|
|
||||||
Returns number of games removed this pass.
|
Returns number of games removed this pass.
|
||||||
"""
|
"""
|
||||||
if not allowed:
|
if not allowed_app_ids:
|
||||||
return 0
|
return 0
|
||||||
installed = get_installed_games()
|
installed = get_installed_games()
|
||||||
count = 0
|
count = 0
|
||||||
for app_id, name in installed:
|
for app_id, name in installed:
|
||||||
if app_id in allowed:
|
if app_id in allowed_app_ids:
|
||||||
continue
|
continue
|
||||||
if is_protected_app(app_id):
|
if is_protected_app(app_id):
|
||||||
continue
|
continue
|
||||||
|
|||||||
@ -69,7 +69,7 @@ def _protected_name_stems() -> list[str]:
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return [name for _, name in allowed_games(State.load()) if name]
|
return [name for _, name in allowed_games(State.load()) if name]
|
||||||
except Exception: # pylint: disable=broad-exception-caught
|
except Exception:
|
||||||
logger.exception("Could not load allowed games for the deletion safety net")
|
logger.exception("Could not load allowed games for the deletion safety net")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|||||||
@ -7,6 +7,7 @@ under the 250-line cap.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
from steam_backlog_enforcer._hltb_types import (
|
from steam_backlog_enforcer._hltb_types import (
|
||||||
ProgressCb,
|
ProgressCb,
|
||||||
@ -18,7 +19,7 @@ from steam_backlog_enforcer._hltb_types import (
|
|||||||
load_hltb_rush_cache,
|
load_hltb_rush_cache,
|
||||||
save_hltb_cache,
|
save_hltb_cache,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer.hltb import fetch_hltb_times_timed, games_per_second
|
from steam_backlog_enforcer.hltb import fetch_hltb_times
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -55,20 +56,40 @@ def fetch_hltb_times_cached(
|
|||||||
len(uncached),
|
len(uncached),
|
||||||
len(games) - len(uncached),
|
len(games) - len(uncached),
|
||||||
)
|
)
|
||||||
elapsed = fetch_hltb_times_timed(uncached, cache, polls, progress_cb, extras)
|
t0 = time.monotonic()
|
||||||
|
fetch_hltb_times(
|
||||||
|
uncached,
|
||||||
|
cache=cache,
|
||||||
|
polls=polls,
|
||||||
|
progress_cb=progress_cb,
|
||||||
|
extras=extras,
|
||||||
|
)
|
||||||
|
elapsed = time.monotonic() - t0
|
||||||
|
|
||||||
# Final save.
|
# Final save.
|
||||||
save_hltb_cache(cache, polls, extras)
|
save_hltb_cache(cache, polls, extras)
|
||||||
|
|
||||||
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
|
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
|
||||||
|
rate = len(uncached) / elapsed if elapsed > 0 else 0
|
||||||
logger.info(
|
logger.info(
|
||||||
"HLTB fetch done: %d/%d found in %.1fs (%.0f games/s)",
|
"HLTB fetch done: %d/%d found in %.1fs (%.0f games/s)",
|
||||||
found,
|
found,
|
||||||
len(uncached),
|
len(uncached),
|
||||||
elapsed,
|
elapsed,
|
||||||
games_per_second(len(uncached), elapsed),
|
rate,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.info("All %d games found in HLTB cache.", len(games))
|
logger.info("All %d games found in HLTB cache.", len(games))
|
||||||
|
|
||||||
return cache
|
return cache
|
||||||
|
|
||||||
|
|
||||||
|
_REEXPORTED_TYPES = frozenset({"HLTB_BASE_URL"})
|
||||||
|
|
||||||
|
_MOVED_TO_HLTB_CONFIDENCE = frozenset(
|
||||||
|
{
|
||||||
|
"fetch_hltb_confidence_cached",
|
||||||
|
"fetch_hltb_detail_missing",
|
||||||
|
"get_hltb_submit_url",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|||||||
@ -19,14 +19,11 @@ from steam_backlog_enforcer._hltb_types import (
|
|||||||
load_hltb_leisure_100h_cache,
|
load_hltb_leisure_100h_cache,
|
||||||
load_hltb_polls_cache,
|
load_hltb_polls_cache,
|
||||||
load_hltb_rush_cache,
|
load_hltb_rush_cache,
|
||||||
restore_prior_hours,
|
|
||||||
save_hltb_cache,
|
save_hltb_cache,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer.hltb import (
|
from steam_backlog_enforcer.hltb import (
|
||||||
fetch_hltb_confidence,
|
fetch_hltb_confidence,
|
||||||
fetch_hltb_times,
|
fetch_hltb_times,
|
||||||
fetch_hltb_times_timed,
|
|
||||||
games_per_second,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -37,30 +34,6 @@ logger = logging.getLogger(__name__)
|
|||||||
# ──────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
def refetch_poll_counts(missing: list[tuple[int, str]]) -> dict[int, int]:
|
|
||||||
"""Re-search ``missing`` for poll counts and return the refreshed polls cache.
|
|
||||||
|
|
||||||
The search-level fetch skips anything already in the hours cache, so the
|
|
||||||
hours entries are dropped first to force it -- then put back where the
|
|
||||||
refetch found nothing better, since a prior leisure/DLC estimate is
|
|
||||||
trusted over a miss.
|
|
||||||
"""
|
|
||||||
cache = load_hltb_cache()
|
|
||||||
polls = load_hltb_polls_cache()
|
|
||||||
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
|
|
||||||
for aid, _name in missing:
|
|
||||||
cache.pop(aid, None)
|
|
||||||
save_hltb_cache(cache, polls)
|
|
||||||
|
|
||||||
fetch_hltb_confidence_cached(missing)
|
|
||||||
|
|
||||||
refreshed_hours = load_hltb_cache()
|
|
||||||
refreshed_polls = load_hltb_polls_cache()
|
|
||||||
restore_prior_hours(refreshed_hours, preserved_hours)
|
|
||||||
save_hltb_cache(refreshed_hours, refreshed_polls)
|
|
||||||
return refreshed_polls
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_hltb_confidence_cached(
|
def fetch_hltb_confidence_cached(
|
||||||
games: list[tuple[int, str]],
|
games: list[tuple[int, str]],
|
||||||
progress_cb: ProgressCb | None = None,
|
progress_cb: ProgressCb | None = None,
|
||||||
@ -169,19 +142,31 @@ def fetch_hltb_detail_missing(
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.info("Backfilling HLTB game ID for %d game(s)...", n_id)
|
logger.info("Backfilling HLTB game ID for %d game(s)...", n_id)
|
||||||
elapsed = fetch_hltb_times_timed(missing, cache, polls, progress_cb, extras)
|
t0 = time.monotonic()
|
||||||
|
fetch_hltb_times(
|
||||||
|
missing,
|
||||||
|
cache=cache,
|
||||||
|
polls=polls,
|
||||||
|
progress_cb=progress_cb,
|
||||||
|
extras=extras,
|
||||||
|
)
|
||||||
|
elapsed = time.monotonic() - t0
|
||||||
|
|
||||||
restore_prior_hours(cache, prior_hours)
|
# 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
|
||||||
|
|
||||||
save_hltb_cache(cache, polls, extras)
|
save_hltb_cache(cache, polls, extras)
|
||||||
|
|
||||||
fetched = sum(1 for app_id, _ in missing_rush if extras.rush.get(app_id, -1) > 0)
|
fetched = sum(1 for app_id, _ in missing_rush if extras.rush.get(app_id, -1) > 0)
|
||||||
|
rate = len(missing) / elapsed if elapsed > 0 else 0
|
||||||
logger.info(
|
logger.info(
|
||||||
"HLTB detail fetch done: %d/%d got rush data in %.1fs (%.0f games/s)",
|
"HLTB detail fetch done: %d/%d got rush data in %.1fs (%.0f games/s)",
|
||||||
fetched,
|
fetched,
|
||||||
len(missing_rush),
|
len(missing_rush),
|
||||||
elapsed,
|
elapsed,
|
||||||
games_per_second(len(missing), elapsed),
|
rate,
|
||||||
)
|
)
|
||||||
return fetched
|
return fetched
|
||||||
|
|
||||||
|
|||||||
@ -182,12 +182,9 @@ def _find_best_extended(
|
|||||||
entry_name = (entry.get("game_name") or "").lower()
|
entry_name = (entry.get("game_name") or "").lower()
|
||||||
if entry_name.startswith((lower + ":", lower + " -")):
|
if entry_name.startswith((lower + ":", lower + " -")):
|
||||||
suffix = entry_name[len(lower) :].lstrip(" :-")
|
suffix = entry_name[len(lower) :].lstrip(" :-")
|
||||||
if any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES):
|
if not any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES) and (
|
||||||
continue
|
best is None or entry.get("comp_100", 0) > best[0].get("comp_100", 0)
|
||||||
if best is not None and entry.get("comp_100", 0) <= best[0].get(
|
|
||||||
"comp_100", 0
|
|
||||||
):
|
):
|
||||||
continue
|
|
||||||
best = (entry, sim)
|
best = (entry, sim)
|
||||||
return best
|
return best
|
||||||
|
|
||||||
|
|||||||
@ -62,11 +62,12 @@ class _SearchCtx:
|
|||||||
headers: dict[str, str]
|
headers: dict[str, str]
|
||||||
cache: dict[int, float]
|
cache: dict[int, float]
|
||||||
polls: dict[int, int] = field(default_factory=dict)
|
polls: dict[int, int] = field(default_factory=dict)
|
||||||
extras: _HLTBExtras = field(default_factory=_HLTBExtras)
|
count_comp: dict[int, int] = field(default_factory=dict)
|
||||||
auth: _AuthInfo | None = None
|
auth: _AuthInfo | None = None
|
||||||
counter: dict[str, int] = field(default_factory=dict)
|
counter: dict[str, int] = field(default_factory=dict)
|
||||||
total: int = 0
|
total: int = 0
|
||||||
progress_cb: ProgressCb | None = None
|
progress_cb: ProgressCb | None = None
|
||||||
|
hltb_game_id: dict[int, int] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
async def _search_one(
|
async def _search_one(
|
||||||
@ -122,21 +123,25 @@ async def _search_one(
|
|||||||
if result is not None:
|
if result is not None:
|
||||||
ctx.cache[app_id] = result.completionist_hours
|
ctx.cache[app_id] = result.completionist_hours
|
||||||
ctx.polls[app_id] = result.comp_100_count
|
ctx.polls[app_id] = result.comp_100_count
|
||||||
ctx.extras.count_comp[app_id] = result.count_comp
|
ctx.count_comp[app_id] = result.count_comp
|
||||||
if result.hltb_game_id > 0:
|
if result.hltb_game_id > 0:
|
||||||
ctx.extras.hltb_game_id[app_id] = result.hltb_game_id
|
ctx.hltb_game_id[app_id] = result.hltb_game_id
|
||||||
ctx.counter["found"] += 1
|
ctx.counter["found"] += 1
|
||||||
else:
|
else:
|
||||||
ctx.cache[app_id] = -1
|
ctx.cache[app_id] = -1
|
||||||
ctx.polls[app_id] = 0
|
ctx.polls[app_id] = 0
|
||||||
ctx.extras.count_comp[app_id] = 0
|
ctx.count_comp[app_id] = 0
|
||||||
|
|
||||||
ctx.counter["done"] += 1
|
ctx.counter["done"] += 1
|
||||||
done = ctx.counter["done"]
|
done = ctx.counter["done"]
|
||||||
|
|
||||||
# Incremental save every _SAVE_INTERVAL lookups.
|
# Incremental save every _SAVE_INTERVAL lookups.
|
||||||
if not done % _SAVE_INTERVAL:
|
if not done % _SAVE_INTERVAL:
|
||||||
save_hltb_cache(ctx.cache, ctx.polls, ctx.extras)
|
save_hltb_cache(
|
||||||
|
ctx.cache,
|
||||||
|
ctx.polls,
|
||||||
|
_HLTBExtras(count_comp=ctx.count_comp, hltb_game_id=ctx.hltb_game_id),
|
||||||
|
)
|
||||||
|
|
||||||
# Report progress.
|
# Report progress.
|
||||||
if ctx.progress_cb is not None:
|
if ctx.progress_cb is not None:
|
||||||
@ -145,18 +150,17 @@ async def _search_one(
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def _search_batch(
|
async def _fetch_batch(
|
||||||
games: list[tuple[int, str]],
|
games: list[tuple[int, str]],
|
||||||
cache: dict[int, float],
|
cache: dict[int, float],
|
||||||
polls: dict[int, int],
|
polls: dict[int, int],
|
||||||
progress_cb: ProgressCb | None,
|
progress_cb: ProgressCb | None,
|
||||||
extras: _HLTBExtras,
|
extras: _HLTBExtras | None = None,
|
||||||
) -> list[HLTBResult]:
|
) -> list[HLTBResult]:
|
||||||
"""Run the search-level HLTB lookups for a batch through one session.
|
"""Fetch HLTB data for a batch of games using one shared session."""
|
||||||
|
if extras is None:
|
||||||
|
extras = _HLTBExtras()
|
||||||
|
|
||||||
Hours, poll counts and the extras come from the search results alone;
|
|
||||||
:func:`_fetch_batch` layers the per-game detail pages on top of this.
|
|
||||||
"""
|
|
||||||
# 1. Discover the search URL (sync, one-time).
|
# 1. Discover the search URL (sync, one-time).
|
||||||
search_url = _get_hltb_search_url()
|
search_url = _get_hltb_search_url()
|
||||||
logger.info("HLTB search URL: %s", search_url)
|
logger.info("HLTB search URL: %s", search_url)
|
||||||
@ -187,6 +191,9 @@ async def _search_batch(
|
|||||||
|
|
||||||
# 4. Fire all searches through a single persistent session.
|
# 4. Fire all searches through a single persistent session.
|
||||||
sem = asyncio.Semaphore(MAX_CONCURRENT)
|
sem = asyncio.Semaphore(MAX_CONCURRENT)
|
||||||
|
counter = {"done": 0, "found": 0}
|
||||||
|
total = len(games)
|
||||||
|
|
||||||
connector = aiohttp.TCPConnector(
|
connector = aiohttp.TCPConnector(
|
||||||
limit=MAX_CONCURRENT,
|
limit=MAX_CONCURRENT,
|
||||||
keepalive_timeout=30,
|
keepalive_timeout=30,
|
||||||
@ -201,29 +208,25 @@ async def _search_batch(
|
|||||||
headers=headers,
|
headers=headers,
|
||||||
cache=cache,
|
cache=cache,
|
||||||
polls=polls,
|
polls=polls,
|
||||||
extras=extras,
|
count_comp=extras.count_comp,
|
||||||
auth=auth,
|
auth=auth,
|
||||||
counter={"done": 0, "found": 0},
|
counter=counter,
|
||||||
total=len(games),
|
total=total,
|
||||||
progress_cb=progress_cb,
|
progress_cb=progress_cb,
|
||||||
|
hltb_game_id=extras.hltb_game_id,
|
||||||
)
|
)
|
||||||
tasks = [_search_one(sem, ctx, app_id, name) for app_id, name in games]
|
tasks = [
|
||||||
|
_search_one(
|
||||||
|
sem,
|
||||||
|
ctx,
|
||||||
|
app_id,
|
||||||
|
name,
|
||||||
|
)
|
||||||
|
for app_id, name in games
|
||||||
|
]
|
||||||
results = await asyncio.gather(*tasks)
|
results = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
return [r for r in results if r is not None]
|
search_results = [r for r in results if r is not None]
|
||||||
|
|
||||||
|
|
||||||
async def _fetch_batch(
|
|
||||||
games: list[tuple[int, str]],
|
|
||||||
cache: dict[int, float],
|
|
||||||
polls: dict[int, int],
|
|
||||||
progress_cb: ProgressCb | None,
|
|
||||||
extras: _HLTBExtras | None = None,
|
|
||||||
) -> list[HLTBResult]:
|
|
||||||
"""Fetch HLTB data for a batch of games using one shared session."""
|
|
||||||
if extras is None:
|
|
||||||
extras = _HLTBExtras()
|
|
||||||
search_results = await _search_batch(games, cache, polls, progress_cb, extras)
|
|
||||||
|
|
||||||
# 5. Fetch leisure times + DLC from game detail pages.
|
# 5. Fetch leisure times + DLC from game detail pages.
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@ -42,19 +42,20 @@ _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:
|
def _get_hltb_search_url() -> str:
|
||||||
"""Discover the current HLTB search API endpoint.
|
"""Discover the current HLTB search API endpoint.
|
||||||
|
|
||||||
Scrapes the homepage for JS bundles containing the fetch URL, walking
|
Scrapes the homepage for JS bundles containing the fetch URL.
|
||||||
every bundle until one names it (howlongtobeatpy >= 1.0.23 does that
|
Falls back to ``/api/finder`` if extraction fails.
|
||||||
itself; the older ``parse_all_scripts`` two-step is gone). Falls back to
|
|
||||||
``/api/finder`` if extraction fails.
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
search_info = HTMLRequests.send_website_request_getcode(_USER_AGENT)
|
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,
|
||||||
|
)
|
||||||
if search_info and search_info.search_url:
|
if search_info and search_info.search_url:
|
||||||
url: str = HTMLRequests.BASE_URL + search_info.search_url
|
url: str = HTMLRequests.BASE_URL + search_info.search_url
|
||||||
return url
|
return url
|
||||||
@ -71,7 +72,9 @@ async def _get_auth_info(
|
|||||||
init_url = search_url + "/init"
|
init_url = search_url + "/init"
|
||||||
ts = int(time.time() * 1000)
|
ts = int(time.time() * 1000)
|
||||||
headers = {
|
headers = {
|
||||||
"User-Agent": _USER_AGENT,
|
"User-Agent": (
|
||||||
|
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
|
||||||
|
),
|
||||||
"referer": "https://howlongtobeat.com/",
|
"referer": "https://howlongtobeat.com/",
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -136,17 +136,6 @@ def _read_raw_cache() -> dict[int, dict[str, Any]]:
|
|||||||
return out
|
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]:
|
def load_hltb_cache() -> dict[int, float]:
|
||||||
"""Load the hours portion of the HLTB cache.
|
"""Load the hours portion of the HLTB cache.
|
||||||
|
|
||||||
|
|||||||
@ -7,24 +7,44 @@ introduces no cycle. Split to keep both files under the 250-line cap.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
from steam_backlog_enforcer._store_tools import (
|
|
||||||
GUARDCTL,
|
|
||||||
SUDO,
|
|
||||||
TEE,
|
|
||||||
)
|
|
||||||
from steam_backlog_enforcer.config import (
|
from steam_backlog_enforcer.config import (
|
||||||
BLOCKED_DOMAINS,
|
BLOCKED_DOMAINS,
|
||||||
HOSTS_FILE,
|
HOSTS_FILE,
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from collections.abc import Callable
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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:
|
def _disable_hosts_protection() -> None:
|
||||||
"""Temporarily unlock /etc/hosts so its content can be edited.
|
"""Temporarily unlock /etc/hosts so its content can be edited.
|
||||||
@ -32,7 +52,7 @@ def _disable_hosts_protection() -> None:
|
|||||||
Guard-lib: stop watcher, collapse bind mount, chattr -i.
|
Guard-lib: stop watcher, collapse bind mount, chattr -i.
|
||||||
"""
|
"""
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, GUARDCTL, "file-guard", "pacman-unlock", "hosts"],
|
[_SUDO, _GUARDCTL, "file-guard", "pacman-unlock", "hosts"],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=10,
|
timeout=10,
|
||||||
check=False,
|
check=False,
|
||||||
@ -45,7 +65,7 @@ def _enable_hosts_protection() -> None:
|
|||||||
Guard-lib: chattr +i, reapply bind mount, restart watcher.
|
Guard-lib: chattr +i, reapply bind mount, restart watcher.
|
||||||
"""
|
"""
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, GUARDCTL, "file-guard", "sync", "hosts"],
|
[_SUDO, _GUARDCTL, "file-guard", "sync", "hosts"],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=10,
|
timeout=10,
|
||||||
check=False,
|
check=False,
|
||||||
@ -55,7 +75,7 @@ def _enable_hosts_protection() -> None:
|
|||||||
def _sudo_write_hosts(content: str) -> None:
|
def _sudo_write_hosts(content: str) -> None:
|
||||||
"""Write *content* to /etc/hosts via ``sudo tee``."""
|
"""Write *content* to /etc/hosts via ``sudo tee``."""
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, TEE, str(HOSTS_FILE)],
|
[_SUDO, _TEE, str(HOSTS_FILE)],
|
||||||
input=content.encode(),
|
input=content.encode(),
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=subprocess.DEVNULL,
|
||||||
timeout=10,
|
timeout=10,
|
||||||
@ -63,53 +83,32 @@ def _sudo_write_hosts(content: str) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def rewrite_hosts_lines(
|
def _reblock_hosts() -> bool:
|
||||||
rewrite: Callable[[str], str | None], done_message: str
|
"""Uncomment Steam Store entries in /etc/hosts."""
|
||||||
) -> bool:
|
|
||||||
"""Apply ``rewrite`` to every /etc/hosts line, under the protection dance.
|
|
||||||
|
|
||||||
``rewrite`` returns the replacement for a line, or ``None`` to keep it.
|
|
||||||
The file is only written -- and ``done_message`` only logged -- when a
|
|
||||||
line actually changed; protection is lifted before and restored after
|
|
||||||
either way.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Whether the edit (or the no-op) completed without an OSError.
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
_disable_hosts_protection()
|
_disable_hosts_protection()
|
||||||
content = HOSTS_FILE.read_text(encoding="utf-8")
|
content = HOSTS_FILE.read_text(encoding="utf-8")
|
||||||
new_lines = []
|
new_lines = []
|
||||||
changed = False
|
changed = False
|
||||||
for line in content.splitlines(keepends=True):
|
for line in content.splitlines(keepends=True):
|
||||||
replacement = rewrite(line)
|
stripped = line.strip()
|
||||||
if replacement is None:
|
if stripped.startswith("# ") and any(
|
||||||
new_lines.append(line)
|
d in stripped for d in BLOCKED_DOMAINS
|
||||||
else:
|
):
|
||||||
new_lines.append(replacement)
|
# Remove the '# ' prefix.
|
||||||
|
uncommented = line.replace("# ", "", 1)
|
||||||
|
new_lines.append(uncommented)
|
||||||
changed = True
|
changed = True
|
||||||
|
else:
|
||||||
|
new_lines.append(line)
|
||||||
|
|
||||||
if changed:
|
if changed:
|
||||||
_sudo_write_hosts("".join(new_lines))
|
_sudo_write_hosts("".join(new_lines))
|
||||||
logger.info(done_message)
|
logger.info("Re-enabled Steam Store entries in /etc/hosts.")
|
||||||
|
|
||||||
_enable_hosts_protection()
|
_enable_hosts_protection()
|
||||||
except OSError:
|
except OSError:
|
||||||
logger.exception("Failed to modify /etc/hosts")
|
logger.exception("Failed to modify /etc/hosts")
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _uncomment_blocked(line: str) -> str | None:
|
|
||||||
"""The line with its '# ' prefix removed, if it is a commented-out block."""
|
|
||||||
stripped = line.strip()
|
|
||||||
if stripped.startswith("# ") and any(d in stripped for d in BLOCKED_DOMAINS):
|
|
||||||
return line.replace("# ", "", 1)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _reblock_hosts() -> bool:
|
|
||||||
"""Uncomment Steam Store entries in /etc/hosts."""
|
|
||||||
return rewrite_hosts_lines(
|
|
||||||
_uncomment_blocked, "Re-enabled Steam Store entries in /etc/hosts."
|
|
||||||
)
|
|
||||||
|
|||||||
@ -32,20 +32,29 @@ transports, the memo, and the incident on total failure.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING
|
import time as time_module
|
||||||
|
from typing import TYPE_CHECKING, Final
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
from steam_backlog_enforcer._bonus_incident import report_leetcode_incident
|
from steam_backlog_enforcer._bonus_incident import report_leetcode_incident
|
||||||
from steam_backlog_enforcer._leetcode_ledger import read_ledger_solved_today
|
from steam_backlog_enforcer._leetcode_ledger import read_ledger_solved_today
|
||||||
from steam_backlog_enforcer._status_api import AnswerCache, get_status
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from steam_backlog_enforcer.config import Config
|
from steam_backlog_enforcer.config import Config
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_cache = AnswerCache()
|
_TIMEOUT_SECONDS: Final = 2.0
|
||||||
|
_CACHE_TTL_SECONDS: Final = 60.0
|
||||||
|
|
||||||
|
# Only successes are cached, matching _workout_budget: a failure is retried on
|
||||||
|
# the very next tick, so a restarted service takes effect immediately instead
|
||||||
|
# of costing an hour for another minute.
|
||||||
|
_cache: dict[str, tuple[float, bool]] = {}
|
||||||
|
|
||||||
|
|
||||||
def reset_cache() -> None:
|
def reset_cache() -> None:
|
||||||
@ -68,7 +77,22 @@ def _fetch_leetcode_today(url: str) -> bool:
|
|||||||
could not check.
|
could not check.
|
||||||
KeyError: The payload lacked the expected fields.
|
KeyError: The payload lacked the expected fields.
|
||||||
"""
|
"""
|
||||||
block = get_status(url)["leetcode"]
|
split = urlsplit(url)
|
||||||
|
conn = http.client.HTTPConnection(
|
||||||
|
split.hostname or "127.0.0.1",
|
||||||
|
split.port or 80,
|
||||||
|
timeout=_TIMEOUT_SECONDS,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
conn.request("GET", split.path or "/api/status")
|
||||||
|
resp = conn.getresponse()
|
||||||
|
body = resp.read()
|
||||||
|
if resp.status != http.HTTPStatus.OK:
|
||||||
|
msg = f"status {resp.status} {resp.reason}"
|
||||||
|
raise ValueError(msg)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
block = json.loads(body)["leetcode"]
|
||||||
if not block["checked"]:
|
if not block["checked"]:
|
||||||
# The server answered, but said it could not look. That is not a "no".
|
# The server answered, but said it could not look. That is not a "no".
|
||||||
msg = f"leetcode-guard could not check: {block.get('reason', 'no reason')}"
|
msg = f"leetcode-guard could not check: {block.get('reason', 'no reason')}"
|
||||||
@ -89,9 +113,10 @@ def leetcode_solved_today(config: Config) -> bool | None:
|
|||||||
incident while an honest "not solved yet" does not.
|
incident while an honest "not solved yet" does not.
|
||||||
"""
|
"""
|
||||||
url = config.leetcode_status_url
|
url = config.leetcode_status_url
|
||||||
cached = _cache.fresh(url)
|
now = time_module.monotonic()
|
||||||
if cached is not None:
|
cached = _cache.get(url)
|
||||||
return cached
|
if cached is not None and now - cached[0] < _CACHE_TTL_SECONDS:
|
||||||
|
return cached[1]
|
||||||
|
|
||||||
path = Path(config.leetcode_ledger_path).expanduser()
|
path = Path(config.leetcode_ledger_path).expanduser()
|
||||||
answer = read_ledger_solved_today(path)
|
answer = read_ledger_solved_today(path)
|
||||||
@ -100,7 +125,8 @@ def leetcode_solved_today(config: Config) -> bool | None:
|
|||||||
if answer is None:
|
if answer is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return _cache.store(url, answer=answer)
|
_cache[url] = (now, answer)
|
||||||
|
return answer
|
||||||
|
|
||||||
|
|
||||||
def _fallback_to_endpoint(url: str, path: Path) -> bool | None:
|
def _fallback_to_endpoint(url: str, path: Path) -> bool | None:
|
||||||
|
|||||||
@ -106,6 +106,7 @@ def get_all_owned_app_ids(config: Config) -> list[int]:
|
|||||||
return snapshot_ids
|
return snapshot_ids
|
||||||
logger.warning("Could not fetch owned game list for hiding.")
|
logger.warning("Could not fetch owned game list for hiding.")
|
||||||
return []
|
return []
|
||||||
|
else:
|
||||||
return merged_ids
|
return merged_ids
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -7,7 +7,7 @@ which is what lets the enforcer survive a restart mid-session.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field, fields
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import json
|
import json
|
||||||
import logging
|
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:
|
if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION:
|
||||||
logger.warning("Playtime state at %s has an unknown schema.", path)
|
logger.warning("Playtime state at %s has an unknown schema.", path)
|
||||||
return None
|
return None
|
||||||
known = {f.name for f in fields(PlaytimeState)}
|
fields = PlaytimeState.__dataclass_fields__
|
||||||
return PlaytimeState(**{k: v for k, v in data.items() if k in known})
|
return PlaytimeState(**{k: v for k, v in data.items() if k in fields})
|
||||||
|
|
||||||
|
|
||||||
def save_state(state: PlaytimeState, *, demo: bool) -> None:
|
def save_state(state: PlaytimeState, *, demo: bool) -> None:
|
||||||
|
|||||||
@ -9,11 +9,11 @@ import logging
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from steam_backlog_enforcer._echo import _echo
|
from steam_backlog_enforcer._echo import _echo
|
||||||
from steam_backlog_enforcer._hltb_confidence import (
|
from steam_backlog_enforcer._hltb_confidence import fetch_hltb_confidence_cached
|
||||||
refetch_poll_counts,
|
|
||||||
)
|
|
||||||
from steam_backlog_enforcer._hltb_types import (
|
from steam_backlog_enforcer._hltb_types import (
|
||||||
|
load_hltb_cache,
|
||||||
load_hltb_polls_cache,
|
load_hltb_polls_cache,
|
||||||
|
save_hltb_cache,
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -48,7 +48,25 @@ def _backfill_polls_for_finished(
|
|||||||
"Backfilling HLTB poll counts for %d already-finished games...",
|
"Backfilling HLTB poll counts for %d already-finished games...",
|
||||||
len(missing),
|
len(missing),
|
||||||
)
|
)
|
||||||
return refetch_poll_counts(missing)
|
# Force a fresh search by removing the hours entries we want to refetch.
|
||||||
|
# (fetch_hltb_times_cached skips entries already in the hours cache.)
|
||||||
|
cache = load_hltb_cache()
|
||||||
|
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
|
||||||
|
for aid, _name in missing:
|
||||||
|
cache.pop(aid, None)
|
||||||
|
save_hltb_cache(cache, polls_cache)
|
||||||
|
|
||||||
|
fetch_hltb_confidence_cached(missing)
|
||||||
|
|
||||||
|
# Restore any previously-known hours that the refetch may have replaced
|
||||||
|
# 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
|
||||||
|
save_hltb_cache(refreshed_hours, refreshed_polls)
|
||||||
|
return refreshed_polls
|
||||||
|
|
||||||
|
|
||||||
def _report_poll_confidence(
|
def _report_poll_confidence(
|
||||||
|
|||||||
@ -100,31 +100,6 @@ def _assign_chosen_game(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _clear_assignment(state: State, message: str) -> None:
|
|
||||||
"""Say why nothing could be assigned and leave the slot empty."""
|
|
||||||
_echo(message)
|
|
||||||
state.current_app_id = None
|
|
||||||
state.current_game_name = ""
|
|
||||||
state.save()
|
|
||||||
|
|
||||||
|
|
||||||
def _no_pick_message(confidence_skipped: int, linux_skipped: int) -> str:
|
|
||||||
"""Why the candidate pass produced nothing: confidence, or ProtonDB."""
|
|
||||||
if confidence_skipped > 0 and linux_skipped == 0:
|
|
||||||
return _NO_CONF_MSG
|
|
||||||
return "\nNo playable games left (all have poor ProtonDB ratings)!"
|
|
||||||
|
|
||||||
|
|
||||||
def _open_candidates(games: list[GameInfo], state: State) -> list[GameInfo]:
|
|
||||||
"""Unfinished, unskipped games, shortest first, with cached confidence."""
|
|
||||||
skip = set(state.finished_app_ids) | state.active_skipped_ids()
|
|
||||||
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
|
|
||||||
if candidates:
|
|
||||||
candidates.sort(key=_sort_key)
|
|
||||||
_apply_cached_confidence_to_candidates(candidates)
|
|
||||||
return candidates
|
|
||||||
|
|
||||||
|
|
||||||
def _pick_next_game_sequential(
|
def _pick_next_game_sequential(
|
||||||
games: list[GameInfo],
|
games: list[GameInfo],
|
||||||
state: State,
|
state: State,
|
||||||
@ -138,18 +113,29 @@ def _pick_next_game_sequential(
|
|||||||
``state`` for that game and the next candidate is evaluated.
|
``state`` for that game and the next candidate is evaluated.
|
||||||
"""
|
"""
|
||||||
while True:
|
while True:
|
||||||
candidates = _open_candidates(games, state)
|
skip = set(state.finished_app_ids) | state.active_skipped_ids()
|
||||||
|
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
|
||||||
if not candidates:
|
if not candidates:
|
||||||
_clear_assignment(state, _NO_CONF_MSG)
|
_echo(_NO_CONF_MSG)
|
||||||
|
state.current_app_id = None
|
||||||
|
state.current_game_name = ""
|
||||||
|
state.save()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
candidates.sort(key=_sort_key)
|
||||||
|
_apply_cached_confidence_to_candidates(candidates)
|
||||||
chosen, confidence_skipped, linux_skipped = _pick_next_shortest_candidate(
|
chosen, confidence_skipped, linux_skipped = _pick_next_shortest_candidate(
|
||||||
candidates
|
candidates
|
||||||
)
|
)
|
||||||
if chosen is None:
|
if chosen is None:
|
||||||
_clear_assignment(
|
_echo(
|
||||||
state, _no_pick_message(confidence_skipped, linux_skipped)
|
_NO_CONF_MSG
|
||||||
|
if confidence_skipped > 0 and linux_skipped == 0
|
||||||
|
else "\nNo playable games left (all have poor ProtonDB ratings)!"
|
||||||
)
|
)
|
||||||
|
state.current_app_id = None
|
||||||
|
state.current_game_name = ""
|
||||||
|
state.save()
|
||||||
return
|
return
|
||||||
|
|
||||||
if not on_select(chosen):
|
if not on_select(chosen):
|
||||||
|
|||||||
@ -32,7 +32,7 @@ def _sort_key(g: GameInfo) -> tuple[int, float]:
|
|||||||
"""Sort by known HLTB time (shortest first), then unknown games."""
|
"""Sort by known HLTB time (shortest first), then unknown games."""
|
||||||
if g.completionist_hours > 0:
|
if g.completionist_hours > 0:
|
||||||
return (0, g.completionist_hours)
|
return (0, g.completionist_hours)
|
||||||
return (1, hash(g.name.lower().encode().hex()))
|
return (1, g.name.lower().encode().hex().__hash__())
|
||||||
|
|
||||||
|
|
||||||
def _pick_playable_candidate(
|
def _pick_playable_candidate(
|
||||||
|
|||||||
@ -11,18 +11,18 @@ from steam_backlog_enforcer._hltb_types import (
|
|||||||
load_hltb_cache,
|
load_hltb_cache,
|
||||||
load_hltb_count_comp_cache,
|
load_hltb_count_comp_cache,
|
||||||
load_hltb_polls_cache,
|
load_hltb_polls_cache,
|
||||||
restore_prior_hours,
|
|
||||||
save_hltb_cache,
|
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
|
from steam_backlog_enforcer.game_install import _echo
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from steam_backlog_enforcer.steam_api import GameInfo
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@ -123,7 +123,9 @@ def _refresh_candidate_confidence_batch(
|
|||||||
refreshed_hours = load_hltb_cache()
|
refreshed_hours = load_hltb_cache()
|
||||||
refreshed_polls = load_hltb_polls_cache()
|
refreshed_polls = load_hltb_polls_cache()
|
||||||
refreshed_count_comp = load_hltb_count_comp_cache()
|
refreshed_count_comp = load_hltb_count_comp_cache()
|
||||||
restore_prior_hours(refreshed_hours, prior_hours)
|
for aid, old_hours in prior_hours.items():
|
||||||
|
if old_hours > 0 and refreshed_hours.get(aid, -1) <= 0:
|
||||||
|
refreshed_hours[aid] = old_hours
|
||||||
save_hltb_cache(
|
save_hltb_cache(
|
||||||
refreshed_hours, refreshed_polls, _HLTBExtras(count_comp=refreshed_count_comp)
|
refreshed_hours, refreshed_polls, _HLTBExtras(count_comp=refreshed_count_comp)
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1,88 +0,0 @@
|
|||||||
"""One loopback status-API read, shared by the workout and LeetCode bonuses.
|
|
||||||
|
|
||||||
Both bonuses ask a sibling daemon's ``/api/status`` endpoint over loopback and
|
|
||||||
reuse a successful answer for a minute. The transport and the cache policy
|
|
||||||
are identical, so they live here once; each bonus keeps only the field it
|
|
||||||
reads out of the payload.
|
|
||||||
|
|
||||||
Uses ``http.client`` rather than ``urllib.request`` deliberately, matching
|
|
||||||
``screen_locker._http_workout_fetch``: it takes a host and a path rather than a
|
|
||||||
URL, so there is no scheme for a bad config value to turn into a ``file://``
|
|
||||||
read, and no lint waiver is needed to say so.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import http.client
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
from typing import Any, Final
|
|
||||||
from urllib.parse import urlsplit
|
|
||||||
|
|
||||||
# Loopback, so a short timeout is generous. The daemon ticks frequently and
|
|
||||||
# must never block on this.
|
|
||||||
_TIMEOUT_SECONDS: Final = 2.0
|
|
||||||
|
|
||||||
# A successful answer is reused for this long. The daemon would otherwise make
|
|
||||||
# one HTTP call per tick, and the answer changes at most a few times a day. The
|
|
||||||
# cost is that a workout logged now raises the budget within a minute rather
|
|
||||||
# than instantly -- invisible next to a two-hour swing.
|
|
||||||
_CACHE_TTL_SECONDS: Final = 60.0
|
|
||||||
|
|
||||||
|
|
||||||
def get_status(url: str) -> dict[str, Any]:
|
|
||||||
"""GET a status endpoint and return its JSON body.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
url: The status endpoint, e.g. ``http://127.0.0.1:8770/api/status``.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
OSError: The endpoint could not be reached.
|
|
||||||
ValueError: The response was not usable JSON, or not a 200.
|
|
||||||
"""
|
|
||||||
split = urlsplit(url)
|
|
||||||
conn = http.client.HTTPConnection(
|
|
||||||
split.hostname or "127.0.0.1",
|
|
||||||
split.port or 80,
|
|
||||||
timeout=_TIMEOUT_SECONDS,
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
conn.request("GET", split.path or "/api/status")
|
|
||||||
resp = conn.getresponse()
|
|
||||||
body = resp.read()
|
|
||||||
if resp.status != http.HTTPStatus.OK:
|
|
||||||
msg = f"status {resp.status} {resp.reason}"
|
|
||||||
raise ValueError(msg)
|
|
||||||
finally:
|
|
||||||
conn.close()
|
|
||||||
payload: dict[str, Any] = json.loads(body)
|
|
||||||
return payload
|
|
||||||
|
|
||||||
|
|
||||||
class AnswerCache:
|
|
||||||
"""Successful answers by URL, each good for :data:`_CACHE_TTL_SECONDS`.
|
|
||||||
|
|
||||||
Only *successes* are stored. A failure is retried on the very next tick, so
|
|
||||||
a restarted status server takes effect immediately instead of serving the
|
|
||||||
floor for another minute.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
"""Start empty."""
|
|
||||||
self._entries: dict[str, tuple[float, bool]] = {}
|
|
||||||
|
|
||||||
def clear(self) -> None:
|
|
||||||
"""Drop every cached answer, forcing the next call to re-ask."""
|
|
||||||
self._entries.clear()
|
|
||||||
|
|
||||||
def fresh(self, url: str) -> bool | None:
|
|
||||||
"""The cached answer for ``url`` if it is still within its TTL."""
|
|
||||||
cached = self._entries.get(url)
|
|
||||||
if cached is not None and time.monotonic() - cached[0] < _CACHE_TTL_SECONDS:
|
|
||||||
return cached[1]
|
|
||||||
return None
|
|
||||||
|
|
||||||
def store(self, url: str, *, answer: bool) -> bool:
|
|
||||||
"""Remember ``answer`` for ``url`` as of now, and hand it back."""
|
|
||||||
self._entries[url] = (time.monotonic(), answer)
|
|
||||||
return answer
|
|
||||||
@ -77,6 +77,7 @@ class SteamAPIClient:
|
|||||||
except requests.RequestException as e:
|
except requests.RequestException as e:
|
||||||
msg = f"Steam API request failed: {e}"
|
msg = f"Steam API request failed: {e}"
|
||||||
raise SteamAPIError(msg) from e
|
raise SteamAPIError(msg) from e
|
||||||
|
else:
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def get_owned_games(self) -> list[dict[str, Any]]:
|
def get_owned_games(self) -> list[dict[str, Any]]:
|
||||||
|
|||||||
@ -20,7 +20,6 @@ from steam_backlog_enforcer._desktop_env import (
|
|||||||
resolve_desktop_user,
|
resolve_desktop_user,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._steam_launch import steam_is_installed
|
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
|
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -43,6 +42,7 @@ def _get_uid_gid_for_user(username: str) -> tuple[int, int]:
|
|||||||
pw = pwd.getpwnam(username)
|
pw = pwd.getpwnam(username)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return 1000, 1000
|
return 1000, 1000
|
||||||
|
else:
|
||||||
return pw.pw_uid, pw.pw_gid
|
return pw.pw_uid, pw.pw_gid
|
||||||
|
|
||||||
|
|
||||||
@ -106,7 +106,11 @@ def _ensure_steam_running() -> None:
|
|||||||
else:
|
else:
|
||||||
cmd = ["steam", "-silent"]
|
cmd = ["steam", "-silent"]
|
||||||
|
|
||||||
spawn_detached(cmd)
|
subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
# Give Steam time to initialize and start scanning manifests.
|
# Give Steam time to initialize and start scanning manifests.
|
||||||
time.sleep(15)
|
time.sleep(15)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
|
|||||||
@ -19,20 +19,6 @@ logger = logging.getLogger(__name__)
|
|||||||
_SPAWNED: list[subprocess.Popen[bytes]] = []
|
_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:
|
def _reap_spawned() -> None:
|
||||||
"""Clear out previously launched processes that have since exited.
|
"""Clear out previously launched processes that have since exited.
|
||||||
|
|
||||||
@ -63,4 +49,10 @@ def _run_as_user(cmd: list[str], user: str | None) -> None:
|
|||||||
return
|
return
|
||||||
full_cmd = desktop_user_cmd(cmd, user)
|
full_cmd = desktop_user_cmd(cmd, user)
|
||||||
|
|
||||||
_SPAWNED.append(spawn_detached(full_cmd))
|
_SPAWNED.append(
|
||||||
|
subprocess.Popen(
|
||||||
|
full_cmd,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|||||||
@ -9,26 +9,50 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import contextlib
|
import contextlib
|
||||||
import logging
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
import socket
|
import socket
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
from steam_backlog_enforcer._store_tools import (
|
|
||||||
IPTABLES,
|
|
||||||
IPTABLES_CHAIN,
|
|
||||||
SUDO,
|
|
||||||
)
|
|
||||||
from steam_backlog_enforcer.config import (
|
from steam_backlog_enforcer.config import (
|
||||||
BLOCKED_DOMAINS,
|
BLOCKED_DOMAINS,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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:
|
def _is_iptables_blocked() -> bool:
|
||||||
"""Check if our iptables chain exists and has rules."""
|
"""Check if our iptables chain exists and has rules."""
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
[SUDO, IPTABLES, "-L", IPTABLES_CHAIN, "-n"],
|
[_SUDO, _IPTABLES, "-L", IPTABLES_CHAIN, "-n"],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
@ -36,6 +60,7 @@ def _is_iptables_blocked() -> bool:
|
|||||||
)
|
)
|
||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
return result.returncode == 0 and "DROP" in result.stdout
|
return result.returncode == 0 and "DROP" in result.stdout
|
||||||
|
|
||||||
|
|
||||||
@ -44,14 +69,14 @@ def _block_store_iptables() -> bool:
|
|||||||
try:
|
try:
|
||||||
# Create chain if it doesn't exist.
|
# Create chain if it doesn't exist.
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, IPTABLES, "-N", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-N", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
# Flush existing rules in our chain.
|
# Flush existing rules in our chain.
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, IPTABLES, "-F", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=True,
|
check=True,
|
||||||
@ -68,8 +93,8 @@ def _block_store_iptables() -> bool:
|
|||||||
for ip in blocked_ips:
|
for ip in blocked_ips:
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[
|
[
|
||||||
SUDO,
|
_SUDO,
|
||||||
IPTABLES,
|
_IPTABLES,
|
||||||
"-A",
|
"-A",
|
||||||
IPTABLES_CHAIN,
|
IPTABLES_CHAIN,
|
||||||
"-d",
|
"-d",
|
||||||
@ -84,14 +109,14 @@ def _block_store_iptables() -> bool:
|
|||||||
|
|
||||||
# Hook our chain into OUTPUT if not already there.
|
# Hook our chain into OUTPUT if not already there.
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
[SUDO, IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=True,
|
check=True,
|
||||||
@ -99,6 +124,7 @@ def _block_store_iptables() -> bool:
|
|||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
logger.exception("Failed to block store via iptables")
|
logger.exception("Failed to block store via iptables")
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips))
|
logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@ -107,19 +133,19 @@ def _unblock_store_iptables() -> bool:
|
|||||||
"""Remove iptables-based block."""
|
"""Remove iptables-based block."""
|
||||||
try:
|
try:
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, IPTABLES, "-F", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[SUDO, IPTABLES, "-X", IPTABLES_CHAIN],
|
[_SUDO, _IPTABLES, "-X", IPTABLES_CHAIN],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
check=False,
|
check=False,
|
||||||
@ -127,6 +153,7 @@ def _unblock_store_iptables() -> bool:
|
|||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
logger.exception("Failed to unblock iptables")
|
logger.exception("Failed to unblock iptables")
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
logger.info("Steam Store unblocked from iptables.")
|
logger.info("Steam Store unblocked from iptables.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|||||||
@ -1,38 +0,0 @@
|
|||||||
"""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)
|
|
||||||
@ -11,16 +11,16 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
from steam_backlog_enforcer._hosts_protection import (
|
|
||||||
_disable_hosts_protection,
|
|
||||||
_enable_hosts_protection,
|
|
||||||
_sudo_write_hosts,
|
|
||||||
)
|
|
||||||
from steam_backlog_enforcer._total_block_domains import (
|
from steam_backlog_enforcer._total_block_domains import (
|
||||||
_ALL_TOTAL_BLOCK_DOMAINS,
|
_ALL_TOTAL_BLOCK_DOMAINS,
|
||||||
NULL_ROUTE_IP,
|
NULL_ROUTE_IP,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer.config import HOSTS_FILE
|
from steam_backlog_enforcer.config import HOSTS_FILE
|
||||||
|
from steam_backlog_enforcer.store_blocker import (
|
||||||
|
_disable_hosts_protection,
|
||||||
|
_enable_hosts_protection,
|
||||||
|
_sudo_write_hosts,
|
||||||
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|||||||
@ -159,7 +159,10 @@ def apply_total_block_iptables() -> bool:
|
|||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
logger.exception("Failed to apply total-block iptables rules")
|
logger.exception("Failed to apply total-block iptables rules")
|
||||||
return False
|
return False
|
||||||
logger.info("Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips))
|
else:
|
||||||
|
logger.info(
|
||||||
|
"Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips)
|
||||||
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@ -187,5 +190,6 @@ def remove_total_block_iptables() -> bool:
|
|||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
logger.exception("Failed to remove total-block iptables rules")
|
logger.exception("Failed to remove total-block iptables rules")
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
_IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True)
|
_IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True)
|
||||||
return True
|
return True
|
||||||
|
|||||||
@ -61,7 +61,7 @@ _STALE_MSG = (
|
|||||||
class _Handler(BaseHTTPRequestHandler):
|
class _Handler(BaseHTTPRequestHandler):
|
||||||
"""Serve the dataset JSON and the static frontend bundle (read-only)."""
|
"""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."""
|
"""Route the default request log to ``logging`` at debug level."""
|
||||||
logger.debug("%s - %s", self.address_string(), fmt % args)
|
logger.debug("%s - %s", self.address_string(), fmt % args)
|
||||||
|
|
||||||
|
|||||||
@ -6,9 +6,22 @@ from collections import Counter
|
|||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
import re
|
import re
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from steam_backlog_enforcer.config import CONFIG_DIR
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# File paths (patched in tests via conftest)
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
APPROVED_EXCEPTIONS_FILE: Path = CONFIG_DIR / "approved_exceptions.json"
|
||||||
|
EXCEPTION_AUDIT_LOG: Path = CONFIG_DIR / "exception_audit.log"
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────
|
||||||
# Constants
|
# Constants
|
||||||
# ──────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@ -35,6 +35,16 @@ logger = logging.getLogger(__name__)
|
|||||||
APPROVED_EXCEPTIONS_FILE: Path = CONFIG_DIR / "approved_exceptions.json"
|
APPROVED_EXCEPTIONS_FILE: Path = CONFIG_DIR / "approved_exceptions.json"
|
||||||
EXCEPTION_AUDIT_LOG: Path = CONFIG_DIR / "exception_audit.log"
|
EXCEPTION_AUDIT_LOG: Path = CONFIG_DIR / "exception_audit.log"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# Constants
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_MIN_REASON_WORDS: int = 5
|
||||||
|
_MIN_REASON_LENGTH: int = 25
|
||||||
|
_MIN_ENTROPY: float = 3.0
|
||||||
|
# Reject runs of the same character longer than this (e.g. "aaaa").
|
||||||
|
_MAX_CHAR_RUN: int = 3
|
||||||
|
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────
|
||||||
# Reason validation
|
# Reason validation
|
||||||
|
|||||||
@ -11,21 +11,42 @@ malformed body, non-200 -- yields ``None``, logged at warning with the concrete
|
|||||||
reason, and the caller grants no workout bonus. Failing open would let the
|
reason, and the caller grants no workout bonus. Failing open would let the
|
||||||
whole coupling be defeated by stopping one user service, and a silent bonus
|
whole coupling be defeated by stopping one user service, and a silent bonus
|
||||||
would be indistinguishable from an earned one.
|
would be indistinguishable from an earned one.
|
||||||
|
|
||||||
|
Uses ``http.client`` rather than ``urllib.request`` deliberately, matching
|
||||||
|
``screen_locker._http_workout_fetch``: it takes a host and a path rather than a
|
||||||
|
URL, so there is no scheme for a bad config value to turn into a ``file://``
|
||||||
|
read, and no lint waiver is needed to say so.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
from typing import TYPE_CHECKING
|
import time
|
||||||
|
from typing import TYPE_CHECKING, Final
|
||||||
from steam_backlog_enforcer._status_api import AnswerCache, get_status
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from steam_backlog_enforcer.config import Config
|
from steam_backlog_enforcer.config import Config
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_cache = AnswerCache()
|
# Loopback, so a short timeout is generous. The daemon ticks frequently and
|
||||||
|
# must never block on this.
|
||||||
|
_TIMEOUT_SECONDS: Final = 2.0
|
||||||
|
|
||||||
|
# A successful answer is reused for this long. The daemon would otherwise make
|
||||||
|
# one HTTP call per tick, and the answer changes at most a few times a day. The
|
||||||
|
# cost is that a workout logged now raises the budget within a minute rather
|
||||||
|
# than instantly -- invisible next to a two-hour swing.
|
||||||
|
_CACHE_TTL_SECONDS: Final = 60.0
|
||||||
|
|
||||||
|
# Only *successes* are cached. A failure is retried on the very next tick, so a
|
||||||
|
# restarted status server takes effect immediately instead of serving the floor
|
||||||
|
# for another minute. A dict rather than a module global so no function here
|
||||||
|
# needs a `global` statement to write it.
|
||||||
|
_cache: dict[str, tuple[float, bool]] = {}
|
||||||
|
|
||||||
|
|
||||||
def reset_cache() -> None:
|
def reset_cache() -> None:
|
||||||
@ -47,7 +68,22 @@ def _fetch_workout_today(url: str) -> bool:
|
|||||||
ValueError: The response was not usable JSON, or not a 200.
|
ValueError: The response was not usable JSON, or not a 200.
|
||||||
KeyError: The payload lacked the expected fields.
|
KeyError: The payload lacked the expected fields.
|
||||||
"""
|
"""
|
||||||
return bool(get_status(url)["gaming"]["workout_today"])
|
split = urlsplit(url)
|
||||||
|
conn = http.client.HTTPConnection(
|
||||||
|
split.hostname or "127.0.0.1",
|
||||||
|
split.port or 80,
|
||||||
|
timeout=_TIMEOUT_SECONDS,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
conn.request("GET", split.path or "/api/status")
|
||||||
|
resp = conn.getresponse()
|
||||||
|
body = resp.read()
|
||||||
|
if resp.status != http.HTTPStatus.OK:
|
||||||
|
msg = f"status {resp.status} {resp.reason}"
|
||||||
|
raise ValueError(msg)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return bool(json.loads(body)["gaming"]["workout_today"])
|
||||||
|
|
||||||
|
|
||||||
def workout_logged_today(config: Config) -> bool | None:
|
def workout_logged_today(config: Config) -> bool | None:
|
||||||
@ -62,9 +98,10 @@ def workout_logged_today(config: Config) -> bool | None:
|
|||||||
distinct from ``False`` so the caller can log which one happened.
|
distinct from ``False`` so the caller can log which one happened.
|
||||||
"""
|
"""
|
||||||
url = config.workout_status_url
|
url = config.workout_status_url
|
||||||
cached = _cache.fresh(url)
|
now = time.monotonic()
|
||||||
if cached is not None:
|
cached = _cache.get(url)
|
||||||
return cached
|
if cached is not None and now - cached[0] < _CACHE_TTL_SECONDS:
|
||||||
|
return cached[1]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
answer = _fetch_workout_today(url)
|
answer = _fetch_workout_today(url)
|
||||||
@ -86,4 +123,5 @@ def workout_logged_today(config: Config) -> bool | None:
|
|||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return _cache.store(url, answer=answer)
|
_cache[url] = (now, answer)
|
||||||
|
return answer
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import contextlib
|
import contextlib
|
||||||
from dataclasses import dataclass, field, fields
|
from dataclasses import dataclass, field
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@ -66,11 +66,6 @@ def _atomic_write(path: Path, data: str, *, mode: int | None = None) -> None:
|
|||||||
raise
|
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
|
@dataclass
|
||||||
class Config:
|
class Config:
|
||||||
"""User configuration."""
|
"""User configuration."""
|
||||||
@ -137,7 +132,9 @@ class Config:
|
|||||||
"""Load config from disk, or return defaults."""
|
"""Load config from disk, or return defaults."""
|
||||||
if CONFIG_FILE.exists():
|
if CONFIG_FILE.exists():
|
||||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||||
return cls(**{k: v for k, v in data.items() if k in _field_names(cls)})
|
return cls(
|
||||||
|
**{k: v for k, v in data.items() if k in cls.__dataclass_fields__}
|
||||||
|
)
|
||||||
return cls()
|
return cls()
|
||||||
|
|
||||||
|
|
||||||
@ -149,14 +146,14 @@ class State:
|
|||||||
current_game_name: str = ""
|
current_game_name: str = ""
|
||||||
finished_app_ids: list[int] = field(default_factory=list)
|
finished_app_ids: list[int] = field(default_factory=list)
|
||||||
skipped_until: dict[str, str] = field(default_factory=dict)
|
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.
|
"""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
|
Games in this map are excluded from auto-assignment until the timestamp
|
||||||
elapses. Populated when the user declines a freshly-picked game via the
|
elapses. Populated when the user declines a freshly-picked game via the
|
||||||
interactive prompt in ``cmd_done``.
|
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_app_id: int | None = None
|
||||||
manual_pick_game_name: str = ""
|
manual_pick_game_name: str = ""
|
||||||
manual_pick_started_at: str = ""
|
manual_pick_started_at: str = ""
|
||||||
@ -217,7 +214,9 @@ class State:
|
|||||||
except json.JSONDecodeError, OSError, ValueError:
|
except json.JSONDecodeError, OSError, ValueError:
|
||||||
logger.warning("Corrupt state file, using defaults.")
|
logger.warning("Corrupt state file, using defaults.")
|
||||||
return cls()
|
return cls()
|
||||||
state = cls(**{k: v for k, v in data.items() if k in _field_names(cls)})
|
state = cls(
|
||||||
|
**{k: v for k, v in data.items() if k in cls.__dataclass_fields__}
|
||||||
|
)
|
||||||
state._migrate_legacy_manual_pick()
|
state._migrate_legacy_manual_pick()
|
||||||
return state
|
return state
|
||||||
return cls()
|
return cls()
|
||||||
|
|||||||
@ -99,6 +99,7 @@ def _kill_pid_by_name(pid: int, name: str) -> bool:
|
|||||||
except PermissionError:
|
except PermissionError:
|
||||||
logger.exception("No permission to kill PID %d (%s).", pid, name)
|
logger.exception("No permission to kill PID %d (%s).", pid, name)
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -89,6 +89,7 @@ def _trigger_steam_install(app_id: int, label: str) -> bool:
|
|||||||
)
|
)
|
||||||
except FileNotFoundError, OSError, subprocess.TimeoutExpired:
|
except FileNotFoundError, OSError, subprocess.TimeoutExpired:
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
logger.info("Triggered Steam install for %s via protocol handler", label)
|
logger.info("Triggered Steam install for %s via protocol handler", label)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|||||||
@ -14,10 +14,18 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import time
|
|
||||||
|
|
||||||
from steam_backlog_enforcer._hltb_search import _fetch_batch, _search_batch
|
import aiohttp
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._hltb_search import (
|
||||||
|
_fetch_batch,
|
||||||
|
_get_auth_info,
|
||||||
|
_get_hltb_search_url,
|
||||||
|
_search_one,
|
||||||
|
_SearchCtx,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer._hltb_types import (
|
from steam_backlog_enforcer._hltb_types import (
|
||||||
|
MAX_CONCURRENT,
|
||||||
HLTBResult,
|
HLTBResult,
|
||||||
ProgressCb,
|
ProgressCb,
|
||||||
_HLTBExtras,
|
_HLTBExtras,
|
||||||
@ -37,8 +45,74 @@ async def _fetch_batch_confidence_only(
|
|||||||
count_comp: dict[int, int] | None = None,
|
count_comp: dict[int, int] | None = None,
|
||||||
) -> list[HLTBResult]:
|
) -> list[HLTBResult]:
|
||||||
"""Fetch only search-level HLTB data (hours + confidence), no detail pages."""
|
"""Fetch only search-level HLTB data (hours + confidence), no detail pages."""
|
||||||
extras = _HLTBExtras(count_comp=count_comp if count_comp is not None else {})
|
# 1. Discover the search URL (sync, one-time).
|
||||||
return await _search_batch(games, cache, polls, progress_cb, extras)
|
search_url = _get_hltb_search_url()
|
||||||
|
logger.info("HLTB search URL: %s", search_url)
|
||||||
|
|
||||||
|
timeout = aiohttp.ClientTimeout(total=20, sock_read=15)
|
||||||
|
|
||||||
|
# 2. Get auth info (separate session — avoids reuse issues).
|
||||||
|
async with aiohttp.ClientSession(timeout=timeout) as init_session:
|
||||||
|
auth = await _get_auth_info(search_url, init_session)
|
||||||
|
if auth is None:
|
||||||
|
logger.warning("Could not get HLTB auth info, aborting fetch.")
|
||||||
|
return []
|
||||||
|
logger.info("HLTB auth token acquired.")
|
||||||
|
|
||||||
|
# 3. Build shared headers for all search requests.
|
||||||
|
headers: dict[str, str] = {
|
||||||
|
"content-type": "application/json",
|
||||||
|
"accept": "*/*",
|
||||||
|
"User-Agent": (
|
||||||
|
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
|
||||||
|
),
|
||||||
|
"referer": "https://howlongtobeat.com/",
|
||||||
|
"x-auth-token": auth.token,
|
||||||
|
}
|
||||||
|
if auth.hp_key:
|
||||||
|
headers["x-hp-key"] = auth.hp_key
|
||||||
|
headers["x-hp-val"] = auth.hp_val
|
||||||
|
|
||||||
|
# 4. Fire all searches through a single persistent session.
|
||||||
|
sem = asyncio.Semaphore(MAX_CONCURRENT)
|
||||||
|
counter = {"done": 0, "found": 0}
|
||||||
|
total = len(games)
|
||||||
|
|
||||||
|
if count_comp is None:
|
||||||
|
count_comp = {}
|
||||||
|
|
||||||
|
connector = aiohttp.TCPConnector(
|
||||||
|
limit=MAX_CONCURRENT,
|
||||||
|
keepalive_timeout=30,
|
||||||
|
)
|
||||||
|
async with aiohttp.ClientSession(
|
||||||
|
timeout=timeout,
|
||||||
|
connector=connector,
|
||||||
|
) as session:
|
||||||
|
ctx = _SearchCtx(
|
||||||
|
session=session,
|
||||||
|
search_url=search_url,
|
||||||
|
headers=headers,
|
||||||
|
cache=cache,
|
||||||
|
polls=polls,
|
||||||
|
count_comp=count_comp,
|
||||||
|
auth=auth,
|
||||||
|
counter=counter,
|
||||||
|
total=total,
|
||||||
|
progress_cb=progress_cb,
|
||||||
|
)
|
||||||
|
tasks = [
|
||||||
|
_search_one(
|
||||||
|
sem,
|
||||||
|
ctx,
|
||||||
|
app_id,
|
||||||
|
name,
|
||||||
|
)
|
||||||
|
for app_id, name in games
|
||||||
|
]
|
||||||
|
results = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
return [r for r in results if r is not None]
|
||||||
|
|
||||||
|
|
||||||
def fetch_hltb_times(
|
def fetch_hltb_times(
|
||||||
@ -66,26 +140,6 @@ def fetch_hltb_times(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def fetch_hltb_times_timed(
|
|
||||||
games: list[tuple[int, str]],
|
|
||||||
cache: dict[int, float],
|
|
||||||
polls: dict[int, int],
|
|
||||||
progress_cb: ProgressCb | None,
|
|
||||||
extras: _HLTBExtras,
|
|
||||||
) -> float:
|
|
||||||
"""Run :func:`fetch_hltb_times` into the given caches; return the seconds taken."""
|
|
||||||
t0 = time.monotonic()
|
|
||||||
fetch_hltb_times(
|
|
||||||
games, cache=cache, polls=polls, progress_cb=progress_cb, extras=extras
|
|
||||||
)
|
|
||||||
return time.monotonic() - t0
|
|
||||||
|
|
||||||
|
|
||||||
def games_per_second(count: int, elapsed: float) -> float:
|
|
||||||
"""Throughput for a completion log line; 0 when nothing was timed."""
|
|
||||||
return count / elapsed if elapsed > 0 else 0
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_hltb_confidence(
|
def fetch_hltb_confidence(
|
||||||
games: list[tuple[int, str]],
|
games: list[tuple[int, str]],
|
||||||
cache: dict[int, float] | None = None,
|
cache: dict[int, float] | None = None,
|
||||||
|
|||||||
@ -90,6 +90,7 @@ class ProtonDBRating:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
tier_rank = TIER_ORDER.get(self.tier, 99)
|
tier_rank = TIER_ORDER.get(self.tier, 99)
|
||||||
|
TIER_ORDER[MIN_PLAYABLE_TIER]
|
||||||
silver_rank = TIER_ORDER["silver"]
|
silver_rank = TIER_ORDER["silver"]
|
||||||
|
|
||||||
if not self.trending_tier:
|
if not self.trending_tier:
|
||||||
|
|||||||
@ -15,9 +15,6 @@ from steam_backlog_enforcer._pick_completion import mark_finished, report_comple
|
|||||||
from steam_backlog_enforcer._scanning_assign import (
|
from steam_backlog_enforcer._scanning_assign import (
|
||||||
_NO_CONF_MSG,
|
_NO_CONF_MSG,
|
||||||
_assign_chosen_game,
|
_assign_chosen_game,
|
||||||
_clear_assignment,
|
|
||||||
_no_pick_message,
|
|
||||||
_open_candidates,
|
|
||||||
_pick_next_game_sequential,
|
_pick_next_game_sequential,
|
||||||
_prompt_user_pick,
|
_prompt_user_pick,
|
||||||
)
|
)
|
||||||
@ -26,8 +23,10 @@ from steam_backlog_enforcer._scanning_candidates import (
|
|||||||
_collect_top_candidates,
|
_collect_top_candidates,
|
||||||
_pick_next_shortest_candidate,
|
_pick_next_shortest_candidate,
|
||||||
_pick_playable_candidate,
|
_pick_playable_candidate,
|
||||||
|
_sort_key,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._scanning_confidence import (
|
from steam_backlog_enforcer._scanning_confidence import (
|
||||||
|
_apply_cached_confidence_to_candidates,
|
||||||
_report_poll_confidence,
|
_report_poll_confidence,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._scanning_tampering import (
|
from steam_backlog_enforcer._scanning_tampering import (
|
||||||
@ -96,9 +95,9 @@ def do_scan(config: Config, state: State) -> list[GameInfo]:
|
|||||||
pct = done * 100 // total
|
pct = done * 100 // total
|
||||||
bar_w = 30
|
bar_w = 30
|
||||||
filled = bar_w * done // total
|
filled = bar_w * done // total
|
||||||
meter = "█" * filled + "░" * (bar_w - filled)
|
bar = "█" * filled + "░" * (bar_w - filled)
|
||||||
_echo(
|
_echo(
|
||||||
f"\r HLTB [{meter}] {done}/{total} ({pct}%) "
|
f"\r HLTB [{bar}] {done}/{total} ({pct}%) "
|
||||||
f"| {found} found | {name[:30]:<30s}",
|
f"| {found} found | {name[:30]:<30s}",
|
||||||
end="",
|
end="",
|
||||||
flush=True,
|
flush=True,
|
||||||
@ -164,16 +163,31 @@ def pick_next_game(
|
|||||||
_pick_next_game_sequential(games, state, config, on_select)
|
_pick_next_game_sequential(games, state, config, on_select)
|
||||||
return
|
return
|
||||||
|
|
||||||
candidates = _open_candidates(games, state)
|
skip = set(state.finished_app_ids) | state.active_skipped_ids()
|
||||||
|
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
|
||||||
|
|
||||||
if not candidates:
|
if not candidates:
|
||||||
_clear_assignment(state, _NO_CONF_MSG)
|
_echo(_NO_CONF_MSG)
|
||||||
|
state.current_app_id = None
|
||||||
|
state.current_game_name = ""
|
||||||
|
state.save()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
candidates.sort(key=_sort_key)
|
||||||
|
_apply_cached_confidence_to_candidates(candidates)
|
||||||
qualified, confidence_skipped, linux_skipped = _collect_qualified_candidates(
|
qualified, confidence_skipped, linux_skipped = _collect_qualified_candidates(
|
||||||
candidates
|
candidates
|
||||||
)
|
)
|
||||||
|
|
||||||
if not qualified:
|
if not qualified:
|
||||||
_clear_assignment(state, _no_pick_message(confidence_skipped, linux_skipped))
|
_echo(
|
||||||
|
_NO_CONF_MSG
|
||||||
|
if confidence_skipped > 0 and linux_skipped == 0
|
||||||
|
else "\nNo playable games left (all have poor ProtonDB ratings)!"
|
||||||
|
)
|
||||||
|
state.current_app_id = None
|
||||||
|
state.current_game_name = ""
|
||||||
|
state.save()
|
||||||
return
|
return
|
||||||
|
|
||||||
idx = _prompt_user_pick(qualified)
|
idx = _prompt_user_pick(qualified)
|
||||||
|
|||||||
@ -12,11 +12,15 @@ blocks via iptables.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
from steam_backlog_enforcer._hosts_protection import (
|
from steam_backlog_enforcer._hosts_protection import (
|
||||||
|
_disable_hosts_protection,
|
||||||
|
_enable_hosts_protection,
|
||||||
_reblock_hosts,
|
_reblock_hosts,
|
||||||
rewrite_hosts_lines,
|
_sudo_write_hosts,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._store_iptables import (
|
from steam_backlog_enforcer._store_iptables import (
|
||||||
_block_store_iptables,
|
_block_store_iptables,
|
||||||
@ -24,12 +28,6 @@ from steam_backlog_enforcer._store_iptables import (
|
|||||||
_unblock_store_iptables,
|
_unblock_store_iptables,
|
||||||
flush_dns_cache,
|
flush_dns_cache,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._store_tools import (
|
|
||||||
BASH,
|
|
||||||
HOSTS_INSTALL_SCRIPT,
|
|
||||||
HOSTS_REDIRECT_IP,
|
|
||||||
SUDO,
|
|
||||||
)
|
|
||||||
from steam_backlog_enforcer.config import (
|
from steam_backlog_enforcer.config import (
|
||||||
BLOCKED_DOMAINS,
|
BLOCKED_DOMAINS,
|
||||||
HOSTS_FILE,
|
HOSTS_FILE,
|
||||||
@ -37,6 +35,33 @@ from steam_backlog_enforcer.config import (
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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:
|
def is_store_blocked() -> bool:
|
||||||
"""Check if Steam Store domains are blocked in /etc/hosts."""
|
"""Check if Steam Store domains are blocked in /etc/hosts."""
|
||||||
@ -50,7 +75,7 @@ def is_store_blocked() -> bool:
|
|||||||
if (
|
if (
|
||||||
not stripped.startswith("#")
|
not stripped.startswith("#")
|
||||||
and "store.steampowered.com" in stripped
|
and "store.steampowered.com" in stripped
|
||||||
and stripped.startswith(HOSTS_REDIRECT_IP)
|
and stripped.startswith(_HOSTS_REDIRECT_IP)
|
||||||
):
|
):
|
||||||
return True
|
return True
|
||||||
except OSError:
|
except OSError:
|
||||||
@ -103,7 +128,7 @@ def _block_via_hosts_install() -> bool:
|
|||||||
try:
|
try:
|
||||||
logger.info("Running hosts install script to block Steam Store...")
|
logger.info("Running hosts install script to block Steam Store...")
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
[SUDO, BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"],
|
[_SUDO, _BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
timeout=120,
|
timeout=120,
|
||||||
@ -112,6 +137,7 @@ def _block_via_hosts_install() -> bool:
|
|||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
logger.exception("Failed to run hosts install script")
|
logger.exception("Failed to run hosts install script")
|
||||||
return False
|
return False
|
||||||
|
else:
|
||||||
if result.returncode == 0:
|
if result.returncode == 0:
|
||||||
logger.info("hosts install script succeeded.")
|
logger.info("hosts install script succeeded.")
|
||||||
return True
|
return True
|
||||||
@ -159,18 +185,30 @@ def _unblock_hosts() -> bool:
|
|||||||
logger.info("Steam Store not blocked in /etc/hosts, nothing to do.")
|
logger.info("Steam Store not blocked in /etc/hosts, nothing to do.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return rewrite_hosts_lines(
|
try:
|
||||||
_comment_out_blocked, "Commented out Steam Store entries in /etc/hosts."
|
_disable_hosts_protection()
|
||||||
)
|
content = HOSTS_FILE.read_text(encoding="utf-8")
|
||||||
|
new_lines = []
|
||||||
|
changed = False
|
||||||
def _comment_out_blocked(line: str) -> str | None:
|
for line in content.splitlines(keepends=True):
|
||||||
"""The line commented out, if it is a live redirect of a blocked domain."""
|
|
||||||
stripped = line.strip()
|
stripped = line.strip()
|
||||||
if (
|
if (
|
||||||
not stripped.startswith("#")
|
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)
|
and any(d in stripped for d in BLOCKED_DOMAINS)
|
||||||
):
|
):
|
||||||
return f"# {line}" if line.endswith("\n") else f"# {line}\n"
|
new_lines.append(f"# {line}" if line.endswith("\n") else f"# {line}\n")
|
||||||
return None
|
changed = True
|
||||||
|
else:
|
||||||
|
new_lines.append(line)
|
||||||
|
|
||||||
|
if changed:
|
||||||
|
_sudo_write_hosts("".join(new_lines))
|
||||||
|
logger.info("Commented out Steam Store entries in /etc/hosts.")
|
||||||
|
|
||||||
|
_enable_hosts_protection()
|
||||||
|
except OSError:
|
||||||
|
logger.exception("Failed to modify /etc/hosts")
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
return True
|
||||||
|
|||||||
@ -55,16 +55,6 @@ class TestDesktopEnvArgs:
|
|||||||
args = desktop_env_args("bob", 1000)
|
args = desktop_env_args("bob", 1000)
|
||||||
assert _env_value(args, "XDG_RUNTIME_DIR") == "/run/user/1000"
|
assert _env_value(args, "XDG_RUNTIME_DIR") == "/run/user/1000"
|
||||||
|
|
||||||
def test_steam_runtime_logger_kept_out_of_the_journal(self) -> None:
|
|
||||||
"""srt-logger must be told not to mirror Steam's console into journald.
|
|
||||||
|
|
||||||
It inherits the service's JOURNAL_STREAM and opts in on its own; one
|
|
||||||
boot's worth of joystick FFB errors (481k lines) evicted two weeks of
|
|
||||||
journal history and the evidence for a curfew failure with it.
|
|
||||||
"""
|
|
||||||
args = desktop_env_args("bob", 1000)
|
|
||||||
assert _env_value(args, "SRT_LOGGER_USE_JOURNAL") == "0"
|
|
||||||
|
|
||||||
def test_dbus_address_defaults_to_uid_path(self) -> None:
|
def test_dbus_address_defaults_to_uid_path(self) -> None:
|
||||||
"""DBUS falls back to the uid-derived socket when unset."""
|
"""DBUS falls back to the uid-derived socket when unset."""
|
||||||
env_copy = os.environ.copy()
|
env_copy = os.environ.copy()
|
||||||
|
|||||||
@ -11,11 +11,12 @@ import aiohttp
|
|||||||
|
|
||||||
from steam_backlog_enforcer._hltb_matching import _similarity
|
from steam_backlog_enforcer._hltb_matching import _similarity
|
||||||
from steam_backlog_enforcer._hltb_search import _AuthInfo
|
from steam_backlog_enforcer._hltb_search import _AuthInfo
|
||||||
from steam_backlog_enforcer._hltb_search_api import _get_auth_info, _get_hltb_search_url
|
from steam_backlog_enforcer._hltb_search_api import _get_hltb_search_url
|
||||||
from steam_backlog_enforcer._hltb_types import (
|
from steam_backlog_enforcer._hltb_types import (
|
||||||
load_hltb_cache,
|
load_hltb_cache,
|
||||||
save_hltb_cache,
|
save_hltb_cache,
|
||||||
)
|
)
|
||||||
|
from steam_backlog_enforcer.hltb import _get_auth_info
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -106,16 +107,15 @@ class TestGetHltbSearchUrl:
|
|||||||
url = _get_hltb_search_url()
|
url = _get_hltb_search_url()
|
||||||
assert url == "https://howlongtobeat.com/api/finder"
|
assert url == "https://howlongtobeat.com/api/finder"
|
||||||
|
|
||||||
def test_passes_the_user_agent_the_library_now_requires(self) -> None:
|
def test_first_returns_none_second_returns_info(self) -> None:
|
||||||
"""howlongtobeatpy 1.0.23 takes a user agent, not a parse-all flag."""
|
"""Test first returns none second returns info."""
|
||||||
mock_info = MagicMock()
|
mock_info = MagicMock()
|
||||||
mock_info.search_url = "/api/search/xyz"
|
mock_info.search_url = "/api/search/xyz"
|
||||||
with patch("steam_backlog_enforcer._hltb_search_api.HTMLRequests") as mock_html:
|
with patch("steam_backlog_enforcer._hltb_search_api.HTMLRequests") as mock_html:
|
||||||
mock_html.send_website_request_getcode.return_value = mock_info
|
mock_html.send_website_request_getcode.side_effect = [None, mock_info]
|
||||||
mock_html.BASE_URL = "https://howlongtobeat.com"
|
mock_html.BASE_URL = "https://howlongtobeat.com"
|
||||||
_get_hltb_search_url()
|
url = _get_hltb_search_url()
|
||||||
(agent,) = mock_html.send_website_request_getcode.call_args.args
|
assert url == "https://howlongtobeat.com/api/search/xyz"
|
||||||
assert agent.startswith("Mozilla/5.0")
|
|
||||||
|
|
||||||
def test_exception_fallback(self) -> None:
|
def test_exception_fallback(self) -> None:
|
||||||
"""Test exception fallback."""
|
"""Test exception fallback."""
|
||||||
|
|||||||
@ -13,7 +13,7 @@ from steam_backlog_enforcer.hltb import (
|
|||||||
fetch_hltb_confidence,
|
fetch_hltb_confidence,
|
||||||
)
|
)
|
||||||
|
|
||||||
PKG = "steam_backlog_enforcer._hltb_search"
|
PKG = "steam_backlog_enforcer.hltb"
|
||||||
_CONF = "steam_backlog_enforcer._hltb_confidence"
|
_CONF = "steam_backlog_enforcer._hltb_confidence"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -11,7 +11,6 @@ if TYPE_CHECKING:
|
|||||||
from steam_backlog_enforcer._hltb_types import _HLTBExtras
|
from steam_backlog_enforcer._hltb_types import _HLTBExtras
|
||||||
|
|
||||||
PKG = "steam_backlog_enforcer._hltb_confidence"
|
PKG = "steam_backlog_enforcer._hltb_confidence"
|
||||||
_HLTB = "steam_backlog_enforcer.hltb"
|
|
||||||
|
|
||||||
|
|
||||||
class _DummySession:
|
class _DummySession:
|
||||||
@ -34,7 +33,7 @@ class TestFetchHltbDetailMissing:
|
|||||||
with (
|
with (
|
||||||
patch(f"{PKG}.load_hltb_rush_cache", return_value={440: 15.0}),
|
patch(f"{PKG}.load_hltb_rush_cache", return_value={440: 15.0}),
|
||||||
patch(f"{PKG}.load_hltb_game_id_cache", return_value={440: 12345}),
|
patch(f"{PKG}.load_hltb_game_id_cache", return_value={440: 12345}),
|
||||||
patch(f"{_HLTB}.fetch_hltb_times") as mock_fetch,
|
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
|
||||||
):
|
):
|
||||||
result = fetch_hltb_detail_missing([(440, "TF2")])
|
result = fetch_hltb_detail_missing([(440, "TF2")])
|
||||||
assert result == 0
|
assert result == 0
|
||||||
@ -64,7 +63,7 @@ class TestFetchHltbDetailMissing:
|
|||||||
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
||||||
patch(f"{_HLTB}.fetch_hltb_times", side_effect=add_rush),
|
patch(f"{PKG}.fetch_hltb_times", side_effect=add_rush),
|
||||||
patch(f"{PKG}.save_hltb_cache") as mock_save,
|
patch(f"{PKG}.save_hltb_cache") as mock_save,
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 2.0]),
|
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 2.0]),
|
||||||
):
|
):
|
||||||
@ -91,7 +90,7 @@ class TestFetchHltbDetailMissing:
|
|||||||
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
||||||
patch(f"{_HLTB}.fetch_hltb_times"), # no-op, cache stays empty
|
patch(f"{PKG}.fetch_hltb_times"), # no-op, cache stays empty
|
||||||
patch(f"{PKG}.save_hltb_cache", side_effect=capture_save),
|
patch(f"{PKG}.save_hltb_cache", side_effect=capture_save),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
||||||
):
|
):
|
||||||
@ -132,7 +131,7 @@ class TestFetchHltbDetailMissing:
|
|||||||
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
||||||
patch(f"{_HLTB}.fetch_hltb_times", side_effect=add_hours_and_rush),
|
patch(f"{PKG}.fetch_hltb_times", side_effect=add_hours_and_rush),
|
||||||
patch(f"{PKG}.save_hltb_cache", side_effect=capture_save),
|
patch(f"{PKG}.save_hltb_cache", side_effect=capture_save),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
||||||
):
|
):
|
||||||
@ -149,7 +148,7 @@ class TestFetchHltbDetailMissing:
|
|||||||
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
||||||
patch(f"{_HLTB}.fetch_hltb_times"),
|
patch(f"{PKG}.fetch_hltb_times"),
|
||||||
patch(f"{PKG}.save_hltb_cache"),
|
patch(f"{PKG}.save_hltb_cache"),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[5.0, 5.0]),
|
patch(f"{PKG}.time.monotonic", side_effect=[5.0, 5.0]),
|
||||||
):
|
):
|
||||||
@ -165,7 +164,7 @@ class TestFetchHltbDetailMissing:
|
|||||||
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
|
||||||
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
|
||||||
patch(f"{_HLTB}.fetch_hltb_times"),
|
patch(f"{PKG}.fetch_hltb_times"),
|
||||||
patch(f"{PKG}.save_hltb_cache"),
|
patch(f"{PKG}.save_hltb_cache"),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
||||||
):
|
):
|
||||||
|
|||||||
@ -47,9 +47,9 @@ class TestFetchHltbTimesCached:
|
|||||||
"""Test uncached games fetched."""
|
"""Test uncached games fetched."""
|
||||||
with (
|
with (
|
||||||
patch(f"{_CACHED}.load_hltb_cache", return_value={440: 50.0}),
|
patch(f"{_CACHED}.load_hltb_cache", return_value={440: 50.0}),
|
||||||
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
|
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
|
||||||
patch(f"{_CACHED}.save_hltb_cache") as mock_save,
|
patch(f"{_CACHED}.save_hltb_cache") as mock_save,
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 2.0]),
|
patch(f"{_CACHED}.time.monotonic", side_effect=[0.0, 2.0]),
|
||||||
):
|
):
|
||||||
# fetch_hltb_times modifies cache in-place
|
# fetch_hltb_times modifies cache in-place
|
||||||
def add_to_cache(
|
def add_to_cache(
|
||||||
@ -81,9 +81,9 @@ class TestFetchHltbTimesCached:
|
|||||||
cb = MagicMock()
|
cb = MagicMock()
|
||||||
with (
|
with (
|
||||||
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
|
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
|
||||||
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
|
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
|
||||||
patch(f"{_CACHED}.save_hltb_cache"),
|
patch(f"{_CACHED}.save_hltb_cache"),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
|
patch(f"{_CACHED}.time.monotonic", side_effect=[0.0, 1.0]),
|
||||||
):
|
):
|
||||||
mock_fetch.return_value = []
|
mock_fetch.return_value = []
|
||||||
result = fetch_hltb_times_cached(
|
result = fetch_hltb_times_cached(
|
||||||
@ -96,9 +96,9 @@ class TestFetchHltbTimesCached:
|
|||||||
"""Covers the elapsed == 0 branch for rate calculation."""
|
"""Covers the elapsed == 0 branch for rate calculation."""
|
||||||
with (
|
with (
|
||||||
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
|
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
|
||||||
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
|
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
|
||||||
patch(f"{_CACHED}.save_hltb_cache"),
|
patch(f"{_CACHED}.save_hltb_cache"),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[5.0, 5.0]),
|
patch(f"{_CACHED}.time.monotonic", side_effect=[5.0, 5.0]),
|
||||||
):
|
):
|
||||||
mock_fetch.return_value = []
|
mock_fetch.return_value = []
|
||||||
fetch_hltb_times_cached([(440, "TF2")])
|
fetch_hltb_times_cached([(440, "TF2")])
|
||||||
@ -107,9 +107,9 @@ class TestFetchHltbTimesCached:
|
|||||||
"""Covers the found count in logging."""
|
"""Covers the found count in logging."""
|
||||||
with (
|
with (
|
||||||
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
|
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
|
||||||
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
|
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
|
||||||
patch(f"{_CACHED}.save_hltb_cache"),
|
patch(f"{_CACHED}.save_hltb_cache"),
|
||||||
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 3.0]),
|
patch(f"{_CACHED}.time.monotonic", side_effect=[0.0, 3.0]),
|
||||||
):
|
):
|
||||||
|
|
||||||
def add_found(
|
def add_found(
|
||||||
|
|||||||
@ -32,17 +32,6 @@ class TestPickBestHltbEntry:
|
|||||||
assert result is not None
|
assert result is not None
|
||||||
assert result[0]["game_name"] == "FAITH: The Unholy Trinity"
|
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:
|
def test_prefers_full_edition_dash(self) -> None:
|
||||||
"""Test prefers full edition dash."""
|
"""Test prefers full edition dash."""
|
||||||
demo: dict[str, Any] = {"game_name": "FAITH", "comp_100": 1800}
|
demo: dict[str, Any] = {"game_name": "FAITH", "comp_100": 1800}
|
||||||
|
|||||||
@ -101,7 +101,7 @@ class TestSearchOne:
|
|||||||
ctx = _make_ctx(_make_session(resp))
|
ctx = _make_ctx(_make_session(resp))
|
||||||
result = asyncio.run(_search_one(asyncio.Semaphore(1), ctx, 440, "TF2"))
|
result = asyncio.run(_search_one(asyncio.Semaphore(1), ctx, 440, "TF2"))
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert 440 not in ctx.extras.hltb_game_id
|
assert 440 not in ctx.hltb_game_id
|
||||||
|
|
||||||
def test_not_found(self) -> None:
|
def test_not_found(self) -> None:
|
||||||
"""Test not found."""
|
"""Test not found."""
|
||||||
|
|||||||
@ -22,7 +22,6 @@ if TYPE_CHECKING:
|
|||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
|
|
||||||
_PKG = "steam_backlog_enforcer._leetcode_bonus"
|
_PKG = "steam_backlog_enforcer._leetcode_bonus"
|
||||||
_API = "steam_backlog_enforcer._status_api"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
@ -105,7 +104,7 @@ class TestFetchLeetcodeToday:
|
|||||||
{"leetcode": {"checked": False, "solved_today": False, "reason": "dead"}}
|
{"leetcode": {"checked": False, "solved_today": False, "reason": "dead"}}
|
||||||
).encode()
|
).encode()
|
||||||
with (
|
with (
|
||||||
patch(f"{_API}.http.client.HTTPConnection") as conn,
|
patch(f"{_PKG}.http.client.HTTPConnection") as conn,
|
||||||
pytest.raises(ValueError, match="could not check"),
|
pytest.raises(ValueError, match="could not check"),
|
||||||
):
|
):
|
||||||
resp = conn.return_value.getresponse.return_value
|
resp = conn.return_value.getresponse.return_value
|
||||||
@ -116,7 +115,7 @@ class TestFetchLeetcodeToday:
|
|||||||
def test_a_non_200_is_an_error(self) -> None:
|
def test_a_non_200_is_an_error(self) -> None:
|
||||||
"""An error page is not a payload."""
|
"""An error page is not a payload."""
|
||||||
with (
|
with (
|
||||||
patch(f"{_API}.http.client.HTTPConnection") as conn,
|
patch(f"{_PKG}.http.client.HTTPConnection") as conn,
|
||||||
pytest.raises(ValueError, match="status 500"),
|
pytest.raises(ValueError, match="status 500"),
|
||||||
):
|
):
|
||||||
resp = conn.return_value.getresponse.return_value
|
resp = conn.return_value.getresponse.return_value
|
||||||
@ -130,7 +129,7 @@ class TestFetchLeetcodeToday:
|
|||||||
payload = json.dumps(
|
payload = json.dumps(
|
||||||
{"leetcode": {"checked": True, "solved_today": True, "reason": "1"}}
|
{"leetcode": {"checked": True, "solved_today": True, "reason": "1"}}
|
||||||
).encode()
|
).encode()
|
||||||
with patch(f"{_API}.http.client.HTTPConnection") as conn:
|
with patch(f"{_PKG}.http.client.HTTPConnection") as conn:
|
||||||
resp = conn.return_value.getresponse.return_value
|
resp = conn.return_value.getresponse.return_value
|
||||||
resp.status = 200
|
resp.status = 200
|
||||||
resp.read.return_value = payload
|
resp.read.return_value = payload
|
||||||
|
|||||||
@ -14,7 +14,6 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
_TYPES = "steam_backlog_enforcer._hltb_types"
|
_TYPES = "steam_backlog_enforcer._hltb_types"
|
||||||
_CMD = "steam_backlog_enforcer._cmd_done"
|
_CMD = "steam_backlog_enforcer._cmd_done"
|
||||||
_CONF = "steam_backlog_enforcer._hltb_confidence"
|
|
||||||
_SCAN = "steam_backlog_enforcer.scanning"
|
_SCAN = "steam_backlog_enforcer.scanning"
|
||||||
|
|
||||||
|
|
||||||
@ -69,7 +68,7 @@ class TestBackfillPollsForFinished:
|
|||||||
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
||||||
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
||||||
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 1, "name": "G"}]),
|
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 1, "name": "G"}]),
|
||||||
patch(f"{_CONF}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
|
patch(f"{_CMD}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
|
||||||
patch(f"{_CMD}._echo"),
|
patch(f"{_CMD}._echo"),
|
||||||
):
|
):
|
||||||
result = _cmd_done._backfill_polls_for_finished(_state([1]))
|
result = _cmd_done._backfill_polls_for_finished(_state([1]))
|
||||||
@ -94,7 +93,7 @@ class TestBackfillPollsForFinished:
|
|||||||
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
||||||
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
||||||
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 7, "name": "G"}]),
|
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 7, "name": "G"}]),
|
||||||
patch(f"{_CONF}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
|
patch(f"{_CMD}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
|
||||||
patch(f"{_CMD}._echo"),
|
patch(f"{_CMD}._echo"),
|
||||||
):
|
):
|
||||||
result = _cmd_done._backfill_polls_for_finished(
|
result = _cmd_done._backfill_polls_for_finished(
|
||||||
@ -122,7 +121,7 @@ class TestBackfillPollsForFinished:
|
|||||||
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
||||||
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
||||||
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 3, "name": "G"}]),
|
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 3, "name": "G"}]),
|
||||||
patch(f"{_CONF}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
|
patch(f"{_CMD}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
|
||||||
patch(f"{_CMD}._echo"),
|
patch(f"{_CMD}._echo"),
|
||||||
):
|
):
|
||||||
_cmd_done._backfill_polls_for_finished(_state([3]))
|
_cmd_done._backfill_polls_for_finished(_state([3]))
|
||||||
|
|||||||
@ -15,7 +15,6 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
_TYPES = "steam_backlog_enforcer._hltb_types"
|
_TYPES = "steam_backlog_enforcer._hltb_types"
|
||||||
_CMD = "steam_backlog_enforcer._cmd_done"
|
_CMD = "steam_backlog_enforcer._cmd_done"
|
||||||
_CONF = "steam_backlog_enforcer._hltb_confidence"
|
|
||||||
_SCAN = "steam_backlog_enforcer.scanning"
|
_SCAN = "steam_backlog_enforcer.scanning"
|
||||||
_SCANCONF = "steam_backlog_enforcer._scanning_confidence"
|
_SCANCONF = "steam_backlog_enforcer._scanning_confidence"
|
||||||
_POLLS = "steam_backlog_enforcer._polls_reporting"
|
_POLLS = "steam_backlog_enforcer._polls_reporting"
|
||||||
@ -161,7 +160,7 @@ class TestScanningPollsIntegration:
|
|||||||
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
||||||
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
||||||
patch(
|
patch(
|
||||||
f"{_CONF}.fetch_hltb_confidence_cached",
|
f"{_POLLS}.fetch_hltb_confidence_cached",
|
||||||
side_effect=fake_fetch,
|
side_effect=fake_fetch,
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
@ -198,7 +197,7 @@ class TestScanningPollsIntegration:
|
|||||||
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
|
||||||
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
|
||||||
patch(
|
patch(
|
||||||
f"{_CONF}.fetch_hltb_confidence_cached",
|
f"{_POLLS}.fetch_hltb_confidence_cached",
|
||||||
side_effect=fake_fetch,
|
side_effect=fake_fetch,
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
|
|||||||
@ -141,11 +141,6 @@ class TestPickNextGameGroup2:
|
|||||||
"steam_backlog_enforcer._scanning_confidence._echo",
|
"steam_backlog_enforcer._scanning_confidence._echo",
|
||||||
side_effect=lambda *a, **_: echoed.append(a[0]),
|
side_effect=lambda *a, **_: echoed.append(a[0]),
|
||||||
),
|
),
|
||||||
# The "nothing assignable" line is spoken where the slot is cleared.
|
|
||||||
patch(
|
|
||||||
"steam_backlog_enforcer._scanning_assign._echo",
|
|
||||||
side_effect=lambda *a, **_: echoed.append(a[0]),
|
|
||||||
),
|
|
||||||
patch(
|
patch(
|
||||||
"steam_backlog_enforcer._scanning_candidates._pick_playable_candidate",
|
"steam_backlog_enforcer._scanning_candidates._pick_playable_candidate",
|
||||||
return_value=None,
|
return_value=None,
|
||||||
|
|||||||
@ -5,13 +5,11 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from steam_backlog_enforcer._hosts_protection import (
|
from steam_backlog_enforcer.store_blocker import (
|
||||||
_disable_hosts_protection,
|
_disable_hosts_protection,
|
||||||
_enable_hosts_protection,
|
_enable_hosts_protection,
|
||||||
_reblock_hosts,
|
_reblock_hosts,
|
||||||
_sudo_write_hosts,
|
_sudo_write_hosts,
|
||||||
)
|
|
||||||
from steam_backlog_enforcer.store_blocker import (
|
|
||||||
_unblock_hosts,
|
_unblock_hosts,
|
||||||
flush_dns_cache,
|
flush_dns_cache,
|
||||||
)
|
)
|
||||||
@ -20,7 +18,6 @@ if TYPE_CHECKING:
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
PKG = "steam_backlog_enforcer.store_blocker"
|
PKG = "steam_backlog_enforcer.store_blocker"
|
||||||
_HP = "steam_backlog_enforcer._hosts_protection"
|
|
||||||
|
|
||||||
|
|
||||||
class TestSudoWriteHosts:
|
class TestSudoWriteHosts:
|
||||||
@ -73,10 +70,10 @@ class TestUnblockHosts:
|
|||||||
)
|
)
|
||||||
with (
|
with (
|
||||||
patch(f"{PKG}.is_store_blocked", return_value=True),
|
patch(f"{PKG}.is_store_blocked", return_value=True),
|
||||||
patch(f"{_HP}.HOSTS_FILE", hosts_file),
|
patch(f"{PKG}.HOSTS_FILE", hosts_file),
|
||||||
patch(f"{_HP}._disable_hosts_protection"),
|
patch(f"{PKG}._disable_hosts_protection"),
|
||||||
patch(f"{_HP}._enable_hosts_protection"),
|
patch(f"{PKG}._enable_hosts_protection"),
|
||||||
patch(f"{_HP}._sudo_write_hosts") as mock_write,
|
patch(f"{PKG}._sudo_write_hosts") as mock_write,
|
||||||
):
|
):
|
||||||
result = _unblock_hosts()
|
result = _unblock_hosts()
|
||||||
assert result is True
|
assert result is True
|
||||||
@ -91,10 +88,10 @@ class TestUnblockHosts:
|
|||||||
)
|
)
|
||||||
with (
|
with (
|
||||||
patch(f"{PKG}.is_store_blocked", return_value=True),
|
patch(f"{PKG}.is_store_blocked", return_value=True),
|
||||||
patch(f"{_HP}.HOSTS_FILE", hosts_file),
|
patch(f"{PKG}.HOSTS_FILE", hosts_file),
|
||||||
patch(f"{_HP}._disable_hosts_protection"),
|
patch(f"{PKG}._disable_hosts_protection"),
|
||||||
patch(f"{_HP}._enable_hosts_protection"),
|
patch(f"{PKG}._enable_hosts_protection"),
|
||||||
patch(f"{_HP}._sudo_write_hosts") as mock_write,
|
patch(f"{PKG}._sudo_write_hosts") as mock_write,
|
||||||
):
|
):
|
||||||
result = _unblock_hosts()
|
result = _unblock_hosts()
|
||||||
assert result is True
|
assert result is True
|
||||||
@ -103,7 +100,7 @@ class TestUnblockHosts:
|
|||||||
def test_os_error(self) -> None:
|
def test_os_error(self) -> None:
|
||||||
with (
|
with (
|
||||||
patch(f"{PKG}.is_store_blocked", return_value=True),
|
patch(f"{PKG}.is_store_blocked", return_value=True),
|
||||||
patch(f"{_HP}._disable_hosts_protection", side_effect=OSError),
|
patch(f"{PKG}._disable_hosts_protection", side_effect=OSError),
|
||||||
):
|
):
|
||||||
result = _unblock_hosts()
|
result = _unblock_hosts()
|
||||||
assert result is False
|
assert result is False
|
||||||
|
|||||||
@ -25,7 +25,6 @@ if TYPE_CHECKING:
|
|||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
|
|
||||||
_PKG = "steam_backlog_enforcer._workout_budget"
|
_PKG = "steam_backlog_enforcer._workout_budget"
|
||||||
_API = "steam_backlog_enforcer._status_api"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
@ -113,8 +112,7 @@ class TestWorkoutLoggedToday:
|
|||||||
"""A workout logged later in the day still raises the budget."""
|
"""A workout logged later in the day still raises the budget."""
|
||||||
with (
|
with (
|
||||||
patch(f"{_PKG}._fetch_workout_today", return_value=False) as fetch,
|
patch(f"{_PKG}._fetch_workout_today", return_value=False) as fetch,
|
||||||
# Stored at 0.0; read back at 999.0 (expired); stored again.
|
patch(f"{_PKG}.time.monotonic", side_effect=[0.0, 999.0]),
|
||||||
patch(f"{_API}.time.monotonic", side_effect=[0.0, 999.0, 999.0]),
|
|
||||||
):
|
):
|
||||||
workout_logged_today(_config())
|
workout_logged_today(_config())
|
||||||
workout_logged_today(_config())
|
workout_logged_today(_config())
|
||||||
|
|||||||
@ -22,7 +22,7 @@
|
|||||||
"@testing-library/jest-dom": "7.0.1",
|
"@testing-library/jest-dom": "7.0.1",
|
||||||
"@testing-library/react": "16.3.3",
|
"@testing-library/react": "16.3.3",
|
||||||
"@testing-library/user-event": "14.6.7",
|
"@testing-library/user-event": "14.6.7",
|
||||||
"@types/node": "26.5.1",
|
"@types/node": "26.4.0",
|
||||||
"@types/react": "19.3.0",
|
"@types/react": "19.3.0",
|
||||||
"@types/react-dom": "19.3.0",
|
"@types/react-dom": "19.3.0",
|
||||||
"@vitejs/plugin-react": "6.1.1",
|
"@vitejs/plugin-react": "6.1.1",
|
||||||
|
|||||||
@ -31,8 +31,8 @@ importers:
|
|||||||
specifier: 14.6.7
|
specifier: 14.6.7
|
||||||
version: 14.6.7(@testing-library/dom@10.4.1)
|
version: 14.6.7(@testing-library/dom@10.4.1)
|
||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: 26.5.1
|
specifier: 26.4.0
|
||||||
version: 26.5.1
|
version: 26.4.0
|
||||||
'@types/react':
|
'@types/react':
|
||||||
specifier: 19.3.0
|
specifier: 19.3.0
|
||||||
version: 19.3.0
|
version: 19.3.0
|
||||||
@ -41,7 +41,7 @@ importers:
|
|||||||
version: 19.3.0(@types/react@19.3.0)
|
version: 19.3.0(@types/react@19.3.0)
|
||||||
'@vitejs/plugin-react':
|
'@vitejs/plugin-react':
|
||||||
specifier: 6.1.1
|
specifier: 6.1.1
|
||||||
version: 6.1.1(vite@8.3.0(@types/node@26.5.1))
|
version: 6.1.1(vite@8.3.0(@types/node@26.4.0))
|
||||||
'@vitest/coverage-v8':
|
'@vitest/coverage-v8':
|
||||||
specifier: 5.0.0
|
specifier: 5.0.0
|
||||||
version: 5.0.0(vitest@5.0.0)
|
version: 5.0.0(vitest@5.0.0)
|
||||||
@ -68,10 +68,10 @@ importers:
|
|||||||
version: 8.70.0(eslint@10.10.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3)
|
version: 8.70.0(eslint@10.10.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3)
|
||||||
vite:
|
vite:
|
||||||
specifier: 8.3.0
|
specifier: 8.3.0
|
||||||
version: 8.3.0(@types/node@26.5.1)
|
version: 8.3.0(@types/node@26.4.0)
|
||||||
vitest:
|
vitest:
|
||||||
specifier: 5.0.0
|
specifier: 5.0.0
|
||||||
version: 5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1))
|
version: 5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0))
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
|
|
||||||
@ -458,8 +458,8 @@ packages:
|
|||||||
'@types/json-schema@7.0.15':
|
'@types/json-schema@7.0.15':
|
||||||
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
|
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
|
||||||
|
|
||||||
'@types/node@26.5.1':
|
'@types/node@26.4.0':
|
||||||
resolution: {integrity: sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g==}
|
resolution: {integrity: sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==}
|
||||||
|
|
||||||
'@types/react-dom@19.3.0':
|
'@types/react-dom@19.3.0':
|
||||||
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
|
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
|
||||||
@ -1210,8 +1210,8 @@ packages:
|
|||||||
engines: {node: '>=14.17'}
|
engines: {node: '>=14.17'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
undici-types@8.9.0:
|
undici-types@8.3.0:
|
||||||
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
|
resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
|
||||||
|
|
||||||
undici@8.10.0:
|
undici@8.10.0:
|
||||||
resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==}
|
resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==}
|
||||||
@ -1681,7 +1681,7 @@ snapshots:
|
|||||||
picocolors: 1.1.1
|
picocolors: 1.1.1
|
||||||
redent: 3.0.0
|
redent: 3.0.0
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
vitest: 5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1))
|
vitest: 5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0))
|
||||||
|
|
||||||
'@testing-library/react@16.3.3(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)':
|
'@testing-library/react@16.3.3(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
@ -1712,9 +1712,9 @@ snapshots:
|
|||||||
|
|
||||||
'@types/json-schema@7.0.15': {}
|
'@types/json-schema@7.0.15': {}
|
||||||
|
|
||||||
'@types/node@26.5.1':
|
'@types/node@26.4.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 8.9.0
|
undici-types: 8.3.0
|
||||||
|
|
||||||
'@types/react-dom@19.3.0(@types/react@19.3.0)':
|
'@types/react-dom@19.3.0(@types/react@19.3.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
@ -1815,10 +1815,10 @@ snapshots:
|
|||||||
'@typescript-eslint/types': 8.70.0
|
'@typescript-eslint/types': 8.70.0
|
||||||
eslint-visitor-keys: 5.0.1
|
eslint-visitor-keys: 5.0.1
|
||||||
|
|
||||||
'@vitejs/plugin-react@6.1.1(vite@8.3.0(@types/node@26.5.1))':
|
'@vitejs/plugin-react@6.1.1(vite@8.3.0(@types/node@26.4.0))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@rolldown/pluginutils': 1.0.1
|
'@rolldown/pluginutils': 1.0.1
|
||||||
vite: 8.3.0(@types/node@26.5.1)
|
vite: 8.3.0(@types/node@26.4.0)
|
||||||
|
|
||||||
'@vitest/coverage-v8@5.0.0(vitest@5.0.0)':
|
'@vitest/coverage-v8@5.0.0(vitest@5.0.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
@ -1830,7 +1830,7 @@ snapshots:
|
|||||||
obug: 2.1.4
|
obug: 2.1.4
|
||||||
std-env: 4.2.0
|
std-env: 4.2.0
|
||||||
tinyrainbow: 3.1.1
|
tinyrainbow: 3.1.1
|
||||||
vitest: 5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1))
|
vitest: 5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0))
|
||||||
|
|
||||||
'@vitest/istanbul-lib-coverage@1.0.1': {}
|
'@vitest/istanbul-lib-coverage@1.0.1': {}
|
||||||
|
|
||||||
@ -1838,14 +1838,14 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@vitest/istanbul-lib-coverage': 1.0.1
|
'@vitest/istanbul-lib-coverage': 1.0.1
|
||||||
|
|
||||||
'@vitest/mocker@5.0.0(vite@8.3.0(@types/node@26.5.1))':
|
'@vitest/mocker@5.0.0(vite@8.3.0(@types/node@26.4.0))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@jridgewell/trace-mapping': 0.3.31
|
'@jridgewell/trace-mapping': 0.3.31
|
||||||
'@vitest/spy': 5.0.0
|
'@vitest/spy': 5.0.0
|
||||||
estree-walker: 3.0.3
|
estree-walker: 3.0.3
|
||||||
magic-string: 1.3.1
|
magic-string: 1.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
vite: 8.3.0(@types/node@26.5.1)
|
vite: 8.3.0(@types/node@26.4.0)
|
||||||
|
|
||||||
'@vitest/spy@5.0.0': {}
|
'@vitest/spy@5.0.0': {}
|
||||||
|
|
||||||
@ -2431,7 +2431,7 @@ snapshots:
|
|||||||
|
|
||||||
typescript@6.0.3: {}
|
typescript@6.0.3: {}
|
||||||
|
|
||||||
undici-types@8.9.0: {}
|
undici-types@8.3.0: {}
|
||||||
|
|
||||||
undici@8.10.0: {}
|
undici@8.10.0: {}
|
||||||
|
|
||||||
@ -2445,7 +2445,7 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
punycode: 2.3.1
|
punycode: 2.3.1
|
||||||
|
|
||||||
vite@8.3.0(@types/node@26.5.1):
|
vite@8.3.0(@types/node@26.4.0):
|
||||||
dependencies:
|
dependencies:
|
||||||
lightningcss: 1.33.0
|
lightningcss: 1.33.0
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
@ -2453,13 +2453,13 @@ snapshots:
|
|||||||
rolldown: 1.2.6
|
rolldown: 1.2.6
|
||||||
tinyglobby: 0.2.17
|
tinyglobby: 0.2.17
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 26.5.1
|
'@types/node': 26.4.0
|
||||||
fsevents: 2.3.3
|
fsevents: 2.3.3
|
||||||
|
|
||||||
vitest@5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1)):
|
vitest@5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0)):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/chai': 5.2.3
|
'@types/chai': 5.2.3
|
||||||
'@vitest/mocker': 5.0.0(vite@8.3.0(@types/node@26.5.1))
|
'@vitest/mocker': 5.0.0(vite@8.3.0(@types/node@26.4.0))
|
||||||
chai: 6.2.2
|
chai: 6.2.2
|
||||||
es-module-lexer: 2.3.2
|
es-module-lexer: 2.3.2
|
||||||
expect-type: 1.4.0
|
expect-type: 1.4.0
|
||||||
@ -2470,10 +2470,10 @@ snapshots:
|
|||||||
tinybench: 6.1.4
|
tinybench: 6.1.4
|
||||||
tinyexec: 1.3.0
|
tinyexec: 1.3.0
|
||||||
tinyglobby: 0.2.17
|
tinyglobby: 0.2.17
|
||||||
vite: 8.3.0(@types/node@26.5.1)
|
vite: 8.3.0(@types/node@26.4.0)
|
||||||
why-is-node-running: 2.3.0
|
why-is-node-running: 2.3.0
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 26.5.1
|
'@types/node': 26.4.0
|
||||||
'@vitest/coverage-v8': 5.0.0(vitest@5.0.0)
|
'@vitest/coverage-v8': 5.0.0(vitest@5.0.0)
|
||||||
jsdom: 30.0.1
|
jsdom: 30.0.1
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user