steam-backlog-enforcer/steam_backlog_enforcer/_playtime_notify.py
Krzysztof kuhy Rudnicki 4424a26dbe Fail fast on Steam launch, add job desktop env
Steam launch: _wait_for_cdp_ready watches the launched Popen and raises
"Steam exited during startup (exit code N)" instead of polling 45 s, and
launching is refused when no X display is up.

Non-root jobs: desktop_user_cmd prefixes DISPLAY/XAUTHORITY/XDG_RUNTIME_DIR
via env, so a web-job Steam launch reaches the display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
2026-11-16 09:42:45 +01:00

71 lines
2.1 KiB
Python

"""Desktop notifications for the playtime budget, and time formatting.
Notifications must reach the logged-in desktop session, not the root systemd
context the enforcer runs in, which is why they are dispatched through
``_run_as_user``.
"""
from __future__ import annotations
import logging
from steam_backlog_enforcer._desktop_env import (
resolve_desktop_user as _resolve_desktop_user,
)
from steam_backlog_enforcer._steam_process import _run_as_user
logger = logging.getLogger(__name__)
_SECONDS_PER_MINUTE = 60
_MINUTES_PER_HOUR = 60
def short_duration(seconds: int) -> str:
"""Render a threshold as a toast-sized number + unit (textgate: no words).
Args:
seconds: Seconds remaining.
Returns:
``"30s"``, ``"5m"``, ``"1h"`` or ``"1h 30m"``.
"""
if seconds < _SECONDS_PER_MINUTE:
return f"{seconds}s"
hours, minutes = divmod(seconds // _SECONDS_PER_MINUTE, _MINUTES_PER_HOUR)
if not hours:
return f"{minutes}m"
return f"{hours}h {minutes}m" if minutes else f"{hours}h"
def notify_desktop_user(title: str, body: str) -> None:
"""Send a desktop notification into the real user's session.
``enforcer.send_notification`` now drops privileges too, so this differs
only in delivery: it is fire-and-forget (``Popen``) where that one waits up
to 5s, which matters on the playtime-cutoff path.
Args:
title: Notification title.
body: Notification body.
"""
user = _resolve_desktop_user()
try:
_run_as_user(["notify-send", title, body, "--icon=dialog-warning"], user)
except OSError, ValueError:
logger.debug("Could not send desktop notification.")
def _humanise(seconds: int) -> str:
"""Render a warning threshold as a short human phrase.
Args:
seconds: Seconds remaining.
Returns:
A phrase such as ``"30 minutes"`` or ``"10 seconds"``.
"""
if seconds < _SECONDS_PER_MINUTE:
return f"{seconds} seconds"
minutes = seconds // _SECONDS_PER_MINUTE
return "1 hour" if minutes == _MINUTES_PER_HOUR else f"{minutes} minutes"