Compare commits

..

27 Commits

Author SHA1 Message Date
1475ab913b Shard ci-precommit into four gate steps
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Each slice runs under 30 s; together they run all 35 default-stage
hooks once. CI (pre-commit.yml) is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:45:58 +01:00
2998bd5353 Give enum-only run files covered members
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:40:13 +01:00
0ec8cfddec Exempt run_tcx fixtures from whitespace fixers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:35:55 +01:00
39c85a7dfd Revert "Normalize run_tcx fixture whitespace"
The golden test compares the encoder with these byte-exact files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:35:54 +01:00
5d3547c221 Fix gate: file caps, silent catch, pin bump
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:31:18 +01:00
7f9169b9d0 Normalize run_tcx fixture whitespace
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 17:19:37 +01:00
17dac66a11 Allow an extra workout after done today
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:53:37 +01:00
23ad2e02b4 Swap google_sign_in for google_account_token
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:48:04 +01:00
aaaecca3be Show the live map on the run screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:27:42 +01:00
bd12b8711d Add run screen, home entry, provisioning
One-screen live run UI (icons and digits), map slot via mapBuilder, upload badge, sandbox e2e, Pixel 6a inset test, dufs provisioning script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:24:25 +01:00
97d73b31f5 Merge main, use shared dufs login
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:15:15 +01:00
66e9948777 WIP run screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:12:59 +01:00
801e303b39 Merge branch 'worktree-agent-a19044abadd522d41' 2026-11-10 16:12:27 +01:00
6fa9666cdd Marker lists distinct runs; guard fixes
Marker: twins (Pixel_6a_ infix) listed once, app-authored files never. Backup guard: a recorded run no longer lifts the workout-history clobber guard. runGuarded: a throw outside per-file handling logs and sets failed. Silent-failure hook clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:11:59 +01:00
b1ff91249b Merge branch 'worktree-agent-acd53f670745f7d44' 2026-11-10 16:09:14 +01:00
0411116f24 Harden RunnerUp retirement after review
Silent-failure checker, mypy, pylint now clean. Hidden packages count
as installed (pm list -u), pull gets a long timeout, wifi entries are
matched by ro.serialno, and a missing log/drop dir is a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:08:40 +01:00
770a88454d Add run controller, run service, km cue
Foreground service (dataSync+location) started after access, numbers-only notification, kilometre buzz and chime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:07:25 +01:00
a6c97dab8f Import RunnerUp history into the app
One-time, phone-only import of /RunnerUp/processed over dufs WebDAV as display-only runs, then a dotfile marker PUT for the PC. Never PUTs a tcx. Icon-only status badge in Settings, shared DufsCredentials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:07:03 +01:00
8ca4c301fd Back up and export GPS runs
runs/run_points were in neither backup.json nor the user export. App-made runs go in the backup (history returns from the PC), all runs in export v3; merge keyed by id or hash, idempotent. The backup clobber guard now also protects a runs-only backup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:06:56 +01:00
ca205fa67e Build a fresh tile provider per map
TileLayer disposes its provider; cache only the directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:03:02 +01:00
25ee5ca9ad Add sandbox GPS replay and speed setting
Synthetic 4 km loop generated in Dart, replayed at 1x/10x/60x; main imports the dufs login and retries pending uploads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:02:39 +01:00
50faee673f Wire runnerup-retire units into installer
Daily timer (+10 min after boot) running the retirement, installed
and removed with the other screen-locker units; README section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:01:37 +01:00
b174339979 Add RunnerUp retirement logic
Anchor = PC credit time of an app-authored run (joined on TCX end
time in log.json), due 7 days later, gated on a validated import
marker, then adb backup + uninstall. Typed results, --status/--dry-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:01:17 +01:00
8a26387396 Add run recorder, upload queue, saver
State machine over PositionSource + GpsFilter with pause segments, pending-run WebDAV PUT queue, dufs login import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:00:31 +01:00
b4e69dbff4 Add RunMap, run detail and runs in history
RunMap.route/.live (flutter_map, OSM tiles cached on disk,
collapsed icon-only attribution, one warning when tiles fail),
RunDetailScreen (full-bleed map + numbers, no scrolling), a runs
strip in the history, and day+sport dedupe that hides the PC's
runnerup_verified entry once the phone has the run itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 16:00:01 +01:00
63caf9dee9 Match RunnerUp TCX: Calories, walk as Other
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 15:41:55 +01:00
c2544c4a9c Add GPS run foundation: TCX codec, DB, deps
Pure-Dart TCX codec pinned to the PC's RunnerUp parser by a shared
golden fixture (Dart byte-compare + pytest through the real verifier),
GPS filters and moving-time maths mirroring the PC walk rule, runs /
run_points tables (schema v9), PositionSource seam over geolocator,
location permissions and foreground service type, map/cache deps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
2026-11-10 15:37:41 +01:00
143 changed files with 15323 additions and 326 deletions

View File

@ -13,9 +13,13 @@ repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
# run_tcx holds byte-exact RunnerUp exports; the golden test compares the
# encoder's output with them, so the fixers must never rewrite them.
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
exclude: ^screen_locker/tests/fixtures/run_tcx/
- id: end-of-file-fixer
exclude: ^screen_locker/tests/fixtures/run_tcx/
- id: check-yaml
# pnpm-lock.yaml is a two-document stream by design.
exclude: ^web/pnpm-lock\.yaml$
@ -126,6 +130,7 @@ repos:
# what else happened to be staged alongside. Both are a hard 10.00.
- id: pylint
name: pylint (source, 10.00)
alias: pylint-source
exclude: ^screen_locker/tests/
args:
- --rcfile=pyproject.toml
@ -185,6 +190,9 @@ repos:
# The CI mirror, one step per hook so each call stays under the 60 s
# action cap. Order matters: ci-venv (re)builds .ci-mirror-venv from
# requirements.txt when it changed, so ci-pytest only reuses it.
# `pre-commit run --all-files` is split into four ci-precommit-* steps
# (each well under the cap); together they run every default-stage hook
# exactly once -- see run_precommit_group in scripts/ci_mirror.sh.
- id: ci-venv
name: CI mirror (clean requirements.txt venv)
entry: bash scripts/ci_mirror.sh venv
@ -193,9 +201,33 @@ repos:
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit
name: CI mirror (pre-commit --all-files)
entry: bash scripts/ci_mirror.sh precommit
- id: ci-precommit-pylint-source
name: "CI mirror (pre-commit --all-files: pylint source)"
entry: bash scripts/ci_mirror.sh precommit pylint-source
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit-pylint-tests
name: "CI mirror (pre-commit --all-files: pylint tests)"
entry: bash scripts/ci_mirror.sh precommit pylint-tests
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit-flutter-web
name: "CI mirror (pre-commit --all-files: flutter analyze + web lint/typecheck)"
entry: bash scripts/ci_mirror.sh precommit flutter-web
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-precommit-rest
name: "CI mirror (pre-commit --all-files: every other hook)"
entry: bash scripts/ci_mirror.sh precommit rest
language: system
pass_filenames: false
always_run: true

View File

@ -48,6 +48,13 @@ so a run finished after 20:00 pushes the hour later without the phone being
plugged in; the per-minute shutdown check then lifts the night lockdown on its
own once the hour is past "now" (digital-wellbeing's check script).
**Retiring RunnerUp.** A week after the PC first credits a run recorded by the
workout app (TCX author `kuhy workout_app`), `runnerup-retire.timer` (daily, retries
until the phone is attached) backs `/sdcard/Documents/RunnerUp` up to
`~/data/cloud/RunnerUp/runnerup_phone_backup_<date>/` and uninstalls `org.runnerup.free`,
once the app's `.workout_app_import.json` matches `processed/`; no app run, no uninstall.
`python3 -m screen_locker.runnerup_retire --status` / `--dry-run` change nothing.
## MCP server (Claude Code integration)
screen-locker exposes a **read-only** MCP server (`screen_locker._mcp`) so

View File

@ -17,6 +17,8 @@ BONUS_SERVICE_NAME="earner-bonus.service"
BONUS_PATH_NAME="earner-bonus.path"
RUNNERUP_WATCH_NAME="runnerup-watch.service"
WORKOUT_POKE_NAME="workout-poke.service"
RETIRE_SERVICE_NAME="runnerup-retire.service"
RETIRE_TIMER_NAME="runnerup-retire.timer"
# Runtime dependencies. screen_lock.py imports tkinter at module scope. On Arch
# the tkinter MODULE ships inside the `python` package, but the shared library
@ -147,6 +149,12 @@ cp "$SCRIPT_DIR/$RUNNERUP_WATCH_NAME" "$USER_SERVICE_DIR/$RUNNERUP_WATCH_NAME"
bash "$SCRIPT_DIR/scripts/workout_poke_keygen.sh"
cp "$SCRIPT_DIR/$WORKOUT_POKE_NAME" "$USER_SERVICE_DIR/$WORKOUT_POKE_NAME"
# The RunnerUp retirement: a week after the workout app's first credited run
# it backs the old app's exports up and uninstalls it from the phone. A daily
# timer, because the phone is not always attached; a no-op until then.
cp "$SCRIPT_DIR/$RETIRE_SERVICE_NAME" "$USER_SERVICE_DIR/$RETIRE_SERVICE_NAME"
cp "$SCRIPT_DIR/$RETIRE_TIMER_NAME" "$USER_SERVICE_DIR/$RETIRE_TIMER_NAME"
# Update paths in the service file to use absolute paths
REPO_ROOT="$SCRIPT_DIR"
sed -i "s|WorkingDirectory=.*|WorkingDirectory=$REPO_ROOT|" "$USER_SERVICE_DIR/$SERVICE_NAME"
@ -159,25 +167,17 @@ systemctl --user daemon-reload
# Enable the service to start on login (one-shot, no periodic timer)
systemctl --user enable "$SERVICE_NAME"
# Enable the early bird re-check timer
systemctl --user enable --now "$EARLY_BIRD_TIMER_NAME"
# Timers: early bird re-check, periodic re-check, workout sync, the instant
# bonus pass on ledger writes, and the daily RunnerUp retirement retry
systemctl --user enable --now "$EARLY_BIRD_TIMER_NAME" "$LOCKER_TIMER_NAME" \
"$SYNC_TIMER_NAME" "$BONUS_PATH_NAME" "$RETIRE_TIMER_NAME"
# Enable the periodic re-check timer
systemctl --user enable --now "$LOCKER_TIMER_NAME"
# Enable the periodic workout sync
systemctl --user enable --now "$SYNC_TIMER_NAME"
# Enable the instant bonus pass on ledger writes
systemctl --user enable --now "$BONUS_PATH_NAME"
# Enable the instant RunnerUp credit on upload (restart picks up a new script)
systemctl --user enable "$RUNNERUP_WATCH_NAME"
systemctl --user restart "$RUNNERUP_WATCH_NAME"
# Enable the LAN workout poke listener (restart picks up new code)
systemctl --user enable "$WORKOUT_POKE_NAME"
systemctl --user restart "$WORKOUT_POKE_NAME"
# Instant RunnerUp credit on upload, and the LAN workout poke listener
# (restart picks up new code)
for unit in "$RUNNERUP_WATCH_NAME" "$WORKOUT_POKE_NAME"; do
systemctl --user enable "$unit"
systemctl --user restart "$unit"
done
# Verify enforcement is actually armed. enable can silently no-op when systemd
# breaks an ordering cycle by deleting the timer's job -- exactly what happened

View File

@ -17,6 +17,8 @@ UNITS=(
"earner-bonus.service"
"runnerup-watch.service"
"workout-poke.service"
"runnerup-retire.timer"
"runnerup-retire.service"
)
for unit in "${UNITS[@]}"; do

View File

@ -14,7 +14,7 @@ pre-commit==4.7.0
pylint==4.1.3
pytest==9.2.0
pytest-cov==7.1.0
pytest-randomly==5.0.0
pytest-randomly==5.1.0
pytest-sugar==1.1.1
pytest-xdist==3.8.0
# Direct dependency since the Firebase session recovery exchanges a refresh

15
runnerup-retire.service Normal file
View File

@ -0,0 +1,15 @@
[Unit]
Description=Back up and uninstall the stock RunnerUp app a week after the workout app's first credited run
[Service]
Type=oneshot
# screen_locker is pip-installed (editable), like workout-sync.service, so no
# WorkingDirectory/PYTHONPATH. Headless: no DISPLAY, no Tk, no lock screen.
#
# Exit 0 for "not due yet", "no app run credited yet" and "phone not attached"
# (the timer retries), non-zero when a human is needed: invalid import marker,
# adb missing, a failed backup or a refused uninstall. That shows up in
# `systemctl --user --failed`. Every skip says why in the journal:
# journalctl --user -u runnerup-retire
# State and the anchor: python3 -m screen_locker.runnerup_retire --status
ExecStart=/usr/bin/python3 -m screen_locker.runnerup_retire

18
runnerup-retire.timer Normal file
View File

@ -0,0 +1,18 @@
[Unit]
Description=Retry the RunnerUp retirement daily until the phone has been cleaned up
# No After=graphical-session.target: timers.target is ordered before it, and
# that After= closes a cycle systemd resolves by deleting this timer's job
# (see early-bird-workout-check.timer for the 2026-08-04 incident).
[Timer]
# The phone is not always on USB, so a failed or skipped pass is simply tried
# again: shortly after boot and once a day. Most passes are an instant no-op
# (not due yet, or already done), so the timer stays installed.
OnBootSec=10min
OnCalendar=*-*-* 19:00:00
# Persistent=true: a PC that was off at 19:00 still gets that day's pass.
Persistent=true
[Install]
WantedBy=timers.target

View File

@ -0,0 +1,215 @@
"""Retire the stock RunnerUp app a week after the PC first credits an app run.
kuhy's workout_app records runs itself now. Once the PC has credited one of
them, RunnerUp is redundant: seven days later (``GRACE``) it is backed up and
uninstalled, but only if the app has imported the RunnerUp history (a marker
the app writes) and that import matches what ``processed/`` holds. With no
anchor (no app run ever credited) it never uninstalls.
The phone is not always on USB, so ``runnerup-retire.timer`` retries daily
until this succeeds. Every outcome is a typed :class:`RetireResult` whose
reason is logged at the level it deserves: ``info`` for the normal "not due
yet", ``warning`` for a skip that needs attention, ``error`` for a failure.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
from datetime import UTC, datetime, timedelta
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from screen_locker._runnerup_retire_adb import PACKAGE, AdbError
from screen_locker._runnerup_retire_result import LEVEL, Outcome, RetireResult
from screen_locker._runnerup_retire_state import load_state, save_state
from screen_locker._runnerup_retire_tcx import app_run_ends, check_marker, find_anchor
if TYPE_CHECKING:
from screen_locker._runnerup_retire_adb import PhoneLike
from screen_locker._runnerup_retire_state import RetireState
_logger = logging.getLogger(__name__)
GRACE = timedelta(days=7)
STATE_FILE = Path.home() / ".local" / "state" / "screen-locker" / "runnerup_retire.json"
WATCH_DIR = Path.home() / "data" / "cloud" / "RunnerUp"
LOG_FILE = Path(__file__).resolve().parent / "log.json"
MARKER_NAME = ".workout_app_import.json"
@dataclass(frozen=True)
class Paths:
"""Every on-disk location, so tests (and ``--status``) can redirect them."""
state_file: Path
watch_dir: Path
log_file: Path
@classmethod
def default(cls) -> Paths:
"""The live locations (read at call time so tests can patch them)."""
return cls(STATE_FILE, WATCH_DIR, LOG_FILE)
@property
def processed(self) -> Path:
"""Where endurain-import files the RunnerUp exports it has handled."""
return self.watch_dir / "processed"
@property
def marker(self) -> Path:
"""The app's historic-import marker."""
return self.watch_dir / MARKER_NAME
def anchor_dirs(self) -> tuple[Path, Path]:
"""Where an app run's TCX can sit: the drop dir, then ``processed/``."""
return (self.watch_dir, self.processed)
def derive_anchor(paths: Paths, state: RetireState) -> datetime | None:
"""The stored anchor, else the first credit of an app run found on disk."""
return state.anchor or find_anchor(paths.log_file, paths.anchor_dirs())
def _finish(paths: Paths, state: RetireState, now: datetime, why: str) -> None:
save_state(
paths.state_file, replace(state, done_at=now.isoformat(), done_reason=why)
)
def _probe(phone: PhoneLike) -> RetireResult | tuple[str, bool]:
"""``(serial, installed)`` if the phone answers, else the result explaining why."""
if not phone.available():
return RetireResult(
Outcome.ADB_MISSING, "adb is not installed (pacman -S android-tools)"
)
try:
device = phone.find_device()
if device.serial is None:
return RetireResult(
Outcome.DEVICE_ABSENT, f"{device.reason}; retrying next run"
)
return device.serial, phone.installed(device.serial)
except AdbError as exc:
_logger.exception("RunnerUp retirement: asking the phone failed")
return RetireResult(
Outcome.PHONE_ERROR, f"asking the phone failed: {exc}", logged=True
)
def _backup(
paths: Paths, phone: PhoneLike, state: RetireState, serial: str, now: datetime
) -> RetireState | RetireResult:
"""Back the phone's exports up once; a later retry reuses a finished backup."""
if state.backup_path and Path(state.backup_path).is_dir():
return state
final = paths.watch_dir / f"runnerup_phone_backup_{now:%Y-%m-%d}"
try:
made, files = phone.backup(serial, final)
except (AdbError, OSError) as exc:
_logger.exception("RunnerUp retirement: backup failed")
return RetireResult(Outcome.BACKUP_FAILED, f"backup failed: {exc}", logged=True)
_logger.info("Backed up %d RunnerUp TCX files to %s", files, made)
state = replace(state, backup_path=str(made))
save_state(paths.state_file, state)
return state
def _retire(
paths: Paths, phone: PhoneLike, state: RetireState, now: datetime, *, dry_run: bool
) -> RetireResult:
"""Everything after "it is due and the marker is good": the phone steps."""
probed = _probe(phone)
if isinstance(probed, RetireResult):
return probed
serial, present = probed
if not present:
if not dry_run:
_finish(paths, state, now, f"{PACKAGE} was already absent")
return RetireResult(Outcome.ALREADY_GONE, f"{PACKAGE} is already absent")
if dry_run:
return RetireResult(
Outcome.DRY_RUN, "would back up and uninstall (no changes made)"
)
backed = _backup(paths, phone, state, serial, now)
if isinstance(backed, RetireResult):
return backed
try:
phone.uninstall(serial)
except AdbError as exc:
_logger.exception("RunnerUp retirement: uninstall failed")
return RetireResult(
Outcome.UNINSTALL_FAILED, f"uninstall failed: {exc}", logged=True
)
_finish(paths, backed, now, f"uninstalled after backup to {backed.backup_path}")
return RetireResult(
Outcome.UNINSTALLED,
f"{PACKAGE} uninstalled; backup in {backed.backup_path}",
)
def _no_anchor(paths: Paths) -> RetireResult:
"""Why there is no anchor; a missing source is a warning, not "nothing yet"."""
absent = [str(p) for p in (paths.watch_dir, paths.log_file) if not p.exists()]
if absent:
return RetireResult(
Outcome.SOURCES_MISSING,
f"cannot look for app runs, missing: {', '.join(absent)}",
)
seen = len(app_run_ends(paths.anchor_dirs()))
return RetireResult(
Outcome.NO_ANCHOR,
f"no app-recorded run credited yet ({seen} app TCX on disk); nothing to retire",
)
def _gate(
paths: Paths, state: RetireState, now: datetime, *, dry_run: bool
) -> RetireState | RetireResult:
"""The no-phone checks; a state back means "due, marker good: go on"."""
if state.done_at:
return RetireResult(
Outcome.ALREADY_DONE, f"done {state.done_at}: {state.done_reason}"
)
anchor = derive_anchor(paths, state)
if anchor is None:
return _no_anchor(paths)
if not state.anchor_at:
state = replace(state, anchor_at=anchor.isoformat())
if not dry_run:
save_state(paths.state_file, state)
due = anchor + GRACE
if now < due:
return RetireResult(
Outcome.NOT_DUE, f"due {due:%Y-%m-%d %H:%M} (anchor {anchor:%Y-%m-%d})"
)
marker = check_marker(paths.marker, paths.processed)
if not marker.ok:
return RetireResult(
Outcome.MARKER_INVALID, f"{marker.reason}; NOT uninstalling"
)
return state
def run_retire(
paths: Paths,
phone: PhoneLike,
now: datetime | None = None,
*,
dry_run: bool = False,
) -> RetireResult:
"""One pass: uninstall RunnerUp if (and only if) every condition holds."""
when = now or datetime.now(UTC)
gated = _gate(paths, load_state(paths.state_file), when, dry_run=dry_run)
if isinstance(gated, RetireResult):
result = gated
else:
result = _retire(paths, phone, gated, when, dry_run=dry_run)
if not result.logged:
_logger.log(
LEVEL.get(result.outcome, logging.INFO),
"RunnerUp retirement: %s: %s",
result.outcome.value,
result.reason,
)
return result

View File

@ -0,0 +1,181 @@
"""The phone side of the RunnerUp retirement: find it, back it up, uninstall.
Every call carries ``-s <serial>`` and goes through one ``run`` seam, so tests
never touch a device. adb's exit code is not trusted for the uninstall: it
counts only when the output says ``Success`` AND ``pm list packages`` no
longer lists the package.
"""
from __future__ import annotations
from dataclasses import dataclass
import logging
from pathlib import Path
import shutil
import subprocess
from typing import TYPE_CHECKING, Any, NoReturn, Protocol
if TYPE_CHECKING:
from collections.abc import Callable
_logger = logging.getLogger(__name__)
PHONE_SERIAL = "23181JEGR08034"
PACKAGE = "org.runnerup.free"
REMOTE_DIR = "/sdcard/Documents/RunnerUp"
_ADB_TIMEOUT_S = 50
# The whole export history (TCX + GPX) over wifi adb; the oneshot unit has no
# start timeout, so a slow pull is allowed to finish.
_PULL_TIMEOUT_S = 900
class AdbError(RuntimeError):
"""An adb call failed; the message says what and why."""
def _fail(message: str) -> NoReturn:
raise AdbError(message)
@dataclass(frozen=True)
class Device:
"""Outcome of looking for the phone: the adb serial to use, or why not."""
serial: str | None
reason: str
class PhoneLike(Protocol):
"""What the retirement needs from a phone (tests substitute a fake)."""
def available(self) -> bool:
"""Whether adb can be run at all."""
def find_device(self) -> Device:
"""The attached phone, or why there is none."""
def installed(self, dev: str, *, hidden: bool = True) -> bool:
"""Whether RunnerUp is on the phone."""
def backup(self, dev: str, final: Path) -> tuple[Path, int]:
"""Pull the exports to ``final``."""
def uninstall(self, dev: str) -> None:
"""Uninstall RunnerUp or raise ``AdbError``."""
class Phone:
"""adb calls against one phone, with the process runner injectable."""
def __init__(
self,
serial: str = PHONE_SERIAL,
*,
which: Callable[[str], str | None] = shutil.which,
run: Callable[..., Any] = subprocess.run,
) -> None:
"""Pin the phone's serial; ``which``/``run`` are the test seams."""
self.serial = serial
self._which = which
self._run = run
def available(self) -> bool:
"""Whether an ``adb`` binary is on PATH."""
return self._which("adb") is not None
def _adb(self, *args: str, timeout: int = _ADB_TIMEOUT_S) -> str:
cmd = ["adb", *args]
try:
done = self._run(
cmd, capture_output=True, text=True, timeout=timeout, check=False
)
except (OSError, subprocess.TimeoutExpired) as exc:
msg = f"{' '.join(cmd)} did not run: {exc}"
raise AdbError(msg) from exc
if done.returncode:
detail = (done.stdout + done.stderr).strip()
_fail(f"{' '.join(cmd)} exited {done.returncode}: {detail}")
return str(done.stdout)
def _is_phone(self, serial: str) -> bool:
"""Whether an ``adb devices`` entry is the phone.
USB and mDNS serials embed the phone's serial; a plain ``ip:port``
wifi entry does not, so that one is asked for its ``ro.serialno``.
"""
if self.serial in serial:
return True
if ":" not in serial:
return False
try:
asked = self._adb("-s", serial, "shell", "getprop", "ro.serialno")
except AdbError as exc:
_logger.warning("Could not read the serial of %s (%s)", serial, exc)
return False
return asked.strip() == self.serial
def find_device(self) -> Device:
"""The attached phone, over USB or wifi (a wireless serial embeds it)."""
listing = self._adb("devices")
states: list[str] = []
for line in listing.splitlines()[1:]:
serial, _, state = line.partition("\t")
if not self._is_phone(serial):
continue
if state.strip() == "device":
return Device(serial, "attached")
states.append(state.strip())
if states:
return Device(None, f"phone is {'/'.join(states)}, not ready")
return Device(None, f"phone {self.serial} is not attached")
def installed(self, dev: str, *, hidden: bool = True) -> bool:
"""Whether the package is on the phone (exact ``package:`` line).
``hidden`` adds ``-u`` so an app that focus mode hides or disables
still counts as present; it must not be mistaken for an uninstall.
"""
flag = ["-u"] if hidden else []
out = self._adb("-s", dev, "shell", "pm", "list", "packages", *flag, PACKAGE)
return f"package:{PACKAGE}" in out.split()
def backup(self, dev: str, final: Path) -> tuple[Path, int]:
"""Pull the phone's export folder next to ``final``; return (dir, tcx count).
Pulled into a staging dir and renamed only once every phone ``.tcx``
is on disk, so a half backup never looks like a finished one. The
result is a subfolder, never top-level: a top-level ``*.tcx`` would be
credited by runnerup-watch.
"""
listing = self._adb("-s", dev, "shell", "ls", REMOTE_DIR)
wanted = sum(1 for n in listing.split() if n.endswith(".tcx"))
staging = final.with_name(final.name + ".partial")
shutil.rmtree(staging, ignore_errors=True)
staging.mkdir(parents=True)
self._adb("-s", dev, "pull", REMOTE_DIR, str(staging), timeout=_PULL_TIMEOUT_S)
pulled = staging / Path(REMOTE_DIR).name
got = len(list(pulled.rglob("*.tcx"))) if pulled.is_dir() else -1
if got < wanted:
_fail(f"backup pulled {got} of {wanted} TCX files into {staging}")
target, n = final, 1
while target.exists():
n += 1
target = final.with_name(f"{final.name}-{n}")
pulled.rename(target)
staging.rmdir()
return target, got
def uninstall(self, dev: str) -> None:
"""Uninstall the package and prove it is gone, or raise ``AdbError``."""
try:
out = self._adb("-s", dev, "uninstall", PACKAGE)
except AdbError as exc:
# adb exits 1 with "Failure [DELETE_FAILED_...]": keep that reason
# (a device-owner policy can block it) in the error.
msg = f"uninstall refused: {exc}"
raise AdbError(msg) from exc
if "Success" not in out:
_fail(f"uninstall did not report Success: {out.strip()!r}")
if self.installed(dev, hidden=False):
_fail(f"{PACKAGE} is still listed after uninstall")
_logger.info("Uninstalled %s from %s", PACKAGE, dev)

View File

@ -0,0 +1,62 @@
"""Outcomes of one RunnerUp-retirement pass, and how loudly each is logged."""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
import logging
__all__ = ["LEVEL", "Outcome", "RetireResult"]
class Outcome(StrEnum):
"""How a run ended; the value is what the journal shows."""
UNINSTALLED = "uninstalled"
ALREADY_GONE = "already-gone"
ALREADY_DONE = "already-done"
NO_ANCHOR = "no-anchor"
SOURCES_MISSING = "sources-missing"
NOT_DUE = "not-due"
DRY_RUN = "dry-run"
DEVICE_ABSENT = "device-absent"
MARKER_INVALID = "marker-invalid"
ADB_MISSING = "adb-missing"
PHONE_ERROR = "phone-error"
BACKUP_FAILED = "backup-failed"
UNINSTALL_FAILED = "uninstall-failed"
# Level per outcome; the failures also make the unit exit non-zero.
LEVEL = {
Outcome.DEVICE_ABSENT: logging.WARNING,
Outcome.SOURCES_MISSING: logging.WARNING,
Outcome.MARKER_INVALID: logging.WARNING,
Outcome.ADB_MISSING: logging.ERROR,
Outcome.PHONE_ERROR: logging.ERROR,
Outcome.BACKUP_FAILED: logging.ERROR,
Outcome.UNINSTALL_FAILED: logging.ERROR,
}
_NONZERO = frozenset(
{
Outcome.MARKER_INVALID,
Outcome.ADB_MISSING,
Outcome.PHONE_ERROR,
Outcome.BACKUP_FAILED,
Outcome.UNINSTALL_FAILED,
}
)
@dataclass(frozen=True)
class RetireResult:
"""What happened and why, in a sentence a human can act on."""
outcome: Outcome
reason: str
logged: bool = False # the failure was already logged where it was caught
@property
def ok(self) -> bool:
"""False for outcomes the unit should surface as failed."""
return self.outcome not in _NONZERO

View File

@ -0,0 +1,71 @@
"""The retirement's own memory: the anchor, the backup, the done stamp.
One small JSON file (path: ``_runnerup_retire.STATE_FILE``). Written
atomically and only by a real run (``--status`` and ``--dry-run`` never write),
so the file is also the proof that a run happened. The anchor is stored once
and never moved: a later, earlier-looking credit must not push the deadline.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, fields
from datetime import datetime
import json
import logging
import os
from pathlib import Path
import tempfile
_logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class RetireState:
"""What a previous run recorded (all ISO strings, empty until known)."""
anchor_at: str = ""
backup_path: str = ""
done_at: str = ""
done_reason: str = ""
@property
def anchor(self) -> datetime | None:
"""The stored anchor as an aware datetime, or None."""
return datetime.fromisoformat(self.anchor_at) if self.anchor_at else None
def load_state(path: Path) -> RetireState:
"""Read the state; a missing file is a fresh start, a bad one is loud."""
if not path.exists():
return RetireState()
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
_logger.warning(
"Retire state %s is unreadable (%s): starting from scratch, so the "
"anchor is re-derived and the uninstall re-checked",
path,
exc,
)
return RetireState()
if not isinstance(raw, dict):
_logger.warning("Retire state %s is not a JSON object: ignored", path)
return RetireState()
known = {f.name for f in fields(RetireState)}
clean = {k: v for k, v in raw.items() if k in known and isinstance(v, str)}
try:
state = RetireState(**clean)
_ = state.anchor
except ValueError as exc:
_logger.warning("Retire state %s holds a bad anchor (%s): ignored", path, exc)
return RetireState()
return state
def save_state(path: Path, state: RetireState) -> None:
"""Atomically replace the state file (creates the directory on first write)."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".retire-", suffix=".tmp")
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(asdict(state), handle, indent=2)
Path(tmp).replace(path)

View File

@ -0,0 +1,210 @@
"""What the RunnerUp retirement reads off disk: app runs, the marker, the anchor.
Split from :mod:`screen_locker._runnerup_retire` (250-line cap). Everything
here is read-only; nothing touches the phone.
Telling the two sources apart is done on the TCX *content* (``<Author>`` or
``<Creator>`` named ``kuhy workout_app``, the app's ``kRunSourceName``), never
on the file name: the app may name its files however it likes.
The anchor is "when the PC first CREDITED an app run". The credit chokepoint
(``log.json``) stores a run's TCX end as ``completed_at`` on its
``runnerup_verified`` entry and stamps the entry itself with the moment the PC
wrote it. So the anchor is the ``timestamp`` of the entry whose
``completed_at`` equals an app TCX's last trackpoint. Joining on the end time
(not the day) is what makes a same-day RunnerUp run, which fills the day's one
credit slot first, correctly yield no anchor for the app run.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
import json
import logging
import re
from typing import TYPE_CHECKING, Any
from screen_locker._log_io import load_workout_log
from screen_locker._runnerup_tcx import parse_tcx_file
if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path
_logger = logging.getLogger(__name__)
APP_SOURCE_NAME = "kuhy workout_app"
_APP_RE = re.compile(
rb"<(?:Author|Creator)\b[^>]*>\s*<Name>\s*"
+ re.escape(APP_SOURCE_NAME.encode())
+ rb"\s*</Name>"
)
# The WebDAV copy of a RunnerUp export may carry the device name
# (RunnerUp_Pixel_6a_2026-...) that the phone's own copy lacks.
_DEVICE_PREFIX = re.compile(r"^RunnerUp_(?:[A-Za-z0-9]+_)*?(?=\d{4}-\d{2}-\d{2}-)")
_END_TOLERANCE_S = 1.0
def run_key(name: str) -> str:
"""A run's identity: its file name without any device-name prefix."""
return _DEVICE_PREFIX.sub("RunnerUp_", name)
def list_tcx(directory: Path) -> list[Path]:
"""Finished ``*.tcx`` files directly in ``directory`` (dotfiles are partial)."""
if not directory.is_dir():
return []
return sorted(
p for p in directory.glob("*.tcx") if p.is_file() and not p.name.startswith(".")
)
def is_app_tcx(path: Path) -> bool:
"""Whether the TCX names the new app as its author or creator."""
try:
data = path.read_bytes()
except OSError as exc:
_logger.warning(
"Cannot read %s (%s): counting it as a RunnerUp file", path, exc
)
return False
return bool(_APP_RE.search(data))
def _ended_at(path: Path) -> float | None:
"""The run's end exactly as the credit path computed it (same parser)."""
data = parse_tcx_file(str(path))
if data is None or data.get("ended_at") is None:
_logger.warning("App TCX %s has no usable end time: it cannot anchor", path)
return None
return float(data["ended_at"])
def _credited_at(entry: dict[str, Any]) -> datetime | None:
try:
stamp = datetime.fromisoformat(str(entry["timestamp"]))
except (KeyError, ValueError) as exc:
_logger.warning("Credit entry has no usable timestamp (%r): skipped", exc)
return None
return stamp if stamp.tzinfo else stamp.astimezone()
def _as_unix(raw: object) -> float | None:
"""A unix time from a number or numeric string (the log stores both)."""
if isinstance(raw, int | float) and not isinstance(raw, bool):
return float(raw)
if isinstance(raw, str) and re.fullmatch(r"\d+(\.\d+)?", raw):
return float(raw)
return None
def _credit_ends(log_file: Path) -> list[tuple[float, datetime]]:
"""``(TCX end, PC credit time)`` of every credited run that recorded its end."""
found: list[tuple[float, datetime]] = []
for entries in load_workout_log(log_file).values():
for entry in entries:
data = entry.get("workout_data") or {}
if data.get("type") != "runnerup_verified":
continue
end = _as_unix(data.get("completed_at"))
if end is None:
continue # an older entry that never stored its run's end
when = _credited_at(entry)
if when is not None:
found.append((end, when))
return found
def app_run_ends(dirs: Iterable[Path]) -> list[float]:
"""The end time of every app-authored TCX that has a usable one."""
return [
end
for directory in dirs
for path in list_tcx(directory)
if is_app_tcx(path) and (end := _ended_at(path)) is not None
]
def find_anchor(log_file: Path, dirs: Iterable[Path]) -> datetime | None:
"""When the PC first credited an app-recorded run, or None if it never did."""
ends = app_run_ends(dirs)
credited = [
when
for run_end, when in _credit_ends(log_file)
if any(abs(run_end - end) <= _END_TOLERANCE_S for end in ends)
]
return min(credited) if credited else None
@dataclass(frozen=True)
class MarkerCheck:
"""Verdict on the app's historic-import marker."""
ok: bool
reason: str
def _bad(reason: str) -> MarkerCheck:
return MarkerCheck(ok=False, reason=reason)
def _marker_names(marker: object) -> tuple[list[str] | None, str]:
"""The marker's ``tcx_names`` if its shape is valid, else a reason."""
if not isinstance(marker, dict):
return None, "marker is not a JSON object"
names, count = marker.get("tcx_names"), marker.get("count")
if not isinstance(marker.get("completed_at"), str) or not marker["completed_at"]:
return None, "marker has no completed_at"
if not isinstance(names, list) or not all(isinstance(n, str) for n in names):
return None, "marker tcx_names is not a list of names"
if isinstance(count, bool) or not isinstance(count, int) or count != len(names):
return None, f"marker count {count!r} != {len(names)} listed names"
if any("/" in n or n.startswith(".") for n in names):
return None, "marker tcx_names must be bare file names"
return names, ""
def _read_marker(marker_file: Path) -> tuple[object, str]:
"""The parsed marker JSON, or ``(None, why it could not be read)``."""
if not marker_file.exists():
why = f"{marker_file} is missing: the app has not imported yet"
else:
try:
return json.loads(marker_file.read_text(encoding="utf-8")), ""
except (OSError, ValueError) as exc:
why = f"{marker_file} is unreadable ({exc})"
_logger.warning("Import marker problem: %s", why)
return None, why
_logger.warning("Import marker problem: %s", why)
return None, why
def _compare(names: list[str], processed: Path) -> MarkerCheck:
listed = {run_key(n) for n in names}
if len(listed) != len(names):
return _bad("marker lists the same run more than once")
have = {run_key(p.name) for p in list_tcx(processed) if not is_app_tcx(p)}
if absent := sorted(listed - have):
return _bad(f"{len(absent)} listed run(s) not in processed/: {absent[:3]}")
if unlisted := sorted(have - listed):
return _bad(
f"{len(unlisted)} RunnerUp run(s) in processed/ are not in the "
f"marker ({unlisted[:3]}): re-run the app's import"
)
return MarkerCheck(ok=True, reason=f"{len(listed)} runs match")
def check_marker(marker_file: Path, processed: Path) -> MarkerCheck:
"""Validate the app's import marker against what ``processed/`` really holds.
Valid means: the file parses, ``count`` equals the number of listed names,
and the listed runs are exactly the RunnerUp-recorded (non-app) runs in
``processed/``. A run is counted once however many copies exist (the
device-prefixed WebDAV twin and the phone-named copy are one run).
"""
marker, why = _read_marker(marker_file)
if why:
return _bad(why)
names, reason = _marker_names(marker)
return _compare(names, processed) if names is not None else _bad(reason)

View File

@ -65,48 +65,53 @@ class RunnerUpTcxMixin:
shutil.rmtree(tmp_dir, ignore_errors=True)
def _parse_tcx(self, tcx_path: str) -> dict[str, Any] | None:
"""Parse a local TCX file and return activity summary dict.
"""Parse a local TCX file (see :func:`parse_tcx_file`)."""
return parse_tcx_file(tcx_path)
Sums ``TotalTimeSeconds`` and ``DistanceMeters`` across all Laps so
multi-segment runs (pause/resume) are counted in full.
"""
try:
tree = ET.parse(tcx_path)
except ET.ParseError as exc:
_logger.warning(
"TCX file %s is not valid XML (%s) — the run it describes CANNOT "
"be verified and will not count",
tcx_path,
exc,
)
return None
root = tree.getroot()
activity = root.find(f".//{{{_TCX_NS}}}Activity")
if activity is None:
_logger.info("No Activity element in TCX file")
return None
def parse_tcx_file(tcx_path: str) -> dict[str, Any] | None:
"""Parse a local TCX file and return activity summary dict.
sport_str = activity.get("Sport", "")
sport_int = _TCX_SPORT_TO_INT.get(sport_str, -1)
Sums ``TotalTimeSeconds`` and ``DistanceMeters`` across all Laps so
multi-segment runs (pause/resume) are counted in full.
"""
try:
tree = ET.parse(tcx_path)
except ET.ParseError as exc:
_logger.warning(
"TCX file %s is not valid XML (%s) — the run it describes CANNOT "
"be verified and will not count",
tcx_path,
exc,
)
return None
total_seconds = 0.0
total_distance = 0.0
for lap in activity.findall(f"{{{_TCX_NS}}}Lap"):
t_elem = lap.find(f"{{{_TCX_NS}}}TotalTimeSeconds")
d_elem = lap.find(f"{{{_TCX_NS}}}DistanceMeters")
if t_elem is not None and t_elem.text:
total_seconds += float(t_elem.text)
if d_elem is not None and d_elem.text:
total_distance += float(d_elem.text)
root = tree.getroot()
activity = root.find(f".//{{{_TCX_NS}}}Activity")
if activity is None:
_logger.info("No Activity element in TCX file")
return None
return {
"sport": sport_int,
"duration_seconds": int(total_seconds),
"distance_m": total_distance,
"walking": is_walking_export(Path(tcx_path).name, sport_str),
**track_summary(activity),
}
sport_str = activity.get("Sport", "")
sport_int = _TCX_SPORT_TO_INT.get(sport_str, -1)
total_seconds = 0.0
total_distance = 0.0
for lap in activity.findall(f"{{{_TCX_NS}}}Lap"):
t_elem = lap.find(f"{{{_TCX_NS}}}TotalTimeSeconds")
d_elem = lap.find(f"{{{_TCX_NS}}}DistanceMeters")
if t_elem is not None and t_elem.text:
total_seconds += float(t_elem.text)
if d_elem is not None and d_elem.text:
total_distance += float(d_elem.text)
return {
"sport": sport_int,
"duration_seconds": int(total_seconds),
"distance_m": total_distance,
"walking": is_walking_export(Path(tcx_path).name, sport_str),
**track_summary(activity),
}
def _mark_walk(data: dict[str, Any] | None, name: str) -> dict[str, Any] | None:

View File

@ -0,0 +1,99 @@
"""``python3 -m screen_locker.runnerup_retire``: uninstall RunnerUp, a week on.
What ``runnerup-retire.service`` runs. ``--status`` prints anchor, due date,
marker validity and (with ``--query-phone``) whether RunnerUp is installed;
it never writes and never talks to the phone unless asked. ``--dry-run`` runs
every check, including the read-only adb queries, but writes nothing, pulls
nothing and uninstalls nothing. The exit code is non-zero only for outcomes
that need a human (bad marker, adb missing, failed backup or uninstall).
"""
from __future__ import annotations
import argparse
from datetime import UTC, datetime
import logging
import sys
from typing import TYPE_CHECKING
from screen_locker._runnerup_retire import (
GRACE,
Paths,
derive_anchor,
run_retire,
)
from screen_locker._runnerup_retire_adb import PHONE_SERIAL, AdbError, Phone
from screen_locker._runnerup_retire_state import load_state
from screen_locker._runnerup_retire_tcx import check_marker
if TYPE_CHECKING:
from screen_locker._runnerup_retire_adb import PhoneLike
__all__ = ["main", "status_lines"]
_logger = logging.getLogger(__name__)
def _installed_line(phone: PhoneLike, *, query: bool) -> str:
if not query:
return "installed: not queried (add --query-phone)"
try:
device = phone.find_device()
if device.serial is None:
return f"installed: unknown ({device.reason})"
return f"installed: {'yes' if phone.installed(device.serial) else 'no'}"
except AdbError as exc:
_logger.warning("--status could not ask the phone: %s", exc)
return f"installed: unknown ({exc})"
def status_lines(
paths: Paths, phone: PhoneLike, now: datetime, *, query_phone: bool = False
) -> list[str]:
"""The ``--status`` report. Read-only: nothing is created or saved."""
state = load_state(paths.state_file)
anchor = derive_anchor(paths, state)
if anchor is None:
anchor_line, due_line = "anchor: none (no app run credited yet)", "due: never"
else:
origin = "stored" if state.anchor_at else "derived, not yet stored"
due = anchor + GRACE
days = (due - now).total_seconds() / 86400
anchor_line = f"anchor: {anchor.isoformat()} ({origin})"
due_line = f"due: {due:%Y-%m-%d %H:%M} ({days:+.1f} days)"
marker = check_marker(paths.marker, paths.processed)
return [
anchor_line,
due_line,
f"marker: {'valid' if marker.ok else 'INVALID'} ({marker.reason})",
f"done: {state.done_at or 'no'}",
_installed_line(phone, query=query_phone),
]
def main(argv: list[str] | None = None) -> int:
"""CLI entry; returns the process exit code."""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n", maxsplit=1)[0])
parser.add_argument(
"--status", action="store_true", help="print state, change nothing"
)
parser.add_argument(
"--dry-run", action="store_true", help="check everything, change nothing"
)
parser.add_argument(
"--query-phone", action="store_true", help="with --status: ask adb"
)
parser.add_argument("--serial", default=PHONE_SERIAL, help="phone adb serial")
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
paths, phone = Paths.default(), Phone(args.serial)
if args.status:
now = datetime.now(UTC)
lines = status_lines(paths, phone, now, query_phone=args.query_phone)
sys.stdout.write("\n".join(lines) + "\n")
return 0
return 0 if run_retire(paths, phone, dry_run=args.dry_run).ok else 1
if __name__ == "__main__":
sys.exit(main())

View File

@ -105,4 +105,20 @@ ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
"workday_penalty.json",
("_constants.WORKDAY_PENALTY_FILE", "_workday_penalty.WORKDAY_PENALTY_FILE"),
),
# RunnerUp retirement: the anchor/done stamp, the dufs drop directory it
# reads the marker and TCX files from (and writes the phone backup into),
# and the credit log the anchor is derived from. A test must never see, or
# create files under, the user's real RunnerUp folder.
(
"runnerup_retire.json",
("_runnerup_retire.STATE_FILE",),
),
(
"RunnerUp",
("_runnerup_retire.WATCH_DIR",),
),
(
"retire_log.json",
("_runnerup_retire.LOG_FILE",),
),
)

View File

@ -0,0 +1,137 @@
"""Builders for the RunnerUp retirement tests: TCX files, marker, credit log."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
import json
from typing import TYPE_CHECKING, Any
from screen_locker._runnerup_retire import Paths
from screen_locker._runnerup_retire_adb import AdbError, Device
if TYPE_CHECKING:
from pathlib import Path
_NS = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
APP = "kuhy workout_app"
# 2026-11-01T10:30:00Z, the end of every TCX built by default.
END_UNIX = 1793529000.0
def tcx_text(
*, author: str = "RunnerUp", creator: str = "", end: str = "2026-11-01T10:30:00Z"
) -> str:
"""A tiny TCX: two trackpoints (the last is the run's end) and an author."""
creator_xml = f"<Creator><Name>{creator}</Name></Creator>" if creator else ""
return (
f'<?xml version="1.0"?><TrainingCenterDatabase xmlns="{_NS}"><Activities>'
'<Activity Sport="Running"><Id>2026-11-01T10:00:00Z</Id>'
"<Lap><TotalTimeSeconds>1800</TotalTimeSeconds>"
"<DistanceMeters>5000</DistanceMeters><Track>"
"<Trackpoint><Time>2026-11-01T10:00:00Z</Time>"
"<DistanceMeters>0</DistanceMeters></Trackpoint>"
f"<Trackpoint><Time>{end}</Time><DistanceMeters>5000</DistanceMeters>"
f"</Trackpoint></Track></Lap>{creator_xml}</Activity></Activities>"
f'<Author xsi:type="Application_t" xmlns:xsi="x"><Name>{author}</Name>'
"</Author></TrainingCenterDatabase>"
)
def put_tcx(folder: Path, name: str, **kwargs: str) -> Path:
"""Write a TCX named ``name`` into ``folder`` (created if needed)."""
folder.mkdir(parents=True, exist_ok=True)
path = folder / name
path.write_text(tcx_text(**kwargs), encoding="utf-8")
return path
def put_marker(watch: Path, names: list[str], count: int | None = None) -> Path:
"""Write the app's import marker into the drop folder."""
watch.mkdir(parents=True, exist_ok=True)
marker = watch / ".workout_app_import.json"
body = {
"completed_at": "2026-11-02T08:00:00Z",
"count": len(names) if count is None else count,
"tcx_names": names,
}
marker.write_text(json.dumps(body), encoding="utf-8")
return marker
def put_log(log_file: Path, entries: dict[str, list[dict[str, Any]]]) -> None:
"""Write a day-keyed credit log."""
log_file.write_text(json.dumps(entries), encoding="utf-8")
def credit(
timestamp: str, completed_at: object = None, kind: str = "runnerup_verified"
) -> dict[str, Any]:
"""One log entry as the credit chokepoint writes it."""
data: dict[str, Any] = {"type": kind}
if completed_at is not None:
data["completed_at"] = completed_at
return {"timestamp": timestamp, "workout_data": data}
ANCHOR = datetime(2026, 11, 1, 10, 45, tzinfo=UTC)
DUE = ANCHOR + timedelta(days=7)
RUN = "RunnerUp_2026-08-12-17-42-11_Running.tcx"
@dataclass
class FakePhone:
"""Records what the retirement asked of the phone."""
adb: bool = True
device: Device = field(default_factory=lambda: Device("S", "attached"))
present: bool = True
ask_error: AdbError | None = None
backup_error: Exception | None = None
uninstall_error: AdbError | None = None
calls: list[str] = field(default_factory=list)
def available(self) -> bool:
"""Available."""
return self.adb
def find_device(self) -> Device:
"""Find device."""
if self.ask_error:
raise self.ask_error
return self.device
def installed(self, dev: str, *, hidden: bool = True) -> bool:
"""Installed."""
self.calls.append(f"installed {dev}")
return self.present
def backup(self, dev: str, final: Path) -> tuple[Path, int]:
"""Backup."""
self.calls.append("backup")
if self.backup_error:
raise self.backup_error
final.mkdir(parents=True)
return final, 3
def uninstall(self, dev: str) -> None:
"""Uninstall."""
self.calls.append("uninstall")
if self.uninstall_error:
raise self.uninstall_error
def world(tmp_path: Path, *, anchored: bool = True, marker: bool = True) -> Paths:
"""A drop folder with one RunnerUp run, one app run, and the credit log."""
paths = Paths(
tmp_path / "state" / "s.json", tmp_path / "drop", tmp_path / "log.json"
)
put_tcx(paths.processed, RUN)
put_tcx(paths.processed, "app.tcx", author=APP)
put_log(
paths.log_file,
{"d": [credit(ANCHOR.isoformat(), END_UNIX)]} if anchored else {},
)
if marker:
put_marker(paths.watch_dir, [RUN])
return paths

View File

@ -0,0 +1,190 @@
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns3="http://www.garmin.com/xmlschemas/ActivityExtension/v2" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Running">
<Id>2026-08-12T15:42:11Z</Id>
<Lap StartTime="2026-08-12T15:42:11Z">
<TotalTimeSeconds>624</TotalTimeSeconds>
<DistanceMeters>983.6306355595589</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-08-12T15:42:12Z</Time>
<Position>
<LatitudeDegrees>48.858438076</LatitudeDegrees>
<LongitudeDegrees>2.294584871</LongitudeDegrees>
</Position>
<AltitudeMeters>110.06611511572041</AltitudeMeters>
<DistanceMeters>2.142966628074646</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>54</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:13Z</Time>
<Position>
<LatitudeDegrees>48.858442867</LatitudeDegrees>
<LongitudeDegrees>2.294574705</LongitudeDegrees>
</Position>
<AltitudeMeters>109.65041623678366</AltitudeMeters>
<DistanceMeters>3.0187163949012756</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>53</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:37Z</Time>
<Position>
<LatitudeDegrees>48.858578090</LatitudeDegrees>
<LongitudeDegrees>2.294260282</LongitudeDegrees>
</Position>
<AltitudeMeters>102.71014718222068</AltitudeMeters>
<DistanceMeters>31.116633534431458</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>65</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:48Z</Time>
<Position>
<LatitudeDegrees>48.858744365</LatitudeDegrees>
<LongitudeDegrees>2.294188828</LongitudeDegrees>
</Position>
<AltitudeMeters>101.26072111921606</AltitudeMeters>
<DistanceMeters>50.64840912818909</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>61</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:42:56Z</Time>
<Position>
<LatitudeDegrees>48.858792955</LatitudeDegrees>
<LongitudeDegrees>2.294100028</LongitudeDegrees>
</Position>
<AltitudeMeters>100.58585072961351</AltitudeMeters>
<DistanceMeters>58.97427588701248</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>58</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:43:42Z</Time>
<Position>
<LatitudeDegrees>48.858859857</LatitudeDegrees>
<LongitudeDegrees>2.292925949</LongitudeDegrees>
</Position>
<AltitudeMeters>99.60869064520372</AltitudeMeters>
<DistanceMeters>140.32738709449768</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>57</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
</Track>
</Lap>
<Lap StartTime="2026-08-12T15:52:36Z">
<TotalTimeSeconds>626</TotalTimeSeconds>
<DistanceMeters>980.7304027080536</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-08-12T15:52:36Z</Time>
<Position>
<LatitudeDegrees>48.859968549</LatitudeDegrees>
<LongitudeDegrees>2.282023519</LongitudeDegrees>
</Position>
<AltitudeMeters>99.76934097304894</AltitudeMeters>
<DistanceMeters>1003.5486820391379</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>59</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:52:37Z</Time>
<Position>
<LatitudeDegrees>48.859990492</LatitudeDegrees>
<LongitudeDegrees>2.282025531</LongitudeDegrees>
</Position>
<AltitudeMeters>100.06562741186055</AltitudeMeters>
<DistanceMeters>1005.9941445044242</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>57</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:54:28Z</Time>
<Position>
<LatitudeDegrees>48.861645306</LatitudeDegrees>
<LongitudeDegrees>2.281974721</LongitudeDegrees>
</Position>
<AltitudeMeters>99.66943152941295</AltitudeMeters>
<DistanceMeters>1190.9687945595942</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>55</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
<Trackpoint>
<Time>2026-08-12T15:54:46Z</Time>
<Position>
<LatitudeDegrees>48.861872213</LatitudeDegrees>
<LongitudeDegrees>2.282046494</LongitudeDegrees>
</Position>
<AltitudeMeters>99.35286804810477</AltitudeMeters>
<DistanceMeters>1217.0878333947621</DistanceMeters>
<Extensions>
<ns3:TPX>
<ns3:RunCadence>58</ns3:RunCadence>
</ns3:TPX>
</Extensions>
</Trackpoint>
</Track>
</Lap>
<Notes></Notes>
<Creator xsi:type="Device_t">
<Name>RunnerUp Pixel 6a with barometer</Name>
<UnitId>0</UnitId>
<ProductID>0</ProductID>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<BuildMajor>0</BuildMajor>
<BuildMinor>0</BuildMinor>
</Version>
</Creator>
</Activity>
</Activities>
<Author xsi:type="Application_t">
<Name>org.runnerup - 2.11.0.1 - 23000372</Name>
<Build>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Build>
<LangID>en</LangID>
<PartNumber>000-00000-00</PartNumber>
</Author>
</TrainingCenterDatabase>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,748 @@
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Running">
<Id>2026-11-09T16:30:00Z</Id>
<Lap StartTime="2026-11-09T16:30:00Z">
<TotalTimeSeconds>1560</TotalTimeSeconds>
<DistanceMeters>4212.014</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2026-11-09T16:30:00Z</Time>
<Position>
<LatitudeDegrees>48.8584000</LatitudeDegrees>
<LongitudeDegrees>2.2945000</LongitudeDegrees>
</Position>
<AltitudeMeters>35.0</AltitudeMeters>
<DistanceMeters>0.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:30:20Z</Time>
<Position>
<LatitudeDegrees>48.8587720</LatitudeDegrees>
<LongitudeDegrees>2.2949745</LongitudeDegrees>
</Position>
<AltitudeMeters>35.0</AltitudeMeters>
<DistanceMeters>54.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:30:40Z</Time>
<Position>
<LatitudeDegrees>48.8591285</LatitudeDegrees>
<LongitudeDegrees>2.2954757</LongitudeDegrees>
</Position>
<AltitudeMeters>35.3</AltitudeMeters>
<DistanceMeters>107.999</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:31:00Z</Time>
<Position>
<LatitudeDegrees>48.8594688</LatitudeDegrees>
<LongitudeDegrees>2.2960023</LongitudeDegrees>
</Position>
<AltitudeMeters>35.5</AltitudeMeters>
<DistanceMeters>161.998</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:31:20Z</Time>
<Position>
<LatitudeDegrees>48.8597926</LatitudeDegrees>
<LongitudeDegrees>2.2965524</LongitudeDegrees>
</Position>
<AltitudeMeters>35.8</AltitudeMeters>
<DistanceMeters>215.997</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:31:40Z</Time>
<Position>
<LatitudeDegrees>48.8600999</LatitudeDegrees>
<LongitudeDegrees>2.2971240</LongitudeDegrees>
</Position>
<AltitudeMeters>36.1</AltitudeMeters>
<DistanceMeters>269.998</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:32:00Z</Time>
<Position>
<LatitudeDegrees>48.8603909</LatitudeDegrees>
<LongitudeDegrees>2.2977150</LongitudeDegrees>
</Position>
<AltitudeMeters>36.3</AltitudeMeters>
<DistanceMeters>324.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:32:20Z</Time>
<Position>
<LatitudeDegrees>48.8606663</LatitudeDegrees>
<LongitudeDegrees>2.2983230</LongitudeDegrees>
</Position>
<AltitudeMeters>36.6</AltitudeMeters>
<DistanceMeters>378.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:32:40Z</Time>
<Position>
<LatitudeDegrees>48.8609269</LatitudeDegrees>
<LongitudeDegrees>2.2989459</LongitudeDegrees>
</Position>
<AltitudeMeters>36.8</AltitudeMeters>
<DistanceMeters>432.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:33:00Z</Time>
<Position>
<LatitudeDegrees>48.8611740</LatitudeDegrees>
<LongitudeDegrees>2.2995813</LongitudeDegrees>
</Position>
<AltitudeMeters>37.0</AltitudeMeters>
<DistanceMeters>485.998</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:33:20Z</Time>
<Position>
<LatitudeDegrees>48.8614092</LatitudeDegrees>
<LongitudeDegrees>2.3002272</LongitudeDegrees>
</Position>
<AltitudeMeters>37.2</AltitudeMeters>
<DistanceMeters>540.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:33:40Z</Time>
<Position>
<LatitudeDegrees>48.8616342</LatitudeDegrees>
<LongitudeDegrees>2.3008814</LongitudeDegrees>
</Position>
<AltitudeMeters>37.4</AltitudeMeters>
<DistanceMeters>594.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:34:00Z</Time>
<Position>
<LatitudeDegrees>48.8618509</LatitudeDegrees>
<LongitudeDegrees>2.3015420</LongitudeDegrees>
</Position>
<AltitudeMeters>37.5</AltitudeMeters>
<DistanceMeters>648.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:34:20Z</Time>
<Position>
<LatitudeDegrees>48.8620615</LatitudeDegrees>
<LongitudeDegrees>2.3022071</LongitudeDegrees>
</Position>
<AltitudeMeters>37.7</AltitudeMeters>
<DistanceMeters>702.000</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:34:40Z</Time>
<Position>
<LatitudeDegrees>48.8622683</LatitudeDegrees>
<LongitudeDegrees>2.3028751</LongitudeDegrees>
</Position>
<AltitudeMeters>37.8</AltitudeMeters>
<DistanceMeters>756.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:35:00Z</Time>
<Position>
<LatitudeDegrees>48.8624735</LatitudeDegrees>
<LongitudeDegrees>2.3035441</LongitudeDegrees>
</Position>
<AltitudeMeters>37.9</AltitudeMeters>
<DistanceMeters>810.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:35:20Z</Time>
<Position>
<LatitudeDegrees>48.8626796</LatitudeDegrees>
<LongitudeDegrees>2.3042125</LongitudeDegrees>
</Position>
<AltitudeMeters>37.9</AltitudeMeters>
<DistanceMeters>864.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:35:40Z</Time>
<Position>
<LatitudeDegrees>48.8628890</LatitudeDegrees>
<LongitudeDegrees>2.3048786</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>918.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:36:00Z</Time>
<Position>
<LatitudeDegrees>48.8631038</LatitudeDegrees>
<LongitudeDegrees>2.3055406</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>972.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:36:20Z</Time>
<Position>
<LatitudeDegrees>48.8633263</LatitudeDegrees>
<LongitudeDegrees>2.3061968</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>1026.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:36:40Z</Time>
<Position>
<LatitudeDegrees>48.8635585</LatitudeDegrees>
<LongitudeDegrees>2.3068452</LongitudeDegrees>
</Position>
<AltitudeMeters>38.0</AltitudeMeters>
<DistanceMeters>1080.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:37:00Z</Time>
<Position>
<LatitudeDegrees>48.8638022</LatitudeDegrees>
<LongitudeDegrees>2.3074837</LongitudeDegrees>
</Position>
<AltitudeMeters>37.9</AltitudeMeters>
<DistanceMeters>1134.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:37:20Z</Time>
<Position>
<LatitudeDegrees>48.8640589</LatitudeDegrees>
<LongitudeDegrees>2.3081103</LongitudeDegrees>
</Position>
<AltitudeMeters>37.8</AltitudeMeters>
<DistanceMeters>1188.001</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:37:40Z</Time>
<Position>
<LatitudeDegrees>48.8643301</LatitudeDegrees>
<LongitudeDegrees>2.3087227</LongitudeDegrees>
</Position>
<AltitudeMeters>37.7</AltitudeMeters>
<DistanceMeters>1242.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:38:00Z</Time>
<Position>
<LatitudeDegrees>48.8646168</LatitudeDegrees>
<LongitudeDegrees>2.3093186</LongitudeDegrees>
</Position>
<AltitudeMeters>37.6</AltitudeMeters>
<DistanceMeters>1296.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:38:20Z</Time>
<Position>
<LatitudeDegrees>48.8649196</LatitudeDegrees>
<LongitudeDegrees>2.3098958</LongitudeDegrees>
</Position>
<AltitudeMeters>37.5</AltitudeMeters>
<DistanceMeters>1350.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:38:40Z</Time>
<Position>
<LatitudeDegrees>48.8652388</LatitudeDegrees>
<LongitudeDegrees>2.3104521</LongitudeDegrees>
</Position>
<AltitudeMeters>37.3</AltitudeMeters>
<DistanceMeters>1404.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:39:00Z</Time>
<Position>
<LatitudeDegrees>48.8655746</LatitudeDegrees>
<LongitudeDegrees>2.3109853</LongitudeDegrees>
</Position>
<AltitudeMeters>37.1</AltitudeMeters>
<DistanceMeters>1457.999</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:39:20Z</Time>
<Position>
<LatitudeDegrees>48.8659267</LatitudeDegrees>
<LongitudeDegrees>2.3114938</LongitudeDegrees>
</Position>
<AltitudeMeters>36.9</AltitudeMeters>
<DistanceMeters>1512.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:39:40Z</Time>
<Position>
<LatitudeDegrees>48.8662946</LatitudeDegrees>
<LongitudeDegrees>2.3119758</LongitudeDegrees>
</Position>
<AltitudeMeters>36.7</AltitudeMeters>
<DistanceMeters>1566.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:40:00Z</Time>
<Position>
<LatitudeDegrees>48.8666773</LatitudeDegrees>
<LongitudeDegrees>2.3124302</LongitudeDegrees>
</Position>
<AltitudeMeters>36.5</AltitudeMeters>
<DistanceMeters>1620.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:40:20Z</Time>
<Position>
<LatitudeDegrees>48.8670740</LatitudeDegrees>
<LongitudeDegrees>2.3128561</LongitudeDegrees>
</Position>
<AltitudeMeters>36.2</AltitudeMeters>
<DistanceMeters>1674.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:40:40Z</Time>
<Position>
<LatitudeDegrees>48.8674834</LatitudeDegrees>
<LongitudeDegrees>2.3132533</LongitudeDegrees>
</Position>
<AltitudeMeters>36.0</AltitudeMeters>
<DistanceMeters>1728.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:41:00Z</Time>
<Position>
<LatitudeDegrees>48.8679042</LatitudeDegrees>
<LongitudeDegrees>2.3136218</LongitudeDegrees>
</Position>
<AltitudeMeters>35.7</AltitudeMeters>
<DistanceMeters>1782.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:41:20Z</Time>
<Position>
<LatitudeDegrees>48.8683351</LatitudeDegrees>
<LongitudeDegrees>2.3139623</LongitudeDegrees>
</Position>
<AltitudeMeters>35.4</AltitudeMeters>
<DistanceMeters>1836.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:41:40Z</Time>
<Position>
<LatitudeDegrees>48.8687747</LatitudeDegrees>
<LongitudeDegrees>2.3142760</LongitudeDegrees>
</Position>
<AltitudeMeters>35.2</AltitudeMeters>
<DistanceMeters>1890.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:42:00Z</Time>
<Position>
<LatitudeDegrees>48.8692217</LatitudeDegrees>
<LongitudeDegrees>2.3145646</LongitudeDegrees>
</Position>
<AltitudeMeters>34.9</AltitudeMeters>
<DistanceMeters>1944.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:42:20Z</Time>
<Position>
<LatitudeDegrees>48.8696748</LatitudeDegrees>
<LongitudeDegrees>2.3148301</LongitudeDegrees>
</Position>
<AltitudeMeters>34.6</AltitudeMeters>
<DistanceMeters>1998.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:42:40Z</Time>
<Position>
<LatitudeDegrees>48.8701329</LatitudeDegrees>
<LongitudeDegrees>2.3150752</LongitudeDegrees>
</Position>
<AltitudeMeters>34.3</AltitudeMeters>
<DistanceMeters>2052.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:43:00Z</Time>
<Position>
<LatitudeDegrees>48.8705949</LatitudeDegrees>
<LongitudeDegrees>2.3153027</LongitudeDegrees>
</Position>
<AltitudeMeters>34.1</AltitudeMeters>
<DistanceMeters>2106.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:43:20Z</Time>
<Position>
<LatitudeDegrees>48.8710599</LatitudeDegrees>
<LongitudeDegrees>2.3155157</LongitudeDegrees>
</Position>
<AltitudeMeters>33.8</AltitudeMeters>
<DistanceMeters>2160.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:43:40Z</Time>
<Position>
<LatitudeDegrees>48.8715270</LatitudeDegrees>
<LongitudeDegrees>2.3157179</LongitudeDegrees>
</Position>
<AltitudeMeters>33.6</AltitudeMeters>
<DistanceMeters>2214.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:44:00Z</Time>
<Position>
<LatitudeDegrees>48.8719954</LatitudeDegrees>
<LongitudeDegrees>2.3159128</LongitudeDegrees>
</Position>
<AltitudeMeters>33.3</AltitudeMeters>
<DistanceMeters>2268.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:44:20Z</Time>
<Position>
<LatitudeDegrees>48.8724644</LatitudeDegrees>
<LongitudeDegrees>2.3161042</LongitudeDegrees>
</Position>
<AltitudeMeters>33.1</AltitudeMeters>
<DistanceMeters>2322.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:44:40Z</Time>
<Position>
<LatitudeDegrees>48.8729334</LatitudeDegrees>
<LongitudeDegrees>2.3162960</LongitudeDegrees>
</Position>
<AltitudeMeters>32.9</AltitudeMeters>
<DistanceMeters>2376.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:45:00Z</Time>
<Position>
<LatitudeDegrees>48.8734016</LatitudeDegrees>
<LongitudeDegrees>2.3164919</LongitudeDegrees>
</Position>
<AltitudeMeters>32.7</AltitudeMeters>
<DistanceMeters>2430.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:45:20Z</Time>
<Position>
<LatitudeDegrees>48.8738683</LatitudeDegrees>
<LongitudeDegrees>2.3166958</LongitudeDegrees>
</Position>
<AltitudeMeters>32.6</AltitudeMeters>
<DistanceMeters>2484.002</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:45:40Z</Time>
<Position>
<LatitudeDegrees>48.8743329</LatitudeDegrees>
<LongitudeDegrees>2.3169112</LongitudeDegrees>
</Position>
<AltitudeMeters>32.4</AltitudeMeters>
<DistanceMeters>2538.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:46:00Z</Time>
<Position>
<LatitudeDegrees>48.8747943</LatitudeDegrees>
<LongitudeDegrees>2.3171416</LongitudeDegrees>
</Position>
<AltitudeMeters>32.3</AltitudeMeters>
<DistanceMeters>2592.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:46:20Z</Time>
<Position>
<LatitudeDegrees>48.8752516</LatitudeDegrees>
<LongitudeDegrees>2.3173901</LongitudeDegrees>
</Position>
<AltitudeMeters>32.2</AltitudeMeters>
<DistanceMeters>2646.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:46:40Z</Time>
<Position>
<LatitudeDegrees>48.8757037</LatitudeDegrees>
<LongitudeDegrees>2.3176595</LongitudeDegrees>
</Position>
<AltitudeMeters>32.1</AltitudeMeters>
<DistanceMeters>2700.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:47:00Z</Time>
<Position>
<LatitudeDegrees>48.8761495</LatitudeDegrees>
<LongitudeDegrees>2.3179525</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2754.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:47:20Z</Time>
<Position>
<LatitudeDegrees>48.8765876</LatitudeDegrees>
<LongitudeDegrees>2.3182709</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2808.004</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:47:40Z</Time>
<Position>
<LatitudeDegrees>48.8770168</LatitudeDegrees>
<LongitudeDegrees>2.3186164</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2862.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:48:00Z</Time>
<Position>
<LatitudeDegrees>48.8774357</LatitudeDegrees>
<LongitudeDegrees>2.3189900</LongitudeDegrees>
</Position>
<AltitudeMeters>32.0</AltitudeMeters>
<DistanceMeters>2916.006</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:48:20Z</Time>
<Position>
<LatitudeDegrees>48.8778429</LatitudeDegrees>
<LongitudeDegrees>2.3193923</LongitudeDegrees>
</Position>
<AltitudeMeters>32.1</AltitudeMeters>
<DistanceMeters>2970.003</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:48:40Z</Time>
<Position>
<LatitudeDegrees>48.8782372</LatitudeDegrees>
<LongitudeDegrees>2.3198234</LongitudeDegrees>
</Position>
<AltitudeMeters>32.1</AltitudeMeters>
<DistanceMeters>3024.005</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:49:00Z</Time>
<Position>
<LatitudeDegrees>48.8786174</LatitudeDegrees>
<LongitudeDegrees>2.3202829</LongitudeDegrees>
</Position>
<AltitudeMeters>32.2</AltitudeMeters>
<DistanceMeters>3078.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:49:20Z</Time>
<Position>
<LatitudeDegrees>48.8789825</LatitudeDegrees>
<LongitudeDegrees>2.3207698</LongitudeDegrees>
</Position>
<AltitudeMeters>32.3</AltitudeMeters>
<DistanceMeters>3132.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:49:40Z</Time>
<Position>
<LatitudeDegrees>48.8793318</LatitudeDegrees>
<LongitudeDegrees>2.3212829</LongitudeDegrees>
</Position>
<AltitudeMeters>32.5</AltitudeMeters>
<DistanceMeters>3186.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:50:00Z</Time>
<Position>
<LatitudeDegrees>48.8796647</LatitudeDegrees>
<LongitudeDegrees>2.3218205</LongitudeDegrees>
</Position>
<AltitudeMeters>32.6</AltitudeMeters>
<DistanceMeters>3240.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:50:20Z</Time>
<Position>
<LatitudeDegrees>48.8799810</LatitudeDegrees>
<LongitudeDegrees>2.3223808</LongitudeDegrees>
</Position>
<AltitudeMeters>32.8</AltitudeMeters>
<DistanceMeters>3294.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:50:40Z</Time>
<Position>
<LatitudeDegrees>48.8802809</LatitudeDegrees>
<LongitudeDegrees>2.3229617</LongitudeDegrees>
</Position>
<AltitudeMeters>33.0</AltitudeMeters>
<DistanceMeters>3348.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:51:00Z</Time>
<Position>
<LatitudeDegrees>48.8805647</LatitudeDegrees>
<LongitudeDegrees>2.3235609</LongitudeDegrees>
</Position>
<AltitudeMeters>33.2</AltitudeMeters>
<DistanceMeters>3402.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:51:20Z</Time>
<Position>
<LatitudeDegrees>48.8808333</LatitudeDegrees>
<LongitudeDegrees>2.3241761</LongitudeDegrees>
</Position>
<AltitudeMeters>33.4</AltitudeMeters>
<DistanceMeters>3456.009</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:51:40Z</Time>
<Position>
<LatitudeDegrees>48.8810877</LatitudeDegrees>
<LongitudeDegrees>2.3248052</LongitudeDegrees>
</Position>
<AltitudeMeters>33.7</AltitudeMeters>
<DistanceMeters>3510.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:52:00Z</Time>
<Position>
<LatitudeDegrees>48.8813292</LatitudeDegrees>
<LongitudeDegrees>2.3254458</LongitudeDegrees>
</Position>
<AltitudeMeters>33.9</AltitudeMeters>
<DistanceMeters>3564.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:52:20Z</Time>
<Position>
<LatitudeDegrees>48.8815595</LatitudeDegrees>
<LongitudeDegrees>2.3260960</LongitudeDegrees>
</Position>
<AltitudeMeters>34.2</AltitudeMeters>
<DistanceMeters>3618.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:52:40Z</Time>
<Position>
<LatitudeDegrees>48.8817805</LatitudeDegrees>
<LongitudeDegrees>2.3267536</LongitudeDegrees>
</Position>
<AltitudeMeters>34.4</AltitudeMeters>
<DistanceMeters>3672.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:53:00Z</Time>
<Position>
<LatitudeDegrees>48.8819942</LatitudeDegrees>
<LongitudeDegrees>2.3274167</LongitudeDegrees>
</Position>
<AltitudeMeters>34.7</AltitudeMeters>
<DistanceMeters>3726.010</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:53:20Z</Time>
<Position>
<LatitudeDegrees>48.8822028</LatitudeDegrees>
<LongitudeDegrees>2.3280836</LongitudeDegrees>
</Position>
<AltitudeMeters>35.0</AltitudeMeters>
<DistanceMeters>3780.011</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:53:40Z</Time>
<Position>
<LatitudeDegrees>48.8824086</LatitudeDegrees>
<LongitudeDegrees>2.3287525</LongitudeDegrees>
</Position>
<AltitudeMeters>35.2</AltitudeMeters>
<DistanceMeters>3834.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:54:00Z</Time>
<Position>
<LatitudeDegrees>48.8826139</LatitudeDegrees>
<LongitudeDegrees>2.3294217</LongitudeDegrees>
</Position>
<AltitudeMeters>35.5</AltitudeMeters>
<DistanceMeters>3888.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:54:20Z</Time>
<Position>
<LatitudeDegrees>48.8828212</LatitudeDegrees>
<LongitudeDegrees>2.3300896</LongitudeDegrees>
</Position>
<AltitudeMeters>35.8</AltitudeMeters>
<DistanceMeters>3942.013</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:54:40Z</Time>
<Position>
<LatitudeDegrees>48.8830327</LatitudeDegrees>
<LongitudeDegrees>2.3307543</LongitudeDegrees>
</Position>
<AltitudeMeters>36.0</AltitudeMeters>
<DistanceMeters>3996.008</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:55:00Z</Time>
<Position>
<LatitudeDegrees>48.8832508</LatitudeDegrees>
<LongitudeDegrees>2.3314142</LongitudeDegrees>
</Position>
<AltitudeMeters>36.3</AltitudeMeters>
<DistanceMeters>4050.012</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:55:20Z</Time>
<Position>
<LatitudeDegrees>48.8834774</LatitudeDegrees>
<LongitudeDegrees>2.3320674</LongitudeDegrees>
</Position>
<AltitudeMeters>36.5</AltitudeMeters>
<DistanceMeters>4104.014</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:55:40Z</Time>
<Position>
<LatitudeDegrees>48.8837145</LatitudeDegrees>
<LongitudeDegrees>2.3327118</LongitudeDegrees>
</Position>
<AltitudeMeters>36.8</AltitudeMeters>
<DistanceMeters>4158.007</DistanceMeters>
</Trackpoint>
<Trackpoint>
<Time>2026-11-09T16:56:00Z</Time>
<Position>
<LatitudeDegrees>48.8839640</LatitudeDegrees>
<LongitudeDegrees>2.3333455</LongitudeDegrees>
</Position>
<AltitudeMeters>37.0</AltitudeMeters>
<DistanceMeters>4212.014</DistanceMeters>
</Trackpoint>
</Track>
</Lap>
<Creator xsi:type="Device_t">
<Name>kuhy workout_app</Name>
<UnitId>0</UnitId>
<ProductID>0</ProductID>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Creator>
</Activity>
</Activities>
<Author xsi:type="Application_t">
<Name>kuhy workout_app</Name>
<Build>
<Version>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
</Version>
</Build>
<LangID>en</LangID>
<PartNumber>000-00000-00</PartNumber>
</Author>
</TrainingCenterDatabase>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,167 @@
"""Cross-language golden test: the app's TCX is accepted by the real verifier.
The workout app (Dart, ``lib/services/tcx_codec.dart``) writes the TCX files
the PC credits. Each language's own round trip passes happily while the other
side's parser disagrees, so the Dart twin
(``stronglift_replacement/workout_app/test/services/tcx_golden_fixture_test.dart``)
encodes ``fixtures/run_tcx/golden_tracks.json`` and compares the result byte
for byte with the ``.tcx`` files checked in next to it. This test feeds those
SAME files to the real ``RunnerUpVerificationMixin`` -- date glob, parser,
run validation and walk summing -- and asserts the km / minutes the JSON
promises. Everything runs on a temporary drop directory: nothing here reads
or writes ``~/data/cloud/RunnerUp``.
"""
from __future__ import annotations
import json
from pathlib import Path
import shutil
from unittest.mock import MagicMock, patch
import pytest
from screen_locker._runnerup_verification import RunnerUpVerificationMixin
FIXTURES = Path(__file__).parent / "fixtures" / "run_tcx"
SAMPLE = "RunnerUp_2026-08-12-17-42-11_Running.tcx"
# ``_TCX_SPORT_TO_INT`` code for "Running" in screen_locker/_runnerup_tcx.py.
SPORT_RUNNING = 0
def _golden() -> dict[str, dict[str, object]]:
return json.loads((FIXTURES / "golden_tracks.json").read_text(encoding="utf-8"))
class Verifier(RunnerUpVerificationMixin):
"""The real mixin with no phone: only the WebDAV drop directory is read."""
def __init__(self) -> None:
self.adb = MagicMock(return_value=(False, ""))
def _has_adb_device(self) -> bool:
return False
def _run_adb(self, args: list[str]) -> tuple[bool, str]:
return self.adb(args)
@pytest.fixture(name="inbox")
def inbox_fixture(tmp_path: Path) -> Path:
"""A temporary WebDAV inbox standing in for ``~/data/cloud/RunnerUp``."""
inbox = tmp_path / "cloud" / "RunnerUp"
inbox.mkdir(parents=True)
return inbox
def _verify(inbox: Path, today: str) -> tuple[str, str] | None:
"""Run the real file-based verification on ``inbox`` as if it were ``today``."""
with (
patch("screen_locker._runnerup_verification.RUNNERUP_WEBDAV_DIRS", (inbox,)),
patch("screen_locker._runnerup_verification.today_str", return_value=today),
):
return Verifier()._verify_runnerup_via_files()
def _drop(inbox: Path, name: str) -> None:
shutil.copyfile(FIXTURES / name, inbox / name)
class TestGoldenRun:
"""The app's run file passes the PC's run validation unchanged."""
def test_run_is_verified_with_the_promised_km_and_minutes(
self, inbox: Path
) -> None:
"""Date glob, parser and validation accept the app's run file."""
spec = _golden()["running"]
_drop(inbox, str(spec["file"]))
expect = spec["expect"]
assert isinstance(expect, dict)
result = _verify(inbox, "2026-11-09")
assert result == (
expect["status"],
f"Running: {expect['distance_km']} km in {expect['minutes']} min",
)
def test_parsed_fields_match_the_json(self, inbox: Path) -> None:
"""The parser reads sport, duration and distance as the app wrote them."""
spec = _golden()["running"]
_drop(inbox, str(spec["file"]))
data = Verifier()._pull_and_parse_tcx(str(inbox / str(spec["file"])))
assert data is not None
assert data["sport"] == SPORT_RUNNING
assert data["walking"] is False
assert data["duration_seconds"] == spec["total_seconds"]
assert data["distance_m"] == pytest.approx(float(str(spec["distance_m"])))
assert data["activity_id"] == str(spec["started_at"])
def test_the_local_date_in_the_name_is_what_is_globbed(self, inbox: Path) -> None:
"""Another day does not see the file: the stamp is local, the glob is too."""
spec = _golden()["running"]
_drop(inbox, str(spec["file"]))
assert _verify(inbox, "2026-11-10") is None
class TestGoldenWalk:
"""The app's walk file is a walk, and its moving time is what the PC sums."""
def test_walk_is_verified_with_the_promised_moving_minutes(
self, inbox: Path
) -> None:
"""A walk is summed per day: legs, km and moving minutes as promised."""
spec = _golden()["walking"]
_drop(inbox, str(spec["file"]))
expect = spec["expect"]
assert isinstance(expect, dict)
result = _verify(inbox, "2026-11-09")
assert result == (
expect["status"],
(
f"Walking: {expect['legs']} walk(s), {expect['distance_km']} km, "
f"{expect['moving_minutes']} min moving"
),
)
def test_pc_moving_time_equals_the_apps_total_seconds(self, inbox: Path) -> None:
"""Dart's moving-time rule and the PC's ``track_summary`` agree exactly."""
spec = _golden()["walking"]
_drop(inbox, str(spec["file"]))
data = Verifier()._pull_and_parse_tcx(str(inbox / str(spec["file"])))
assert data is not None
assert data["walking"] is True
assert data["moving_seconds"] == pytest.approx(
float(str(spec["total_seconds"]))
)
assert data["activity_id"] == str(spec["started_at"])
def test_walk_is_marked_by_file_name_as_with_runnerup(self, inbox: Path) -> None:
"""Like RunnerUp, the app writes ``Sport="Other"``; the name says walk."""
spec = _golden()["walking"]
name = str(spec["file"])
body = (FIXTURES / name).read_text(encoding="utf-8")
assert 'Sport="Other"' in body
renamed = inbox / "activity.tcx"
renamed.write_text(body)
data = Verifier()._pull_and_parse_tcx(str(renamed))
assert data is not None
assert data["walking"] is False
(inbox / name).write_text(body)
by_name = Verifier()._pull_and_parse_tcx(str(inbox / name))
assert by_name is not None
assert by_name["walking"] is True
class TestRunnerUpSample:
"""The trimmed real RunnerUp export parses to the numbers Dart's decoder sees."""
def test_parser_sums_both_laps(self, inbox: Path) -> None:
"""Same literals as the Dart decoder test: 624 + 626 s, two laps' metres."""
_drop(inbox, SAMPLE)
data = Verifier()._pull_and_parse_tcx(str(inbox / SAMPLE))
assert data is not None
assert data["sport"] == SPORT_RUNNING
assert data["walking"] is False
assert data["duration_seconds"] == 1250
assert data["distance_m"] == pytest.approx(983.6306 + 980.7304, abs=1e-3)
assert data["activity_id"] == "2026-08-12T15:42:11Z"

View File

@ -0,0 +1,216 @@
"""RunnerUp retirement: when it fires, what it refuses, and what it records."""
from __future__ import annotations
from datetime import datetime, timedelta
import logging
from typing import TYPE_CHECKING
import pytest
from screen_locker import _runnerup_retire as rr
from screen_locker._runnerup_retire import Outcome, Paths, run_retire
from screen_locker._runnerup_retire_adb import AdbError, Device
from screen_locker._runnerup_retire_state import RetireState, load_state, save_state
from screen_locker.tests._retire_helpers import (
ANCHOR,
DUE,
RUN,
FakePhone,
put_marker,
world,
)
if TYPE_CHECKING:
from pathlib import Path
def go(paths: Paths, phone: FakePhone, now: datetime = DUE, *, dry_run: bool = False):
"""Go."""
return run_retire(paths, phone, now, dry_run=dry_run)
def test_no_anchor_never_touches_anything(tmp_path: Path) -> None:
"""Test no anchor never touches anything."""
paths = world(tmp_path, anchored=False)
phone = FakePhone()
result = go(paths, phone, DUE + timedelta(days=900))
assert result.outcome is Outcome.NO_ANCHOR
assert result.ok
assert not phone.calls
assert not paths.state_file.exists()
def test_missing_sources_are_a_warning_not_a_quiet_nothing(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test missing sources are a warning not a quiet nothing."""
paths = Paths(tmp_path / "s.json", tmp_path / "nodrop", tmp_path / "nolog.json")
with caplog.at_level(logging.INFO):
result = go(paths, FakePhone())
assert result.outcome is Outcome.SOURCES_MISSING
assert result.ok
assert "nodrop" in result.reason
assert "nolog.json" in result.reason
assert caplog.records[-1].levelno == logging.WARNING
def test_no_anchor_says_how_many_app_runs_it_saw(tmp_path: Path) -> None:
"""Test no anchor says how many app runs it saw."""
paths = world(tmp_path, anchored=False)
assert "(1 app TCX on disk)" in go(paths, FakePhone()).reason
def test_not_due_persists_the_anchor_and_says_when(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test not due persists the anchor and says when."""
paths = world(tmp_path)
with caplog.at_level(logging.INFO):
result = go(paths, FakePhone(), DUE - timedelta(minutes=1))
assert result.outcome is Outcome.NOT_DUE
assert "2026-11-08 10:45" in result.reason
assert load_state(paths.state_file).anchor == ANCHOR
assert [r.levelno for r in caplog.records] == [logging.INFO]
def test_stored_anchor_wins_over_the_log(tmp_path: Path) -> None:
"""Test stored anchor wins over the log."""
paths = world(tmp_path, anchored=False)
save_state(paths.state_file, RetireState(anchor_at=ANCHOR.isoformat()))
assert go(paths, FakePhone(), ANCHOR).outcome is Outcome.NOT_DUE
def test_dry_run_writes_nothing_and_stops_before_the_phone_changes(
tmp_path: Path,
) -> None:
"""Test dry run writes nothing and stops before the phone changes."""
paths = world(tmp_path)
phone = FakePhone()
result = go(paths, phone, dry_run=True)
assert result.outcome is Outcome.DRY_RUN
assert phone.calls == ["installed S"]
assert not paths.state_file.exists()
gone = go(paths, FakePhone(present=False), dry_run=True)
assert gone.outcome is Outcome.ALREADY_GONE
assert not paths.state_file.exists()
@pytest.mark.parametrize("variant", ["missing", "mismatch"])
def test_invalid_marker_blocks_the_uninstall_loudly(
tmp_path: Path, caplog: pytest.LogCaptureFixture, variant: str
) -> None:
"""Test invalid marker blocks the uninstall loudly."""
paths = world(tmp_path, marker=variant == "mismatch")
if variant == "mismatch":
put_marker(paths.watch_dir, [RUN], count=2)
phone = FakePhone()
with caplog.at_level(logging.WARNING):
result = go(paths, phone)
assert result.outcome is Outcome.MARKER_INVALID
assert not result.ok
assert "NOT uninstalling" in result.reason
assert not phone.calls
assert caplog.records[-1].levelno == logging.WARNING
def test_adb_missing_is_a_failure(tmp_path: Path) -> None:
"""Test adb missing is a failure."""
result = go(world(tmp_path), FakePhone(adb=False))
assert result.outcome is Outcome.ADB_MISSING
assert not result.ok
def test_absent_phone_retries_quietly_but_warns(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test absent phone retries quietly but warns."""
phone = FakePhone(device=Device(None, "phone S is not attached"))
with caplog.at_level(logging.WARNING):
result = go(world(tmp_path), phone)
assert result.outcome is Outcome.DEVICE_ABSENT
assert result.ok
assert "not attached" in caplog.text
assert not phone.calls
def test_adb_error_while_asking_is_a_logged_failure(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test adb error while asking is a logged failure."""
phone = FakePhone(ask_error=AdbError("server died"))
with caplog.at_level(logging.ERROR):
result = go(world(tmp_path), phone)
assert result.outcome is Outcome.PHONE_ERROR
assert not result.ok
assert len(caplog.records) == 1 # logged once, where it was caught
def test_already_uninstalled_is_recorded_done(tmp_path: Path) -> None:
"""Test already uninstalled is recorded done."""
paths = world(tmp_path)
result = go(paths, FakePhone(present=False))
assert result.outcome is Outcome.ALREADY_GONE
assert load_state(paths.state_file).done_at
assert go(paths, FakePhone()).outcome is Outcome.ALREADY_DONE
def test_full_run_backs_up_then_uninstalls_then_never_again(tmp_path: Path) -> None:
"""Test full run backs up then uninstalls then never again."""
paths = world(tmp_path)
phone = FakePhone()
result = go(paths, phone)
assert result.outcome is Outcome.UNINSTALLED
assert phone.calls == ["installed S", "backup", "uninstall"]
backup = paths.watch_dir / "runnerup_phone_backup_2026-11-08"
assert backup.is_dir()
assert not list(paths.watch_dir.glob("*.tcx")) # nothing top-level
state = load_state(paths.state_file)
assert state.anchor == ANCHOR
assert state.backup_path == str(backup)
assert state.done_at
again = FakePhone()
assert go(paths, again).outcome is Outcome.ALREADY_DONE
assert not again.calls
@pytest.mark.parametrize("error", [AdbError("short pull"), OSError("disk full")])
def test_failed_backup_blocks_the_uninstall(
tmp_path: Path, caplog: pytest.LogCaptureFixture, error: Exception
) -> None:
"""Test failed backup blocks the uninstall."""
phone = FakePhone(backup_error=error)
with caplog.at_level(logging.ERROR):
result = go(world(tmp_path), phone)
assert result.outcome is Outcome.BACKUP_FAILED
assert not result.ok
assert "uninstall" not in phone.calls
assert str(error) in caplog.text
def test_failed_uninstall_keeps_the_backup_for_the_retry(tmp_path: Path) -> None:
"""Test failed uninstall keeps the backup for the retry."""
paths = world(tmp_path)
first = FakePhone(uninstall_error=AdbError("DELETE_FAILED_DEVICE_POLICY_MANAGER"))
result = go(paths, first)
assert result.outcome is Outcome.UNINSTALL_FAILED
assert not result.ok
assert not load_state(paths.state_file).done_at
retry = FakePhone()
assert go(paths, retry, DUE + timedelta(days=1)).outcome is Outcome.UNINSTALLED
assert retry.calls == ["installed S", "uninstall"] # no second backup
def test_default_paths_are_the_module_constants() -> None:
"""Test default paths are the module constants."""
paths = Paths.default()
assert paths.state_file == rr.STATE_FILE
assert paths.marker == rr.WATCH_DIR / rr.MARKER_NAME
assert paths.processed == rr.WATCH_DIR / "processed"
assert paths.anchor_dirs() == (rr.WATCH_DIR, rr.WATCH_DIR / "processed")
def test_run_retire_defaults_to_the_real_clock(tmp_path: Path) -> None:
"""Test run retire defaults to the real clock."""
paths = world(tmp_path)
assert run_retire(paths, FakePhone(), dry_run=True).outcome is Outcome.DRY_RUN

View File

@ -0,0 +1,225 @@
"""RunnerUp retirement: the adb wrapper and the state file (no real adb)."""
from __future__ import annotations
from pathlib import Path
import subprocess
from types import SimpleNamespace
from typing import Any
import pytest
from screen_locker import _runnerup_retire_adb as ra
SERIAL = ra.PHONE_SERIAL
PKG_LINE = f"package:{ra.PACKAGE}\n"
class FakeAdb:
"""A ``subprocess.run`` stand-in: replies by the adb sub-command."""
def __init__(self, replies: dict[str, Any] | None = None) -> None:
"""Init ."""
self.replies = replies or {}
self.calls: list[list[str]] = []
def __call__(self, cmd: list[str], **_: object) -> SimpleNamespace:
"""Call ."""
self.calls.append(cmd)
for key, reply in self.replies.items():
if key in " ".join(cmd):
if isinstance(reply, BaseException):
raise reply
code, out, err = reply(cmd) if callable(reply) else reply
return SimpleNamespace(returncode=code, stdout=out, stderr=err)
return SimpleNamespace(returncode=0, stdout="", stderr="")
def phone(fake: FakeAdb, adb: str | None = "/usr/bin/adb") -> ra.Phone:
"""Phone."""
return ra.Phone(run=fake, which=lambda _name: adb)
def test_available_follows_which() -> None:
"""Test available follows which."""
assert phone(FakeAdb()).available() is True
assert phone(FakeAdb(), adb=None).available() is False
@pytest.mark.parametrize(
"boom", [FileNotFoundError("adb"), subprocess.TimeoutExpired("adb", 1)]
)
def test_adb_failing_to_run_is_an_adb_error(boom: BaseException) -> None:
"""Test adb failing to run is an adb error."""
with pytest.raises(ra.AdbError, match="did not run"):
phone(FakeAdb({"devices": boom})).find_device()
def test_nonzero_exit_carries_the_output() -> None:
"""Test nonzero exit carries the output."""
fake = FakeAdb({"devices": (1, "", "daemon not running")})
with pytest.raises(ra.AdbError, match="daemon not running"):
phone(fake).find_device()
@pytest.mark.parametrize(
("listing", "serial", "reason"),
[
(f"List of devices attached\n{SERIAL}\tdevice\n", SERIAL, "attached"),
(
f"List of devices attached\nadb-{SERIAL}-x._adb-tls-connect._tcp\tdevice\n",
f"adb-{SERIAL}-x._adb-tls-connect._tcp",
"attached",
),
(f"List of devices attached\n{SERIAL}\tunauthorized\n", None, "unauthorized"),
("List of devices attached\nOTHER\tdevice\n", None, "not attached"),
("List of devices attached\n", None, "not attached"),
],
)
def test_find_device(listing: str, serial: str | None, reason: str) -> None:
"""Test find device."""
device = phone(FakeAdb({"devices": (0, listing, "")})).find_device()
assert device.serial == serial
assert reason in device.reason
def test_wifi_entry_is_asked_for_its_hardware_serial() -> None:
"""Test wifi entry is asked for its hardware serial."""
listing = "List of devices attached\n192.168.1.5:5555\tdevice\n"
fake = FakeAdb({"devices": (0, listing, ""), "getprop": (0, f"{SERIAL}\n", "")})
device = phone(fake).find_device()
assert device.serial == "192.168.1.5:5555"
assert ["adb", "-s", "192.168.1.5:5555", "shell", "getprop", "ro.serialno"] in (
fake.calls
)
def test_wifi_entry_of_another_phone_is_not_ours() -> None:
"""Test wifi entry of another phone is not ours."""
listing = "List of devices attached\n10.0.0.2:5555\tdevice\n"
fake = FakeAdb({"devices": (0, listing, ""), "getprop": (0, "OTHER\n", "")})
assert phone(fake).find_device().serial is None
def test_wifi_entry_that_will_not_answer_is_warned_about(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test wifi entry that will not answer is warned about."""
listing = "List of devices attached\n10.0.0.2:5555\tdevice\n"
fake = FakeAdb({"devices": (0, listing, ""), "getprop": (1, "", "offline")})
with caplog.at_level("WARNING"):
assert phone(fake).find_device().serial is None
assert "Could not read the serial" in caplog.text
def test_presence_probe_sees_hidden_packages_but_the_final_check_does_not() -> None:
"""Test presence probe sees hidden packages but the final check does not."""
fake = FakeAdb({"pm list": (0, PKG_LINE, "")})
phone(fake).installed("dev")
phone(fake).installed("dev", hidden=False)
assert "-u" in fake.calls[0]
assert "-u" not in fake.calls[1]
def test_pull_gets_a_long_timeout_and_other_calls_the_short_one(
tmp_path: Path,
) -> None:
"""Test pull gets a long timeout and other calls the short one."""
timeouts: dict[str, object] = {}
make = _pull_creates(1)
def run(cmd: list[str], **kw: object) -> SimpleNamespace:
"""Run."""
timeouts[cmd[3]] = kw["timeout"]
code, out, err = make(cmd) if cmd[3] == "pull" else (0, "a.tcx\n", "")
return SimpleNamespace(returncode=code, stdout=out, stderr=err)
ra.Phone(run=run, which=lambda _n: "adb").backup("dev", tmp_path / "b")
assert timeouts == {"shell": 50, "pull": 900}
def test_installed_needs_the_exact_package_line() -> None:
"""Test installed needs the exact package line."""
yes = FakeAdb({"pm list": (0, PKG_LINE, "")})
assert phone(yes).installed("dev") is True
assert yes.calls[0][:3] == ["adb", "-s", "dev"]
other = FakeAdb({"pm list": (0, f"package:{ra.PACKAGE}.pro\n", "")})
assert phone(other).installed("dev") is False
def _pull_creates(count: int, root: str = "RunnerUp"):
"""Pull creates."""
def make(cmd: list[str]) -> tuple[int, str, str]:
"""Make."""
folder = Path(cmd[-1]) / root
folder.mkdir(parents=True)
for i in range(count):
(folder / f"r{i}.tcx").write_text("x")
return 0, "", ""
return make
def test_backup_stages_then_renames_and_counts(tmp_path: Path) -> None:
"""Test backup stages then renames and counts."""
fake = FakeAdb({"ls": (0, "a.tcx\nb.tcx\nb.gpx\n", ""), "pull": _pull_creates(2)})
final = tmp_path / "backup_2026"
target, count = phone(fake).backup("dev", final)
assert (target, count) == (final, 2)
assert len(list(final.glob("*.tcx"))) == 2
assert not (tmp_path / "backup_2026.partial").exists()
def test_backup_never_overwrites_an_existing_folder(tmp_path: Path) -> None:
"""Test backup never overwrites an existing folder."""
final = tmp_path / "backup"
final.mkdir()
(tmp_path / "backup.partial").mkdir() # a stale half-pull is cleared
fake = FakeAdb({"ls": (0, "a.tcx\n", ""), "pull": _pull_creates(1)})
target, _ = phone(fake).backup("dev", final)
assert target == tmp_path / "backup-2"
def test_backup_short_pull_is_an_error_and_not_renamed(tmp_path: Path) -> None:
"""Test backup short pull is an error and not renamed."""
fake = FakeAdb({"ls": (0, "a.tcx\nb.tcx\n", ""), "pull": _pull_creates(1)})
with pytest.raises(ra.AdbError, match="pulled 1 of 2"):
phone(fake).backup("dev", tmp_path / "b")
assert not (tmp_path / "b").exists()
def test_backup_pull_that_creates_nothing_is_an_error(tmp_path: Path) -> None:
"""Test backup pull that creates nothing is an error."""
fake = FakeAdb({"ls": (0, "a.tcx\n", "")})
with pytest.raises(ra.AdbError, match="pulled -1 of 1"):
phone(fake).backup("dev", tmp_path / "b")
def test_uninstall_succeeds_only_when_the_package_is_gone() -> None:
"""Test uninstall succeeds only when the package is gone."""
fake = FakeAdb({"uninstall": (0, "Success\n", ""), "pm list": (0, "", "")})
phone(fake).uninstall("dev")
assert ["adb", "-s", "dev", "uninstall", ra.PACKAGE] in fake.calls
def test_uninstall_refusal_keeps_adbs_reason() -> None:
"""Test uninstall refusal keeps adbs reason."""
fail = "Failure [DELETE_FAILED_DEVICE_POLICY_MANAGER]"
fake = FakeAdb({"uninstall": (1, fail, "")})
with pytest.raises(ra.AdbError, match="DELETE_FAILED_DEVICE_POLICY_MANAGER"):
phone(fake).uninstall("dev")
def test_uninstall_without_success_text_is_an_error() -> None:
"""Test uninstall without success text is an error."""
fake = FakeAdb({"uninstall": (0, "weird\n", "")})
with pytest.raises(ra.AdbError, match="did not report Success"):
phone(fake).uninstall("dev")
def test_uninstall_that_leaves_the_package_is_an_error() -> None:
"""Test uninstall that leaves the package is an error."""
fake = FakeAdb({"uninstall": (0, "Success\n", ""), "pm list": (0, PKG_LINE, "")})
with pytest.raises(ra.AdbError, match="still listed"):
phone(fake).uninstall("dev")

View File

@ -0,0 +1,141 @@
"""RunnerUp retirement CLI: ``--status`` is read-only, exit codes follow outcomes."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
import pytest
from screen_locker import runnerup_retire as cli
from screen_locker._runnerup_retire import Outcome, Paths, RetireResult
from screen_locker._runnerup_retire_adb import AdbError, Device
from screen_locker._runnerup_retire_state import RetireState, save_state
from screen_locker.tests._retire_helpers import put_marker
from screen_locker.tests.test_runnerup_retire import ANCHOR, DUE, RUN, FakePhone, world
if TYPE_CHECKING:
from pathlib import Path
def _tree(root: Path) -> set[str]:
"""Tree."""
return {str(p.relative_to(root)) for p in root.rglob("*")}
def test_status_without_anchor(tmp_path: Path) -> None:
"""Test status without anchor."""
paths = world(tmp_path, anchored=False, marker=False)
lines = cli.status_lines(paths, FakePhone(), DUE)
assert lines[0].startswith("anchor: none")
assert lines[1] == "due: never"
assert "INVALID" in lines[2]
assert lines[3] == "done: no"
assert "not queried" in lines[4]
def test_status_is_strictly_read_only_and_marks_a_derived_anchor(
tmp_path: Path,
) -> None:
"""Test status is strictly read only and marks a derived anchor."""
paths = world(tmp_path)
before = _tree(tmp_path)
lines = cli.status_lines(paths, FakePhone(), DUE - timedelta(days=1))
assert _tree(tmp_path) == before
assert not paths.state_file.parent.exists()
assert "derived, not yet stored" in lines[0]
assert "2026-11-08 10:45 (+1.0 days)" in lines[1]
assert lines[2] == "marker: valid (1 runs match)"
def test_status_with_stored_anchor_and_done(tmp_path: Path) -> None:
"""Test status with stored anchor and done."""
paths = world(tmp_path, anchored=False)
save_state(
paths.state_file,
RetireState(anchor_at=ANCHOR.isoformat(), done_at="2026-11-09T00:00:00+00:00"),
)
lines = cli.status_lines(paths, FakePhone(), DUE)
assert "(stored)" in lines[0]
assert lines[3] == "done: 2026-11-09T00:00:00+00:00"
@pytest.mark.parametrize(
("phone", "expected"),
[
(FakePhone(present=True), "installed: yes"),
(FakePhone(present=False), "installed: no"),
(
FakePhone(device=Device(None, "phone S is not attached")),
"installed: unknown (phone S is not attached)",
),
(FakePhone(ask_error=AdbError("boom")), "installed: unknown (boom)"),
],
)
def test_status_query_phone(tmp_path: Path, phone: FakePhone, expected: str) -> None:
"""Test status query phone."""
paths = world(tmp_path)
lines = cli.status_lines(paths, phone, DUE, query_phone=True)
assert lines[4] == expected
def test_main_status_prints_and_exits_zero(
capsys: pytest.CaptureFixture[str],
) -> None:
"""Test main status prints and exits zero."""
assert not cli.main(["--status"]) # the isolated defaults: an empty world
out = capsys.readouterr().out
assert "anchor: none" in out
assert "not queried" in out
def test_main_status_query_phone_uses_the_serial(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""Test main status query phone uses the serial."""
seen: list[str] = []
def fake_phone(serial: str) -> FakePhone:
"""Fake phone."""
seen.append(serial)
return FakePhone()
monkeypatch.setattr(cli, "Phone", fake_phone)
assert not cli.main(["--status", "--query-phone", "--serial", "XYZ"])
assert seen == ["XYZ"]
assert "installed: yes" in capsys.readouterr().out
@pytest.mark.parametrize(
("outcome", "code"),
[(Outcome.NOT_DUE, 0), (Outcome.DEVICE_ABSENT, 0), (Outcome.UNINSTALL_FAILED, 1)],
)
def test_main_exit_code_follows_the_outcome(
monkeypatch: pytest.MonkeyPatch, outcome: Outcome, code: int
) -> None:
"""Test main exit code follows the outcome."""
calls: list[bool] = []
def fake_run(paths: Paths, phone: object, *, dry_run: bool) -> RetireResult:
"""Fake run."""
calls.append(dry_run)
return RetireResult(outcome, "why")
monkeypatch.setattr(cli, "run_retire", fake_run)
assert cli.main(["--dry-run"]) == code
assert calls == [True]
def test_main_with_nothing_to_retire_is_a_clean_noop() -> None:
"""Test main with nothing to retire is a clean noop."""
assert not cli.main([])
def test_status_marker_line_for_a_valid_marker_uses_real_files(
tmp_path: Path,
) -> None:
"""Test status marker line for a valid marker uses real files."""
paths = world(tmp_path, marker=False)
put_marker(paths.watch_dir, [RUN])
now = datetime.now(UTC)
assert cli.status_lines(paths, FakePhone(), now)[2].startswith("marker: valid")

View File

@ -0,0 +1,117 @@
"""RunnerUp retirement: validating the app's import marker against processed/."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
import pytest
from screen_locker import _runnerup_retire_tcx as rt
from screen_locker.tests._retire_helpers import APP, put_marker, put_tcx
if TYPE_CHECKING:
from pathlib import Path
def _processed(tmp_path: Path) -> Path:
"""Processed."""
processed = tmp_path / "processed"
put_tcx(processed, "RunnerUp_2026-08-12-17-42-11_Running.tcx")
put_tcx(processed, "RunnerUp_Pixel_6a_2026-08-12-17-42-11_Running.tcx")
put_tcx(processed, "RunnerUp_2026-08-14-00-58-45_Running.tcx")
put_tcx(processed, "app_2026-11-01.tcx", author=APP)
return processed
_LISTED = [
"RunnerUp_2026-08-12-17-42-11_Running.tcx",
"RunnerUp_2026-08-14-00-58-45_Running.tcx",
]
def test_marker_valid_counts_device_twins_and_ignores_app_files(
tmp_path: Path,
) -> None:
"""Test marker valid counts device twins and ignores app files."""
processed = _processed(tmp_path)
marker = put_marker(tmp_path, _LISTED)
check = rt.check_marker(marker, processed)
assert check.ok
assert "2 runs" in check.reason
def test_marker_may_name_the_device_prefixed_copy(tmp_path: Path) -> None:
"""Test marker may name the device prefixed copy."""
processed = _processed(tmp_path)
names = ["RunnerUp_Pixel_6a_2026-08-12-17-42-11_Running.tcx", _LISTED[1]]
assert rt.check_marker(put_marker(tmp_path, names), processed).ok
def test_marker_missing_is_not_valid(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test marker missing is not valid."""
with caplog.at_level(logging.WARNING):
check = rt.check_marker(tmp_path / "m.json", tmp_path)
assert not check.ok
assert "has not imported yet" in check.reason
assert "marker problem" in caplog.text
def test_marker_unreadable_and_bad_json(tmp_path: Path) -> None:
"""Test marker unreadable and bad json."""
folder_as_marker = tmp_path / "m"
folder_as_marker.mkdir()
assert "unreadable" in rt.check_marker(folder_as_marker, tmp_path).reason
bad = tmp_path / "bad.json"
bad.write_text("{nope")
assert "unreadable" in rt.check_marker(bad, tmp_path).reason
@pytest.mark.parametrize(
("body", "fragment"),
[
("[]", "not a JSON object"),
('{"count": 0, "tcx_names": []}', "no completed_at"),
('{"completed_at": "", "count": 0, "tcx_names": []}', "no completed_at"),
('{"completed_at": "t", "count": 0, "tcx_names": "x"}', "not a list"),
('{"completed_at": "t", "count": 0, "tcx_names": [1]}', "not a list"),
('{"completed_at": "t", "count": 3, "tcx_names": ["a"]}', "count 3"),
('{"completed_at": "t", "count": true, "tcx_names": ["a"]}', "count True"),
('{"completed_at": "t", "count": "1", "tcx_names": ["a"]}', "count '1'"),
('{"completed_at": "t", "count": 1, "tcx_names": ["x/a"]}', "bare file"),
('{"completed_at": "t", "count": 1, "tcx_names": [".a"]}', "bare file"),
],
)
def test_marker_shape_errors(tmp_path: Path, body: str, fragment: str) -> None:
"""Test marker shape errors."""
marker = tmp_path / "m.json"
marker.write_text(body)
check = rt.check_marker(marker, tmp_path)
assert not check.ok
assert fragment in check.reason
def test_marker_listing_one_run_twice_is_invalid(tmp_path: Path) -> None:
"""Test marker listing one run twice is invalid."""
processed = _processed(tmp_path)
twin = "RunnerUp_Pixel_6a_2026-08-12-17-42-11_Running.tcx"
marker = put_marker(tmp_path, [_LISTED[0], twin])
assert "more than once" in rt.check_marker(marker, processed).reason
def test_marker_naming_a_run_not_in_processed_is_invalid(tmp_path: Path) -> None:
"""Test marker naming a run not in processed is invalid."""
processed = _processed(tmp_path)
marker = put_marker(tmp_path, [*_LISTED, "RunnerUp_2099-01-01-00-00-00_X.tcx"])
reason = rt.check_marker(marker, processed).reason
assert "not in processed/" in reason
def test_marker_missing_a_processed_run_asks_for_a_reimport(tmp_path: Path) -> None:
"""Test marker missing a processed run asks for a reimport."""
processed = _processed(tmp_path)
marker = put_marker(tmp_path, _LISTED[:1])
reason = rt.check_marker(marker, processed).reason
assert "re-run the app's import" in reason

View File

@ -0,0 +1,52 @@
"""RunnerUp retirement: the state file round-trip and its loud failures."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from screen_locker._runnerup_retire_state import RetireState, load_state, save_state
if TYPE_CHECKING:
from pathlib import Path
def test_state_roundtrip_and_anchor(tmp_path: Path) -> None:
"""Test state roundtrip and anchor."""
path = tmp_path / "deep" / "s.json"
assert load_state(path) == RetireState()
save_state(path, RetireState(anchor_at="2026-11-01T10:45:00+00:00"))
assert load_state(path).anchor is not None
assert RetireState().anchor is None
@pytest.mark.parametrize(
"body", ["{nope", "[]", json.dumps({"anchor_at": "not a date"})]
)
def test_bad_state_is_loud_and_ignored(
tmp_path: Path, body: str, caplog: pytest.LogCaptureFixture
) -> None:
"""Test bad state is loud and ignored."""
path = tmp_path / "s.json"
path.write_text(body)
with caplog.at_level("WARNING"):
assert load_state(path) == RetireState()
assert "Retire state" in caplog.text
def test_unreadable_state_is_loud(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test unreadable state is loud."""
with caplog.at_level("WARNING"):
assert load_state(tmp_path) == RetireState()
assert "unreadable" in caplog.text
def test_state_ignores_unknown_and_non_string_fields(tmp_path: Path) -> None:
"""Test state ignores unknown and non string fields."""
path = tmp_path / "s.json"
path.write_text(json.dumps({"done_at": 5, "extra": "x", "backup_path": "/b"}))
assert load_state(path) == RetireState(backup_path="/b")

View File

@ -0,0 +1,189 @@
"""RunnerUp retirement: app-run detection, anchor derivation, marker validation."""
from __future__ import annotations
from datetime import UTC, datetime
import logging
from typing import TYPE_CHECKING
import pytest
from screen_locker import _runnerup_retire_tcx as rt
from screen_locker.tests._retire_helpers import (
APP,
END_UNIX,
credit,
put_log,
put_tcx,
)
if TYPE_CHECKING:
from pathlib import Path
_AT = "2026-11-01T10:45:00+00:00"
def test_run_key_drops_device_prefix_only() -> None:
"""Test run key drops device prefix only."""
plain = "RunnerUp_2026-08-22-23-51-04_Running.tcx"
twin = "RunnerUp_Pixel_6a_2026-08-22-23-51-04_Running.tcx"
assert rt.run_key(twin) == plain
assert rt.run_key(plain) == plain
def test_list_tcx_skips_dotfiles_other_types_and_missing_dir(tmp_path: Path) -> None:
"""Test list tcx skips dotfiles other types and missing dir."""
assert rt.list_tcx(tmp_path / "nope") == []
put_tcx(tmp_path, "a.tcx")
put_tcx(tmp_path, ".partial.tcx")
(tmp_path / "a.gpx").write_text("x")
(tmp_path / "dir.tcx").mkdir()
assert [p.name for p in rt.list_tcx(tmp_path)] == ["a.tcx"]
@pytest.mark.parametrize(
("kwargs", "expected"),
[
({"author": APP}, True),
({"creator": APP}, True),
({"author": "RunnerUp"}, False),
({"author": f"{APP} fork"}, False),
],
)
def test_is_app_tcx_reads_author_and_creator(
tmp_path: Path, kwargs: dict[str, str], expected: bool
) -> None:
"""Test is app tcx reads author and creator."""
assert rt.is_app_tcx(put_tcx(tmp_path, "r.tcx", **kwargs)) is expected
def test_is_app_tcx_ignores_the_name_in_free_text(tmp_path: Path) -> None:
"""Test is app tcx ignores the name in free text."""
path = tmp_path / "n.tcx"
path.write_text(f"<Notes>{APP}</Notes>")
assert rt.is_app_tcx(path) is False
def test_is_app_tcx_unreadable_is_a_loud_non_app(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test is app tcx unreadable is a loud non app."""
with caplog.at_level(logging.WARNING):
assert rt.is_app_tcx(tmp_path) is False
assert "Cannot read" in caplog.text
def _app_run(tmp_path: Path, name: str = "app.tcx", where: str = "") -> Path:
"""App run."""
return put_tcx(tmp_path / where if where else tmp_path, name, author=APP)
def test_anchor_is_the_credit_time_of_the_entry_matching_the_run_end(
tmp_path: Path,
) -> None:
"""Test anchor is the credit time of the entry matching the run end."""
_app_run(tmp_path, where="processed")
log = tmp_path / "log.json"
put_log(
log,
{
"2026-11-01": [credit(_AT, END_UNIX)],
"2026-11-02": [credit("2026-11-02T09:00:00+00:00", "1700000000.0")],
},
)
found = rt.find_anchor(log, [tmp_path, tmp_path / "processed"])
assert found == datetime(2026, 11, 1, 10, 45, tzinfo=UTC)
def test_anchor_accepts_a_stringified_end_and_the_earliest_credit(
tmp_path: Path,
) -> None:
"""Test anchor accepts a stringified end and the earliest credit."""
_app_run(tmp_path)
log = tmp_path / "log.json"
put_log(
log,
{
"a": [credit("2026-11-03T00:00:00+00:00", str(END_UNIX))],
"b": [credit("2026-11-02T00:00:00+00:00", END_UNIX + 0.4)],
},
)
found = rt.find_anchor(log, [tmp_path])
assert found == datetime(2026, 11, 2, tzinfo=UTC)
def test_same_day_runnerup_credit_does_not_anchor_the_app_run(tmp_path: Path) -> None:
"""Test same day runnerup credit does not anchor the app run."""
_app_run(tmp_path)
log = tmp_path / "log.json"
put_log(log, {"2026-11-01": [credit(_AT, END_UNIX - 3600)]})
assert rt.find_anchor(log, [tmp_path]) is None
def test_no_app_run_means_no_anchor(tmp_path: Path) -> None:
"""Test no app run means no anchor."""
put_tcx(tmp_path, "r.tcx")
log = tmp_path / "log.json"
put_log(log, {"d": [credit(_AT, END_UNIX)]})
assert rt.find_anchor(log, [tmp_path]) is None
def test_unreadable_or_trackless_app_tcx_cannot_anchor(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test unreadable or trackless app tcx cannot anchor."""
(tmp_path / "bad.tcx").write_text(f"<Author><Name>{APP}</Name></Author>")
log = tmp_path / "log.json"
put_log(log, {"d": [credit(_AT, END_UNIX)]})
with caplog.at_level(logging.WARNING):
assert rt.find_anchor(log, [tmp_path]) is None
assert "cannot anchor" in caplog.text
def test_log_entries_that_cannot_match_are_skipped(
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test log entries that cannot match are skipped."""
_app_run(tmp_path)
log = tmp_path / "log.json"
put_log(
log,
{
"d": [
credit(_AT), # an older entry without completed_at
credit(_AT, True),
credit(_AT, "soon"),
credit(_AT, END_UNIX, kind="manual_workout"),
{
"timestamp": "garbage",
"workout_data": {
"type": "runnerup_verified",
"completed_at": END_UNIX,
},
},
{"workout_data": None},
]
},
)
with caplog.at_level(logging.WARNING):
assert rt.find_anchor(log, [tmp_path]) is None
assert "no usable timestamp" in caplog.text
def test_naive_credit_timestamps_are_read_as_local_time(tmp_path: Path) -> None:
"""Test naive credit timestamps are read as local time."""
_app_run(tmp_path)
log = tmp_path / "log.json"
put_log(log, {"d": [credit("2026-11-01T10:45:00", END_UNIX)]})
found = rt.find_anchor(log, [tmp_path])
assert found is not None
assert found.tzinfo is not None
def test_app_run_ends_lists_every_app_run_in_every_folder(tmp_path: Path) -> None:
"""Test app run ends lists every app run in every folder."""
_app_run(tmp_path, "a.tcx")
_app_run(tmp_path, "b.tcx", where="processed")
put_tcx(tmp_path, "r.tcx")
ends = rt.app_run_ends([tmp_path, tmp_path / "processed"])
assert ends == [END_UNIX, END_UNIX]

View File

@ -20,7 +20,7 @@
# per push under the resource cap, for work finish_auto.sh had just done.
#
# Usage: ci_mirror.sh [venv|precommit|pytest|all] [pytest args...]
# Each step is its own manual hook (ci-venv, ci-precommit, ci-pytest) so no
# Each step is its own manual hook (ci-venv, ci-precommit-*, ci-pytest) so no
# single call outlives the 60 s action cap; `all` (the default) is the old
# one-shot behaviour. pytest runs under xdist (-n auto --dist worksteal):
# serial it was ~85 s, and pytest-cov merges the workers' coverage.
@ -79,9 +79,28 @@ ensure_venv() {
log "clean venv ready"
}
run_precommit_all_files() {
log "pre-commit run --all-files (mirrors the pre-commit workflow)"
pre-commit run --all-files || fail "pre-commit --all-files"
# Hooks that get their own group because they dominate the run time. `rest`
# skips them by id (SKIP matches the id, so `pylint` covers both pylint hooks).
readonly HEAVY_IDS="pylint,flutter-analyze,web-lint,web-typecheck"
# One slice of `pre-commit run --all-files`, small enough for the 60 s action
# cap. The groups partition the default-stage hooks: pylint-source and
# pylint-tests (the aliases of the two `pylint` hooks), flutter-web, and rest
# (everything else). With no group, all of it runs in one go, as CI does.
run_precommit_group() {
local group="${1:-all}"
log "pre-commit run --all-files [$group] (mirrors the pre-commit workflow)"
case "$group" in
all) pre-commit run --all-files ;;
pylint-source | pylint-tests) pre-commit run "$group" --all-files ;;
flutter-web)
pre-commit run flutter-analyze --all-files \
&& pre-commit run web-lint --all-files \
&& pre-commit run web-typecheck --all-files
;;
rest) SKIP="$HEAVY_IDS" pre-commit run --all-files ;;
*) fail "unknown pre-commit group '$group'" ;;
esac || fail "pre-commit --all-files [$group]"
}
run_pytest_clean_venv() {
@ -98,7 +117,7 @@ main() {
esac
case "$mode" in
precommit) run_precommit_all_files; return ;;
precommit) run_precommit_group "${1:-all}"; return ;;
*) ;;
esac
require_file
@ -107,7 +126,7 @@ main() {
venv) ;;
pytest) run_pytest_clean_venv "$@" ;;
*)
run_precommit_all_files
run_precommit_group all
run_pytest_clean_venv "$@"
log "all CI gates passed locally — safe to push"
;;

View File

@ -14,3 +14,30 @@ Implementing design_v2.md improvements.
workout and shows the status-bar notification; notification presses go
through a durable prefs queue, never straight into sqflite (the CRDT
sync layer owns that database's ordering)
## GPS runs (foundation, 2026-11-10)
- The app records runs/walks itself and uploads a TCX the PC credits unchanged.
Contract = the PC parser, pinned by `screen_locker/tests/fixtures/run_tcx/`
(Dart `test/services/tcx_golden_fixture_test.dart` <-> pytest
`screen_locker/tests/test_run_tcx_golden.py`). Regenerate after a deliberate
codec change: `UPDATE_GOLDEN=1 flutter test test/services/tcx_golden_fixture_test.dart`.
- File name `RunnerUp_YYYY-MM-DD-HH-MM-SS_<Running|Walking>.tcx`, stamp in
LOCAL time; `<Id>`/`<Time>` UTC `Z`; source tag `kuhy workout_app` in
`Author/Name` + `Creator/Name`.
- Trackpoints must be <= 30 s apart with cumulative `DistanceMeters`, or the PC
credits no walking time (`lib/services/run_math.dart` mirrors that rule).
- Thresholds that decide credit (3.5 km / 25 min) live on the PC only.
- GPS sits behind `PositionSource` (`position_source*.dart`); imported
RunnerUp runs are stored with `upload_state='never'` (table CHECK).
- RunnerUp history import (`runnerup_importer.dart`): once, on app start, on
the phone only (never the sandbox). PROPFINDs `/RunnerUp/processed/`, stores
every `.tcx` as `runnerup_import`/`never`, then PUTs the dotfile marker
`/RunnerUp/.workout_app_import.json` = `{"completed_at": ISO-UTC, "count": N,
"tcx_names": [...]}`. The importer never PUTs a `.tcx` (a top-level one would
be credited by `runnerup_watch.sh`). A reinstall re-imports and rewrites the
marker with a new `completed_at`: the PC must not use it as a clock.
- `runs`/`run_points` travel in backup.json (app-made runs only; the RunnerUp
history comes back from the PC) and in the user export (version 3, all runs).
Points are one compact JSON string per run.
- dufs login: `dufs_credentials.dart` (`dufs_url`, `dufs_user`, `dufs_password`
in secure storage).

View File

@ -22,6 +22,16 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!-- GPS run/walk tracking. FINE is the GPS fix; COARSE must be declared
alongside it or Android 12+ cannot offer the approximate choice. The
FOREGROUND_SERVICE_LOCATION permission is what lets the same
foreground service keep receiving fixes with the screen off (the
service type below must name `location` on Android 14+). The runtime
grant is requested when a recording starts, never at launch. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<!-- Required by ForegroundTaskOptions(allowWakeLock: true), which takes a
PARTIAL_WAKE_LOCK so the deadline fires with the screen off. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
@ -66,10 +76,16 @@
additionally demands a runtime ACTIVITY_RECOGNITION/BODY_SENSORS
grant on Android 14+, and specialUse needs a Play-review
justification property. Neither buys anything for a sideloaded
personal app, and dataSync's 6h/24h budget dwarfs a workout. -->
personal app, and dataSync's 6h/24h budget dwarfs a workout.
"location" is added for GPS run tracking: a service whose type
list lacks it is not allowed to read the location in the
background on Android 14+. The Dart side must pass
ForegroundServiceTypes.location (with dataSync) when it starts
the service for a recording. -->
<service
android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
android:foregroundServiceType="dataSync"
android:foregroundServiceType="dataSync|location"
android:exported="false"
android:stopWithTask="false" />
<!-- adb-only pairing for the phone->PC workout poke. Exported because

View File

@ -14,6 +14,9 @@ import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/pc_pairing.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/run_upload_credentials.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/runnerup_importer.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/services/sync_service.dart';
@ -80,7 +83,14 @@ void main(List<String> args) async {
Sandbox.defaultRestSecs,
);
SandboxLog.event('rest override loaded', {'secs': Sandbox.restSecs});
Sandbox.runReplayFactor = await StorageService.instance
.getSandboxReplayFactor(Sandbox.defaultReplayFactor);
}
// Run uploads: absorb a login pushed by scripts/provision_run_upload.sh
// (the sandbox never uploads, so it never imports one), then retry any run
// still pending from an earlier launch.
if (!Sandbox.enabled) await RunCredentialStore().importProvisionFile();
unawaited(RunUploader.instance.uploadPending());
// Before the UI exists: a service left over from a crashed or force-stopped
// workout must not sit in the status bar counting down nothing.
await stopStaleBreakService(
@ -120,6 +130,9 @@ void main(List<String> args) async {
if (!Platform.isLinux && !Sandbox.enabled) {
await HttpServerService.instance.start();
}
// One-time RunnerUp history import (no-op in the sandbox and off-phone,
// and once it completed). Off the launch path: it is many downloads.
unawaited(RunnerUpImporter().runGuarded());
runApp(const WorkoutApp());
}
// coverage:ignore-end
@ -167,6 +180,8 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
unawaited(HttpServerService.instance.stop());
case AppLifecycleState.resumed:
unawaited(HttpServerService.instance.start());
// The nearest thing to "connectivity came back" without a plugin.
unawaited(RunUploader.instance.uploadPending());
case AppLifecycleState.inactive:
case AppLifecycleState.hidden:
break;

View File

@ -0,0 +1,51 @@
/// A stored run: the track plus its upload bookkeeping.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
/// Whether a run's TCX has reached the PC's dufs inbox.
enum RunUploadState {
/// Recorded here; not uploaded yet (or the last attempt failed).
pending('pending'),
/// The PC's dufs accepted the file.
uploaded('uploaded'),
/// Must never be uploaded. Every imported RunnerUp run is this: re-sending
/// history would credit old runs as new ones.
never('never');
const RunUploadState(this.storageKey);
/// The value in the `runs.upload_state` column.
final String storageKey;
/// The state stored as [key]; throws on an unknown key.
static RunUploadState fromStorageKey(String key) =>
values.firstWhere((s) => s.storageKey == key);
}
/// One row of the `runs` table with its points (empty when listed).
@immutable
class RunRecord {
/// Creates a record.
const RunRecord({
required this.track,
required this.uploadState,
required this.tcxFilename,
required this.tcxSha256,
});
/// The run; `track.points` is empty in a list result.
final RunTrack track;
/// Upload bookkeeping.
final RunUploadState uploadState;
/// The export file name (see `tcxFilename`).
final String tcxFilename;
/// Hex SHA-256 of the encoded TCX: the dedupe key.
final String tcxSha256;
}

View File

@ -0,0 +1,163 @@
/// A recorded run or walk: the one shape the recorder, the TCX codec, the
/// database and the map all share.
library;
import 'package:flutter/foundation.dart';
/// The sports the app records.
enum RunSport {
/// A run; credited on distance OR duration by the PC.
running('Running', 'Running'),
/// A walk; the PC sums a day's walks and credits their moving time.
///
/// Written as `Sport="Other"` exactly like RunnerUp does (the TCX schema
/// only knows Running, Biking and Other); the `_Walking.tcx` file-name
/// suffix is what marks it a walk.
walking('Walking', 'Other');
const RunSport(this.tcxName, this.tcxSport);
/// The sport's name: the `_<name>.tcx` file-name suffix the PC keys on, and
/// the `runs.sport` column.
final String tcxName;
/// The schema-valid `Sport="..."` attribute the encoder writes.
final String tcxSport;
/// The sport named [tcxName] (also accepts the Strava-style
/// `Sport="Walking"`), or null for anything the app does not record.
static RunSport? fromTcxName(String? tcxName) {
for (final sport in values) {
if (sport.tcxName == tcxName) return sport;
}
return null;
}
}
/// Where a track came from; stored as `runs.source`.
enum RunSource {
/// Recorded by this app.
app('app'),
/// Parsed from a RunnerUp export (history import).
runnerupImport('runnerup_import');
const RunSource(this.storageKey);
/// The value in the `runs.source` column.
final String storageKey;
/// The source stored as [key]; throws on an unknown key.
static RunSource fromStorageKey(String key) =>
values.firstWhere((s) => s.storageKey == key);
}
/// One accepted GPS fix.
@immutable
class RunPoint {
/// Creates a point; [time] is normalised to UTC.
RunPoint({
required DateTime time,
required this.latitude,
required this.longitude,
required this.distanceM,
this.altitudeM,
}) : time = time.toUtc();
/// When the fix was taken (UTC).
final DateTime time;
/// Degrees north.
final double latitude;
/// Degrees east.
final double longitude;
/// Metres above sea level, when the device reports it.
final double? altitudeM;
/// Cumulative credited distance from the start, in metres.
///
/// The PC derives walking speed from the difference between two points'
/// values, so this is the field the recorder must keep honest.
final double distanceM;
@override
bool operator ==(Object other) =>
other is RunPoint &&
other.time == time &&
other.latitude == latitude &&
other.longitude == longitude &&
other.altitudeM == altitudeM &&
other.distanceM == distanceM;
@override
int get hashCode =>
Object.hash(time, latitude, longitude, altitudeM, distanceM);
}
/// A finished (or in-progress) track.
@immutable
class RunTrack {
/// Creates a track; [startedAt] is normalised to UTC.
RunTrack({
required this.id,
required this.sport,
required DateTime startedAt,
required this.points,
required this.totalSeconds,
required this.distanceM,
this.source = RunSource.app,
}) : startedAt = startedAt.toUtc();
/// A track whose [id] is derived from [startedAt] (see [idFor]).
factory RunTrack.started({
required RunSport sport,
required DateTime startedAt,
required List<RunPoint> points,
required int totalSeconds,
required double distanceM,
RunSource source = RunSource.app,
}) => RunTrack(
id: idFor(startedAt),
sport: sport,
startedAt: startedAt,
points: points,
totalSeconds: totalSeconds,
distanceM: distanceM,
source: source,
);
/// The TCX `<Id>`: the start instant, UTC, second precision.
///
/// The PC deduplicates a run's copies (inbox and `processed/`) by this
/// string, so two different runs must never share one.
static String idFor(DateTime startedAt) {
final u = startedAt.toUtc();
String two(int v) => v.toString().padLeft(2, '0');
return '${u.year.toString().padLeft(4, '0')}-${two(u.month)}-${two(u.day)}'
'T${two(u.hour)}:${two(u.minute)}:${two(u.second)}Z';
}
/// The TCX `<Id>` and the database key.
final String id;
/// Running or walking.
final RunSport sport;
/// When recording started (UTC).
final DateTime startedAt;
/// Accepted fixes in time order.
final List<RunPoint> points;
/// Moving time in seconds (not elapsed): what the PC reads as the duration.
final int totalSeconds;
/// Credited distance in metres.
final double distanceM;
/// Recorded here or imported.
final RunSource source;
}

View File

@ -37,6 +37,16 @@ abstract final class Sandbox {
/// the Settings screen, loaded by `main`.
static int restSecs = defaultRestSecs;
/// Replay speed-ups the Settings control offers.
static const List<int> replayFactors = [1, 10, 60];
/// Replay speed-up used when no override has been saved yet.
static const int defaultReplayFactor = 60;
/// How many times faster than real time the sandbox replays a GPS run;
/// persisted by the Settings screen, loaded by `main`.
static int runReplayFactor = defaultReplayFactor;
/// Environment variable that turns the sandbox on where there is no
/// flavor to ask — the Linux desktop build, run under Xvfb to check a
/// change on the PC before it goes anywhere near the phone.

View File

@ -0,0 +1,70 @@
/// The sandbox's GPS: a synthetic loop replayed faster than real time.
///
/// There is no bundled asset (that would need a pubspec entry): the track is a
/// pure function of the start time and sport, so every replay gets its own
/// `RunTrack.id` and two replays never collide in the `runs` table.
library;
import 'dart:math' as math;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/position_source_geolocator.dart';
import 'package:workout_app/services/position_source_scripted.dart';
/// Length of the synthetic loop in metres.
const double kLoopLengthM = 4000;
/// Seconds between replayed fixes (the real request interval).
const int kFixStepSeconds = 2;
// A neutral spot: nobody's home, any tile server has it.
const double _centreLat = 50;
const double _centreLon = 10;
/// Pace of the replay: 10 km/h for a run, a stroll for a walk (a run's speed
/// would trip the walking jump cap and credit nothing).
double replaySpeedMps(RunSport sport) => switch (sport) {
RunSport.running => 10 / 3.6,
RunSport.walking => 5 / 3.6,
};
/// Fixes for one lap of a [kLoopLengthM] circle starting at [start], one every
/// [kFixStepSeconds], 5 m accuracy.
List<GpsFix> sandboxLoopFixes(DateTime start, RunSport sport) {
const radius = kLoopLengthM / (2 * math.pi);
final steps = (kLoopLengthM / replaySpeedMps(sport) / kFixStepSeconds)
.round();
const metresPerDegree = 111194.9;
final lonScale = metresPerDegree * math.cos(_centreLat * math.pi / 180);
return [
for (var i = 0; i <= steps; i++)
GpsFix(
time: start.add(Duration(seconds: i * kFixStepSeconds)),
latitude:
_centreLat +
radius * math.sin(2 * math.pi * i / steps) / metresPerDegree,
longitude:
_centreLon +
radius * (1 - math.cos(2 * math.pi * i / steps)) / lonScale,
accuracyM: 5,
),
];
}
/// The sandbox's [PositionSource]: the loop at [Sandbox.runReplayFactor] times
/// real speed, starting now.
PositionSource sandboxRunSource(RunSport sport, {DateTime? now}) =>
ScriptedPositionSource(
sandboxLoopFixes(now ?? DateTime.now(), sport),
fixDelay: Duration(
microseconds: kFixStepSeconds * 1000000 ~/ Sandbox.runReplayFactor,
),
);
/// The source a recording uses: the replay in the sandbox, the phone's GPS
/// otherwise.
PositionSource positionSourceFor(RunSport sport) =>
Sandbox.enabled ? sandboxRunSource(sport) : GeolocatorPositionSource();

View File

@ -11,8 +11,14 @@ import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/models/manual_workout.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/screens/run_detail_screen.dart';
import 'package:workout_app/services/done_today.dart';
import 'package:workout_app/services/map_tile_cache.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/services/run_history_merge.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/workout_sync_service.dart';
import 'package:workout_app/ui/theme.dart';
@ -23,6 +29,7 @@ part 'history_screen_charts.dart';
part 'history_screen_data.dart';
part 'history_screen_painter.dart';
part 'history_screen_planned.dart';
part 'history_screen_runs.dart';
part 'history_screen_tiles.dart';
const _kTotal = 'Total (all workouts)';
@ -44,6 +51,7 @@ class HistoryScreen extends StatefulWidget {
this.httpClient,
this.firebaseFactory,
this.clock,
this.tileProviderOpener = openOsmTileProvider,
});
/// Overrides the HTTP client used to read synced workouts (tests only).
@ -56,6 +64,9 @@ class HistoryScreen extends StatefulWidget {
/// defaults to [DateTime.now], injected by tests.
final DateTime Function()? clock;
/// Where a run's map tiles come from; a fake in tests.
final TileProviderOpener tileProviderOpener;
@override
State<HistoryScreen> createState() => _HistoryScreenState();
}
@ -64,6 +75,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
List<Map<String, dynamic>> _rows = [];
List<Map<String, dynamic>> _syncedRows = [];
List<Map<String, dynamic>> _plannedRows = [];
List<RunRecord> _runs = [];
bool _loading = true;
String _selected = _kTotal;
List<String> _exerciseNames = [];
@ -103,13 +115,16 @@ class _HistoryScreenState extends State<HistoryScreen> {
// coverage:ignore-end
}
final today = dayKey((widget.clock ?? DateTime.now)());
final synced = _syncedOnly(remote, today);
final runs = await StorageService.instance.listRuns();
// The phone's own copy of a run (it has the map) replaces the PC's entry.
final synced = withoutLocalRuns(_syncedOnly(remote, today), runs);
final planned = _plannedOnly(remote, today);
if (mounted) {
setState(() {
_rows = rows;
_syncedRows = synced;
_plannedRows = planned;
_runs = runs;
_exerciseNames = names;
_selectedState = state;
_loading = false;
@ -137,8 +152,6 @@ class _HistoryScreenState extends State<HistoryScreen> {
}
}
// ── Data helpers ──────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
final allNames = [_kTotal, ..._exerciseNames];
@ -155,7 +168,10 @@ class _HistoryScreenState extends State<HistoryScreen> {
? const Center(child: CircularProgressIndicator())
// Synced and planned entries count too: a phone with no local
// sessions must still list (and let the user delete) its plans.
: _rows.isEmpty && _syncedRows.isEmpty && _plannedRows.isEmpty
: _rows.isEmpty &&
_syncedRows.isEmpty &&
_plannedRows.isEmpty &&
_runs.isEmpty
? Center(
child: Text(
'No workouts yet.',
@ -180,28 +196,24 @@ class _HistoryScreenState extends State<HistoryScreen> {
);
}
void _shiftMonth(int delta) => setState(() {
_calendarMonth = DateTime(
_calendarMonth.year,
_calendarMonth.month + delta,
);
});
List<Widget> _buildTotalView() => [
..._plannedSection(),
if (_runs.isNotEmpty) ...[
_RunsStrip(runs: _runs, onOpen: _openRun),
const SizedBox(height: 16),
],
const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'),
const SizedBox(height: 6),
_WeightChart(points: _rollingAvg2(_totalVolumePoints(_rows))),
const SizedBox(height: 16),
WorkoutCalendar(
workoutDates: _allWorkoutDates(_rows, _syncedRows),
month: _calendarMonth,
onPrevMonth: () => setState(() {
_calendarMonth = DateTime(
_calendarMonth.year,
_calendarMonth.month - 1,
);
}),
onNextMonth: () => setState(() {
_calendarMonth = DateTime(
_calendarMonth.year,
_calendarMonth.month + 1,
);
}),
),
_calendar(_allWorkoutDates(_rows, _syncedRows, _runs)),
const SizedBox(height: 16),
const _SectionLabel('ALL SESSIONS'),
const SizedBox(height: 8),
@ -223,22 +235,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
const SizedBox(height: 6),
_WeightChart(points: _exerciseWeightPoints(_rows, name)),
const SizedBox(height: 16),
WorkoutCalendar(
workoutDates: _exerciseDates(_rows, name),
month: _calendarMonth,
onPrevMonth: () => setState(() {
_calendarMonth = DateTime(
_calendarMonth.year,
_calendarMonth.month - 1,
);
}),
onNextMonth: () => setState(() {
_calendarMonth = DateTime(
_calendarMonth.year,
_calendarMonth.month + 1,
);
}),
),
_calendar(_exerciseDates(_rows, name)),
const SizedBox(height: 16),
_SectionLabel(name.toUpperCase()),
const SizedBox(height: 8),

View File

@ -117,12 +117,17 @@ List<(DateTime, double)> _rollingAvg2(List<(DateTime, double)> pts) {
///
/// Synced dates are included so a day you only worked out on the PC (a
/// RunnerUp run) still marks the calendar here.
///
/// Runs recorded here count by their local start day, which is also the day
/// of the PC entry they replaced.
Set<String> _allWorkoutDates(
List<Map<String, dynamic>> rows,
List<Map<String, dynamic>> syncedRows,
List<RunRecord> runs,
) => {
...rows.map((r) => r['date'] as String),
...syncedRows.map((r) => '${r['date']}'),
...runs.map((r) => dayKey(r.track.startedAt.toLocal())),
};
/// Synced kinds this phone has no local record of, so showing them can't

View File

@ -0,0 +1,126 @@
// The runs overview on HistoryScreen: one fixed-height strip of compact
// tiles (newest first, swipe sideways for older ones) so it costs no
// vertical space (R7). No words: icons and numbers only.
//
// See history_screen_charts.dart for why these are `part` files.
part of 'history_screen.dart';
/// Pieces of the State kept here so history_screen.dart stays under the line
/// cap: the month-paged calendar and opening a run's detail.
extension _RunsAndCalendar on _HistoryScreenState {
Widget _calendar(Set<String> dates) => WorkoutCalendar(
workoutDates: dates,
month: _calendarMonth,
onPrevMonth: () => _shiftMonth(-1),
onNextMonth: () => _shiftMonth(1),
);
Future<void> _openRun(RunRecord record) async {
final full = await StorageService.instance.getRun(record.track.id);
if (full == null || !mounted) return;
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => RunDetailScreen(
track: full.track,
tileProviderOpener: widget.tileProviderOpener,
),
),
);
}
}
class _RunsStrip extends StatelessWidget {
const _RunsStrip({required this.runs, required this.onOpen});
final List<RunRecord> runs;
final void Function(RunRecord) onOpen;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return SizedBox(
key: const Key('runs_strip'),
height: 92,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: runs.length,
separatorBuilder: (_, _) => const SizedBox(width: AppSpacing.sm),
itemBuilder: (_, i) => _RunTile(
run: runs[i].track,
scheme: scheme,
onTap: () => onOpen(runs[i]),
),
),
);
}
}
class _RunTile extends StatelessWidget {
const _RunTile({
required this.run,
required this.scheme,
required this.onTap,
});
final RunTrack run;
final ColorScheme scheme;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final isRun = run.sport == RunSport.running;
final value = TextStyle(
color: scheme.onSurface,
fontWeight: FontWeight.bold,
fontSize: AppTextSize.label,
);
return Semantics(
button: true,
label: isRun ? 'Run' : 'Walk',
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(AppRadius.sm),
child: Container(
width: 104,
padding: const EdgeInsets.all(AppSpacing.sm),
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(AppRadius.sm),
border: Border.all(color: scheme.outline),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(
isRun ? Icons.directions_run : Icons.directions_walk,
size: 18,
color: scheme.primary,
),
const Spacer(),
Text(
formatRunDay(run.startedAt),
style: TextStyle(
color: scheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
],
),
Text(formatDistanceKm(run.distanceM), style: value),
Text(
formatDuration(run.totalSeconds),
style: TextStyle(
color: scheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
],
),
),
),
);
}
}

View File

@ -8,6 +8,7 @@ import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/screens/history_screen.dart';
import 'package:workout_app/screens/manual_workout_screen.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/screens/settings_screen.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/done_today.dart';
@ -153,6 +154,15 @@ class _HomeScreenState extends State<HomeScreen> {
style: TextStyle(color: colorScheme.onSurface),
),
actions: [
IconButton(
key: const Key('home_run'),
icon: Icon(
Icons.directions_run,
color: colorScheme.onSurface,
semanticLabel: 'run',
),
onPressed: _openRun,
),
IconButton(
icon: Icon(Icons.edit_note, color: colorScheme.onSurface),
tooltip: 'Log manual workout',

View File

@ -52,7 +52,7 @@ class _WorkoutCard extends StatelessWidget {
),
const SizedBox(height: 6),
Text(
'Next: Workout $type — tomorrow',
'Next: Workout $type',
style: TextStyle(
color: colorScheme.onSurface,
fontSize: AppTextSize.body,
@ -103,7 +103,9 @@ class _WorkoutCard extends StatelessWidget {
),
),
)
else if (!doneToday)
else
// Never hidden by "done today": the PC pays for every further
// session, so an extra workout must stay one tap away.
SizedBox(
width: double.infinity,
child: ElevatedButton(

View File

@ -14,6 +14,16 @@ extension _HomeScreenNavigation on _HomeScreenState {
unawaited(_load());
}
/// Pushes the GPS run screen, then reloads (a finished run can change
/// today's credit once the PC has it).
Future<void> _openRun() async {
SandboxLog.event('open run screen');
await Navigator.of(
context,
).push(MaterialPageRoute<void>(builder: (_) => const RunScreen()));
unawaited(_load());
}
/// Pushes the workout, resuming the saved session when [resume].
///
/// [auto] is the launch-time open: it replaces home without a transition,

View File

@ -0,0 +1,160 @@
/// One run on one screen: the whole route on a full-bleed map with its
/// numbers (distance, moving time, average pace, date) in a panel over the
/// bottom edge. Nothing scrolls (R7); no words (textgate), icons name each
/// value.
library;
import 'package:flutter/material.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/map_tile_cache.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map.dart';
/// Height reserved under the route for the stats panel, so the fitted route
/// is not hidden behind it.
const _panelClearance = 190.0;
/// Detail of the finished [track] (it must carry its points).
class RunDetailScreen extends StatelessWidget {
/// Creates the screen; [tileProviderOpener] is swapped by tests.
const RunDetailScreen({
required this.track,
super.key,
this.tileProviderOpener = openOsmTileProvider,
});
/// The run, with points (see `StorageServiceRuns.getRun`).
final RunTrack track;
/// Where the map's tiles come from.
final TileProviderOpener tileProviderOpener;
@override
Widget build(BuildContext context) {
final top = MediaQuery.paddingOf(context).top;
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
RunMap.route(
points: track.points,
fitPadding: EdgeInsets.fromLTRB(
AppSpacing.xl,
top + 64,
AppSpacing.xl,
_panelClearance,
),
tileProviderOpener: tileProviderOpener,
),
Positioned(
left: AppSpacing.sm,
top: top + AppSpacing.sm,
child: IconButton.filledTonal(
onPressed: () => Navigator.maybePop(context),
icon: const Icon(Icons.arrow_back, semanticLabel: 'Back'),
),
),
Positioned(
left: AppSpacing.md,
right: AppSpacing.md,
bottom: MediaQuery.paddingOf(context).bottom + AppSpacing.md,
child: _StatsPanel(track: track),
),
],
),
);
}
}
class _StatsPanel extends StatelessWidget {
const _StatsPanel({required this.track});
final RunTrack track;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final isRun = track.sport == RunSport.running;
return Container(
key: const Key('run_stats_panel'),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(color: scheme.outline),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Icon(
isRun ? Icons.directions_run : Icons.directions_walk,
color: scheme.primary,
semanticLabel: isRun ? 'Run' : 'Walk',
),
const SizedBox(width: AppSpacing.sm),
Text(
formatFullDate(track.startedAt),
style: TextStyle(color: scheme.onSurfaceVariant),
),
const Spacer(),
if (track.source == RunSource.runnerupImport)
Icon(
Icons.history,
color: scheme.onSurfaceVariant,
semanticLabel: 'Imported',
),
],
),
const SizedBox(height: AppSpacing.md),
Row(
children: [
_Stat(Icons.straighten, formatDistanceKm(track.distanceM)),
_Stat(Icons.timer_outlined, formatDuration(track.totalSeconds)),
_Stat(
Icons.speed,
formatPace(
seconds: track.totalSeconds,
distanceM: track.distanceM,
),
),
],
),
],
),
);
}
}
class _Stat extends StatelessWidget {
const _Stat(this.icon, this.value);
final IconData icon;
final String value;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Expanded(
child: Column(
children: [
Icon(icon, size: 20, color: scheme.onSurfaceVariant),
const SizedBox(height: AppSpacing.xs),
FittedBox(
fit: BoxFit.scaleDown,
child: Text(
value,
style: TextStyle(
color: scheme.onSurface,
fontSize: AppTextSize.title,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}
}

View File

@ -0,0 +1,153 @@
/// The live run/walk screen: sport, start/pause/finish, and big numbers.
///
/// One screen, no scrolling (R7), and no words (textgate): icons, colours and
/// digits only. Icons that report a problem are tappable where the fix is in
/// system settings.
library;
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_format.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import 'package:workout_app/widgets/run_upload_badge.dart';
part 'run_screen_parts.dart';
/// The controller the app uses: real GPS (or the sandbox replay), the real
/// foreground service, the real database and the app-wide upload queue.
RunController buildRunController() => RunController(
sourceFor: positionSourceFor,
service: FlutterForegroundRunClient(),
cues: FeedbackCues(AudioPlayer()),
save: (track) => saveRecordedRun(
track,
storage: StorageService.instance,
enqueue: RunUploader.instance.uploadPending,
),
);
/// Records one run or walk.
class RunScreen extends StatefulWidget {
/// Creates the screen; every argument is a test or map seam.
const RunScreen({
super.key,
this.controllerFactory = buildRunController,
this.uploader,
this.mapBuilder,
this.openSettings = openAppSettings,
});
/// Builds the controller for a recording (called again for "new run").
final RunController Function() controllerFactory;
/// The upload queue shown in the badge; defaults to the app-wide one.
final RunUploader? uploader;
/// Builds the live map from the run's accepted points; defaults to the
/// [RunMapSlot] placeholder. This is where the map widget goes.
final Widget Function(BuildContext, ValueListenable<List<RunPoint>>)?
mapBuilder;
/// Opens the system settings page for this app.
final Future<bool> Function() openSettings;
@override
State<RunScreen> createState() => _RunScreenState();
}
class _RunScreenState extends State<RunScreen> {
late RunController _controller = widget.controllerFactory();
late final RunUploader _uploader = widget.uploader ?? RunUploader.instance;
bool _starting = false;
@override
void initState() {
super.initState();
SandboxLog.event('open run');
// So the badge shows the real queue, not the pre-first-pass default.
unawaited(_uploader.uploadPending());
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _start() async {
setState(() => _starting = true);
try {
await _controller.start();
} finally {
if (mounted) setState(() => _starting = false);
}
}
void _again() {
final old = _controller;
setState(() => _controller = widget.controllerFactory());
old.dispose();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final c = _controller;
final r = c.recorder;
return PopScope(
// A recording lives in this screen's controller: leaving would lose it.
canPop: !c.active,
child: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Column(
children: [
_StatusRow(
controller: c,
uploader: _uploader,
openSettings: widget.openSettings,
),
const SizedBox(height: AppSpacing.sm),
Expanded(
flex: 4,
child:
widget.mapBuilder?.call(context, r.livePoints) ??
RunMapSlot(points: r.livePoints),
),
const SizedBox(height: AppSpacing.md),
Expanded(flex: 3, child: _Numbers(recorder: r)),
const SizedBox(height: AppSpacing.md),
_Controls(
controller: c,
starting: _starting,
onStart: () => unawaited(_start()),
onAgain: _again,
onClose: () => Navigator.of(context).maybePop(),
),
],
),
),
),
),
);
},
);
}

View File

@ -0,0 +1,250 @@
// The run screen's three bands: status icons, the big numbers, the buttons.
part of 'run_screen.dart';
IconData _sportIcon(RunSport sport) => switch (sport) {
RunSport.running => Icons.directions_run,
RunSport.walking => Icons.directions_walk,
};
/// Problems with the recording, as an icon (null when there is none).
({IconData icon, bool danger})? _issueFace(RunIssue issue) => switch (issue) {
RunIssue.none => null,
RunIssue.denied ||
RunIssue.deniedForever ||
RunIssue.serviceOff => (icon: Icons.location_disabled, danger: true),
RunIssue.mockedLocation => (icon: Icons.wrong_location, danger: true),
RunIssue.streamError => (icon: Icons.gps_off, danger: false),
RunIssue.tooShort => (icon: Icons.error_outline, danger: true),
};
class _StatusRow extends StatelessWidget {
const _StatusRow({
required this.controller,
required this.uploader,
required this.openSettings,
});
final RunController controller;
final RunUploader uploader;
final Future<bool> Function() openSettings;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final colors = Theme.of(context).extension<AppStatusColors>()!;
final recorder = controller.recorder;
final issue = _issueFace(recorder.issue);
final fixable =
recorder.issue == RunIssue.deniedForever ||
recorder.issue == RunIssue.serviceOff;
final serviceIcon = switch (controller.serviceState) {
RunServiceState.runningHidden => (Icons.notifications_off, false),
RunServiceState.failed => (Icons.warning_amber, true),
_ => null,
};
final saved = controller.saved;
return SizedBox(
height: 48,
child: Row(
children: [
RunUploadBadge(uploader: uploader),
const Spacer(),
if (controller.saving)
const SizedBox.square(
dimension: 24,
child: CircularProgressIndicator(
key: Key('run_saving'),
strokeWidth: 2,
),
),
if (saved != null)
Icon(
saved.stored ? Icons.check_circle : Icons.error,
key: Key(saved.stored ? 'run_saved_ok' : 'run_saved_failed'),
color: saved.stored ? colors.success : scheme.error,
semanticLabel: saved.stored ? 'saved' : 'not saved',
),
if (serviceIcon != null)
Padding(
padding: const EdgeInsets.only(left: AppSpacing.sm),
child: Icon(
serviceIcon.$1,
key: const Key('run_service_issue'),
color: serviceIcon.$2 ? scheme.error : colors.warning,
semanticLabel: controller.serviceState.name,
),
),
if (issue != null)
IconButton(
key: Key('run_issue_${recorder.issue.name}'),
onPressed: fixable ? () => unawaited(openSettings()) : null,
icon: Icon(
issue.icon,
color: issue.danger ? scheme.error : colors.warning,
semanticLabel: recorder.issue.name,
),
),
Padding(
padding: const EdgeInsets.only(left: AppSpacing.sm),
child: Icon(
_sportIcon(recorder.sport),
color: scheme.onSurfaceVariant,
semanticLabel: recorder.sport.name,
),
),
],
),
);
}
}
class _Numbers extends StatelessWidget {
const _Numbers({required this.recorder});
final RunRecorder recorder;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
const figures = [FontFeature.tabularFigures()];
Widget big(Key key, String text, double size, Color color) => FittedBox(
fit: BoxFit.scaleDown,
child: Text(
text,
key: key,
style: TextStyle(
fontSize: size,
fontWeight: FontWeight.w600,
color: color,
fontFeatures: figures,
),
),
);
Widget small(IconData icon, Key key, String text) => Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: scheme.onSurfaceVariant),
const SizedBox(width: AppSpacing.sm),
Flexible(child: big(key, text, 48, scheme.onSurface)),
],
),
);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: big(
const Key('run_time'),
formatDuration(recorder.seconds),
96,
scheme.onSurface,
),
),
const SizedBox(height: AppSpacing.sm),
Row(
children: [
small(
Icons.straighten,
const Key('run_distance'),
formatDistanceKm(recorder.distanceM),
),
small(
Icons.speed,
const Key('run_pace'),
formatPace(
seconds: recorder.seconds,
distanceM: recorder.distanceM,
),
),
],
),
],
);
}
}
class _Controls extends StatelessWidget {
const _Controls({
required this.controller,
required this.starting,
required this.onStart,
required this.onAgain,
required this.onClose,
});
final RunController controller;
final bool starting;
final VoidCallback onStart;
final VoidCallback onAgain;
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
final recorder = controller.recorder;
final scheme = Theme.of(context).colorScheme;
Widget button(
String id,
IconData icon,
VoidCallback? onTap, {
Color? tint,
}) {
return IconButton.filled(
key: Key('run_$id'),
onPressed: onTap,
iconSize: 40,
style: IconButton.styleFrom(
fixedSize: const Size.square(88),
backgroundColor: tint ?? scheme.primary,
foregroundColor: scheme.onPrimary,
),
icon: Icon(icon, semanticLabel: id),
);
}
final buttons = switch (recorder.phase) {
RunPhase.idle => [
SegmentedButton<RunSport>(
key: const Key('run_sport'),
showSelectedIcon: false,
segments: [
for (final sport in RunSport.values)
ButtonSegment(
value: sport,
icon: Icon(_sportIcon(sport), semanticLabel: sport.name),
),
],
selected: {recorder.sport},
onSelectionChanged: (s) => recorder.selectSport(s.single),
),
button('start', Icons.play_arrow, starting ? null : onStart),
],
RunPhase.recording => [
button('pause', Icons.pause, controller.pause),
button(
'finish',
Icons.stop,
() => unawaited(controller.finish()),
tint: scheme.error,
),
],
RunPhase.paused => [
button('resume', Icons.play_arrow, controller.resume),
button(
'finish',
Icons.stop,
() => unawaited(controller.finish()),
tint: scheme.error,
),
],
RunPhase.finished => [
button('again', Icons.refresh, controller.saving ? null : onAgain),
button('close', Icons.check, controller.saving ? null : onClose),
],
};
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: buttons,
);
}
}

View File

@ -2,9 +2,8 @@
/// settings sheet, plus links to the sync surfaces.
///
/// "Sync settings" is the shared `sync_settings_ui` package (Firebase sync;
/// no Backup section -- see the class doc on [SettingsScreen] for why).
/// "Advanced sync (GitHub)" stays app-local ([GitHubMirrorScreen]) because
/// the shared package has no GitHub surface at all.
/// no Backup section -- see [SettingsScreen]). "Advanced sync (GitHub)" stays
/// app-local ([GitHubMirrorScreen]): the shared package has no GitHub surface.
library;
import 'dart:async';
@ -26,6 +25,7 @@ import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/data_transfer_buttons.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import 'package:workout_app/widgets/runnerup_import_badge.dart';
part 'settings_screen_actions.dart';
part 'settings_screen_deload.dart';

View File

@ -34,6 +34,7 @@ class _SandboxSectionState extends State<_SandboxSection> {
Future<void> _wipe() async {
await StorageService.instance.wipeAll();
Sandbox.restSecs = Sandbox.defaultRestSecs;
Sandbox.runReplayFactor = Sandbox.defaultReplayFactor;
_rest.text = '${Sandbox.restSecs}';
_report('Wiped — the sandbox is back to a fresh install.');
}
@ -60,6 +61,12 @@ class _SandboxSectionState extends State<_SandboxSection> {
_report('Every rest now lasts $secs s.');
}
Future<void> _saveReplay(int factor) async {
await StorageService.instance.setSandboxReplayFactor(factor);
setState(() => Sandbox.runReplayFactor = factor);
_report('GPS runs replay at $factor×.');
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
@ -118,6 +125,27 @@ class _SandboxSectionState extends State<_SandboxSection> {
),
],
),
const SizedBox(height: 12),
Row(
children: [
const Padding(
padding: EdgeInsets.only(right: 12),
child: Icon(Icons.directions_run, semanticLabel: 'GPS replay'),
),
Expanded(
child: SegmentedButton<int>(
key: const Key('sandbox-replay-factor'),
showSelectedIcon: false,
segments: [
for (final f in Sandbox.replayFactors)
ButtonSegment(value: f, label: Text('$f×')),
],
selected: {Sandbox.runReplayFactor},
onSelectionChanged: (s) => unawaited(_saveReplay(s.single)),
),
),
],
),
if (_status != null) ...[
const SizedBox(height: 8),
Text(

View File

@ -179,6 +179,7 @@ class _SettingsAppBar extends StatelessWidget implements PreferredSizeWidget {
title: Text('Settings', style: TextStyle(color: colorScheme.onSurface)),
iconTheme: IconThemeData(color: colorScheme.onSurface),
actions: [
const RunnerUpImportBadge(),
TextButton(
onPressed: loading ? null : onReset,
child: Text(

View File

@ -0,0 +1,74 @@
/// Login for the PC's dufs WebDAV server (`/RunnerUp`, scoped read-write).
///
/// One shared definition so the run uploader and the RunnerUp history
/// importer read the very same secure-storage slots; provisioned once from a
/// `dufs_login.json` that carries `url`, `user` and `password`.
library;
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Secure-storage key of [DufsCredentials.url].
const String kDufsUrlKey = 'dufs_url';
/// Secure-storage key of [DufsCredentials.user].
const String kDufsUserKey = 'dufs_user';
/// Secure-storage key of [DufsCredentials.password].
const String kDufsPasswordKey = 'dufs_password';
/// Where the PC's dufs is and who to log in as.
@immutable
class DufsCredentials {
/// Creates a login; trailing slashes of [url] are dropped so
/// `'$url/RunnerUp/...'` is always well formed.
DufsCredentials({
required String url,
required this.user,
required this.password,
}) : url = url.replaceFirst(RegExp(r'/+$'), '');
/// Parses a `dufs_login.json` document; null when a field is missing.
static DufsCredentials? fromJson(Map<String, dynamic> json) {
final url = json['url'];
final user = json['user'];
final password = json['password'];
if (url is! String || user is! String || password is! String) return null;
if (url.isEmpty || user.isEmpty || password.isEmpty) return null;
return DufsCredentials(url: url, user: user, password: password);
}
/// The origin, e.g. `https://kuhy-cloud.duckdns.org` (no trailing slash).
final String url;
/// The Basic-auth user.
final String user;
/// The Basic-auth password.
final String password;
/// The `Authorization` header value.
String get authorization =>
'Basic ${base64Encode(utf8.encode('$user:$password'))}';
/// The stored login, or null when any of the three slots is empty.
static Future<DufsCredentials?> load({
FlutterSecureStorage storage = const FlutterSecureStorage(),
}) async {
final url = await storage.read(key: kDufsUrlKey);
final user = await storage.read(key: kDufsUserKey);
final password = await storage.read(key: kDufsPasswordKey);
return fromJson({'url': url, 'user': user, 'password': password});
}
/// Stores this login.
Future<void> save({
FlutterSecureStorage storage = const FlutterSecureStorage(),
}) async {
await storage.write(key: kDufsUrlKey, value: url);
await storage.write(key: kDufsUserKey, value: user);
await storage.write(key: kDufsPasswordKey, value: password);
}
}

View File

@ -6,6 +6,7 @@ import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:vibration/vibration.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/storage_service.dart';
@ -54,4 +55,25 @@ class FeedbackCues {
debugPrint('WorkoutApp: finish chime failed to play ($error).');
});
}
/// A whole kilometre of a run was just credited: a double buzz and, if
/// allowed, the chime.
///
/// The vibration plugin rather than [HapticFeedback]: a run happens with the
/// screen off in a pocket, where view haptics may not fire.
Future<void> kilometreReached(int km) async {
SandboxLog.event('cue kilometre', {'km': km, 'sound': soundOn});
if (await Vibration.hasVibrator()) {
// Android/iOS-only: hasVibrator() is false on the Linux test host.
// coverage:ignore-start
unawaited(Vibration.vibrate(pattern: [0, 150, 100, 150]));
// coverage:ignore-end
}
if (!soundOn) return;
await _player.play(AssetSource('sounds/workout_done.wav')).catchError((
Object error,
) {
debugPrint('WorkoutApp: kilometre chime failed to play ($error).');
});
}
}

View File

@ -32,8 +32,8 @@ File? _desktopCredentialFile() {
/// `crdt_sync` Python library) already keeps the sync account there as
/// `firebase.json` + `password`, both mode 600, so the desktop build reads
/// that rather than standing up a second credential the user would have to
/// enter and keep in step. It also sidesteps `google_sign_in`, which has no
/// Linux implementation at all.
/// enter and keep in step. It also sidesteps `google_account_token`, which is
/// Android-only.
///
/// Returns null when the files are absent or malformed; the caller then
/// reports the device as not connected, exactly as an empty keystore would.

View File

@ -2,7 +2,7 @@ part of 'firebase_backend.dart';
// The interactive Google sign-in path. Separate from the rest of the backend
// because it is the only piece that can raise UI, and because it is dead code
// on Linux desktop -- google_sign_in ships no Linux implementation, so the
// on Linux desktop -- google_account_token is Android-only, so the
// desktop build authenticates from the shared refresh token instead.
// coverage:ignore-start

View File

@ -0,0 +1,57 @@
/// The run screen's side of the foreground-service conversation.
library;
/// What the foreground service did when a recording asked for it.
enum RunServiceState {
/// Not started yet (or stopped).
none,
/// Running with its notification visible.
running,
/// Running, but the user denied notifications so nothing is on screen.
runningHidden,
/// The platform refused to start it: GPS may stop with the screen off.
failed,
/// This platform has no foreground services (Linux desktop, tests).
unsupported;
/// True while a service is up, notification shown or not.
bool get isUp => this == running || this == runningHidden;
}
/// Starting, feeding and stopping the recording's foreground service.
///
/// The GPS stream itself stays in the UI isolate (the recorder writes to the
/// database, which only that isolate may do); the service holds the process,
/// the wake lock and the notification so the stream keeps flowing with the
/// screen off. An interface so the controller is testable without Android,
/// and so the one file that touches `flutter_foreground_task` stays small.
abstract class ForegroundRunClient {
/// False on platforms with no foreground service.
bool get isSupported;
/// True when the app may post notifications.
Future<bool> hasNotificationPermission();
/// Asks for notification permission, returning whether it was granted.
Future<bool> requestNotificationPermission();
/// Starts the service showing [title] and [text]. [withLocation] adds the
/// `location` service type, which Android 14 only allows once the location
/// permission is held (the sandbox's replayed GPS has none, so it asks for
/// the data-sync type alone).
Future<bool> start({
required bool withLocation,
required String title,
required String text,
});
/// Redraws the notification.
Future<void> update({required String title, required String text});
/// Stops the service and removes its notification.
Future<void> stop();
}

View File

@ -0,0 +1,116 @@
/// The real run foreground-service client, and the service's entry point.
library;
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:workout_app/services/foreground_run_client.dart';
/// Channel the ongoing run notification lives on.
///
/// Low importance (it is on screen for the whole run and must never buzz) and
/// versioned for the same reason as the workout one: channel settings freeze
/// on first creation. The name is a symbol, not a word (textgate): Android
/// shows it in system settings.
const kRunOngoingChannelId = 'run_ongoing_v1';
// coverage:ignore-start
/// Entry point the plugin calls in the background isolate.
///
/// The handler does nothing: the recorder lives in the UI isolate. The
/// service exists to keep that isolate's process alive, to hold the wake lock
/// and to own the notification.
@pragma('vm:entry-point')
void runServiceStartCallback() {
FlutterForegroundTask.setTaskHandler(_RunServiceTaskHandler());
}
class _RunServiceTaskHandler extends TaskHandler {
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
void onNotificationPressed() => FlutterForegroundTask.launchApp();
@override
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {}
}
// coverage:ignore-end
/// The real [ForegroundRunClient], driving `flutter_foreground_task`.
class FlutterForegroundRunClient implements ForegroundRunClient {
/// Creates a client. Cheap: nothing happens until [start].
FlutterForegroundRunClient();
@override
bool get isSupported => Platform.isAndroid;
// Platform-channel passthroughs. `flutter test` runs on Linux, where
// isSupported is false and none of this is reachable; the decisions that
// lead here live in run_controller.dart, covered against a fake.
// coverage:ignore-start
@override
Future<bool> hasNotificationPermission() async =>
await FlutterForegroundTask.checkNotificationPermission() ==
NotificationPermission.granted;
@override
Future<bool> requestNotificationPermission() async =>
await FlutterForegroundTask.requestNotificationPermission() ==
NotificationPermission.granted;
@override
Future<bool> start({
required bool withLocation,
required String title,
required String text,
}) async {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: kRunOngoingChannelId,
channelName: '\u{1F3C3}',
onlyAlertOnce: true,
),
iosNotificationOptions: const IOSNotificationOptions(),
foregroundTaskOptions: ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.nothing(),
// allowWakeLock stays at its default (true): it is why GPS fixes keep
// arriving with the screen off.
),
);
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
final result = await FlutterForegroundTask.startService(
serviceTypes: [
ForegroundServiceTypes.dataSync,
if (withLocation) ForegroundServiceTypes.location,
],
notificationTitle: title,
notificationText: text,
callback: runServiceStartCallback,
);
return result is ServiceRequestSuccess;
}
@override
Future<void> update({required String title, required String text}) async {
await FlutterForegroundTask.updateService(
notificationTitle: title,
notificationText: text,
);
}
@override
Future<void> stop() async {
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
}
// coverage:ignore-end
}

View File

@ -1,11 +0,0 @@
/// Platform gate for the programmatic Google sign-in flow.
///
/// Conditional export because the answer differs per platform *and* because
/// asking the plugin directly is unsafe: `supportsAuthenticate()` throws
/// `UnimplementedError` where no implementation is registered -- an `Error`,
/// not an `Exception`, so it escapes an ordinary catch and would take down
/// the settings screen's `build()`.
library;
export 'google_platform_io.dart'
if (dart.library.js_interop) 'google_platform_web.dart';

View File

@ -1,10 +0,0 @@
/// Whether the programmatic Google sign-in flow exists on this platform.
///
/// The io half: Android has the Credential Manager flow; Linux desktop does
/// not, and this app's desktop build is the web one anyway.
library;
import 'dart:io';
/// True only on Android, the one platform shipping the programmatic flow.
bool get googleSignInSupported => Platform.isAndroid;

View File

@ -1,8 +0,0 @@
/// Whether the programmatic Google sign-in flow exists on this platform.
///
/// The web half: Google Identity Services signs in only through its own
/// rendered button, so `authenticate()` throws `UnimplementedError` here.
library;
/// Always false: the web plugin has no programmatic sign-in.
bool get googleSignInSupported => false;

View File

@ -2,9 +2,9 @@
///
/// Why this is its own file: `crdt_sync` is deliberately pure Dart (only
/// `crypto` and `http`), because the same library runs on Linux desktop and
/// headless under systemd, where `google_sign_in` does not exist. So the
/// plugin lives here, in the app, and the library only ever receives a token
/// string through a closure.
/// headless under systemd, where no Google plugin exists. So the plugin
/// (`google_account_token`) is used here, in the app, and the library only
/// ever receives a token string through a closure.
///
/// What this buys: on a fresh install the sync account is reached by tapping
/// one account-picker row instead of typing a long password on a phone
@ -14,8 +14,7 @@ library;
import 'dart:developer';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:workout_app/services/google_platform.dart' as platform_gate;
import 'package:google_account_token/google_account_token.dart' as plugin;
/// The account the security rules pin.
///
@ -37,7 +36,8 @@ const kSyncUid = 'OvA2REQyLIhAHOEjzwS1o877rgG3';
/// the phone-deploy skill and CI both run `flutter build apk --release`
/// with no defines, so released APKs would have shown a Google button that
/// always reported "cancelled" -- a visible control that can never succeed,
/// which is the exact thing the web platform gate exists to prevent.
/// which is the exact thing the [googleSignInSupported] gate exists to
/// prevent.
///
/// Fill this in from Firebase console -> Project settings -> the `syncs-rest`
/// Web app's OAuth client (type "Web application"). Android must request a
@ -50,73 +50,43 @@ const kServerClientId =
/// Whether this platform can sign in programmatically.
///
/// False on web, where Google Identity Services only signs in through its own
/// rendered button: `authenticate()` throws `UnimplementedError` there. The
/// desktop build of this app *is* the web build, so without this check the
/// "Sign in with Google" button would crash the settings screen on desktop
/// rather than falling back; see `google_platform.dart` for why this is a
/// platform check rather than a question asked of the plugin.
/// Only Android has an AccountManager (the plugin's own gate). Web and the
/// Linux desktop build authenticate from the shared credential instead, so
/// the button must not exist there. The plugin's check is web-safe (no
/// `dart:io`).
///
/// Also false when no client id is compiled in: a button that cannot possibly
/// succeed is worse than no button, and without this check an unconfigured
/// build reports "cancelled" and sends you debugging the OAuth console for a
/// problem that is really a missing constant.
bool get googleSignInSupported =>
platform_gate.googleSignInSupported && kServerClientId.isNotEmpty;
plugin.googleAccountTokenSupported && kServerClientId.isNotEmpty;
/// Returns a Google ID token for the signed-in account, or null.
///
/// Null rather than throwing when the user dismisses the picker: cancelling is
/// an ordinary outcome, and the caller falls back to the password path.
///
/// [signInFn] and [serverClientId] exist for tests, which cannot reach the
/// platform channel the plugin uses.
/// [signInFn], [serverClientId] and [warn] exist for tests that bypass the
/// plugin or observe the log.
Future<String?> googleIdToken({
Future<String?> Function()? signInFn,
String serverClientId = kServerClientId,
void Function(String message)? warn,
}) async {
if (signInFn != null) return await signInFn();
if (serverClientId.isEmpty) {
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
// fail inside the plugin with a far less obvious message.
log(
'Google sign-in unavailable: GOOGLE_SERVER_CLIENT_ID was not set at '
'build time; falling back to the password path',
level: 900,
);
return null;
}
// The plugin reaches the OS account picker through a platform channel,
// which `flutter test` has no binding for -- the same reason main.dart and
// firebase_backend.dart's keystore adapters are excluded. Everything above
// this point is pure Dart and is covered.
// coverage:ignore-start
try {
await GoogleSignIn.instance.initialize(serverClientId: serverClientId);
if (!GoogleSignIn.instance.supportsAuthenticate()) {
// Web/desktop: sign-in must go through the rendered GIS button, which
// this app does not host yet. Fall back rather than throwing.
log(
'Google sign-in is not available on this platform; falling back to '
'the password path',
level: 900,
);
return null;
// Repo rule: a guard that aborts work must say so. Without this the
// caller only sees "cancelled" and debugs the OAuth console instead.
const message =
'WorkoutApp: Google sign-in unavailable: the Web client id '
'(kServerClientId) is empty; falling back to the password path';
if (warn != null) {
warn(message);
} else {
log(message, level: 900);
}
final account = await GoogleSignIn.instance.authenticate();
return account.authentication.idToken;
} on GoogleSignInException catch (error, stackTrace) {
// Includes the user simply dismissing the picker, which is not an error
// worth surfacing -- but log it, because a *configuration* failure
// (unregistered SHA-1, wrong client id) arrives through the same path and
// is otherwise indistinguishable from "the user changed their mind".
log(
'Google sign-in did not complete',
level: 900,
error: error,
stackTrace: stackTrace,
);
return null;
}
// coverage:ignore-end
return await plugin.googleIdToken(serverClientId: serverClientId);
}

View File

@ -0,0 +1,149 @@
/// Turns raw GPS fixes into the accepted points of a track.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/run_math.dart';
/// Worst horizontal accuracy (metres, 68 % radius) a fix may report.
const double kMaxFixAccuracyM = 25;
/// Consecutive "too fast" fixes after which the filter concludes its anchor
/// was the bad one and re-anchors on the newest fix.
const int kMaxConsecutiveJumps = 5;
/// One reading from the platform's location provider.
@immutable
class GpsFix {
/// Creates a fix.
const GpsFix({
required this.time,
required this.latitude,
required this.longitude,
required this.accuracyM,
this.altitudeM,
this.isMocked = false,
});
/// When the provider took the fix.
final DateTime time;
/// Degrees north.
final double latitude;
/// Degrees east.
final double longitude;
/// Metres above sea level, when known.
final double? altitudeM;
/// Horizontal accuracy radius in metres.
final double accuracyM;
/// Whether Android flagged the fix as coming from a mock provider.
final bool isMocked;
}
/// Why [GpsFilter.add] kept or dropped a fix.
enum FixVerdict {
/// Kept as a new point.
accepted,
/// Dropped: a mock-location fix (faking a run must not credit it).
mocked,
/// Dropped: accuracy worse than [kMaxFixAccuracyM], or not a number.
inaccurate,
/// Dropped: not strictly later (whole seconds) than the last point.
outOfOrder,
/// Dropped: implies a speed above the sport's cap, i.e. a GPS jump.
tooFast,
}
/// Accumulates accepted points and their cumulative credited distance.
///
/// A step between two accepted points adds distance only when it is a moving
/// step (see [isMovingStep]): a dropout longer than [kMaxCreditGapSeconds]
/// and standing-still jitter credit nothing, same as the PC reads a walk.
class GpsFilter {
/// Creates a filter for [sport] (which picks the speed cap).
GpsFilter({required this.sport});
/// The sport being recorded.
final RunSport sport;
final List<RunPoint> _points = [];
int _jumps = 0;
bool _segmentBreak = false;
/// Accepted points so far, in time order.
List<RunPoint> get points => List.unmodifiable(_points);
/// Cumulative credited distance in metres.
double get distanceM => _points.isEmpty ? 0 : _points.last.distanceM;
/// Marks a pause: the next accepted fix starts a new segment, credited with
/// nothing, whatever distance separates it from the last point.
///
/// Without this, a short pause (under [kMaxCreditGapSeconds]) would credit
/// the walk across the paused stretch, and a long one could trip the jump
/// cap on the first fix after resuming.
void breakSegment() => _segmentBreak = true;
/// Judges [fix]; an accepted fix is appended to [points].
FixVerdict add(GpsFix fix) {
if (fix.isMocked) return FixVerdict.mocked;
if (!(fix.accuracyM >= 0 && fix.accuracyM <= kMaxFixAccuracyM)) {
return FixVerdict.inaccurate;
}
// Whole seconds: that is all a TCX trackpoint can say.
final time = DateTime.fromMillisecondsSinceEpoch(
fix.time.millisecondsSinceEpoch ~/ 1000 * 1000,
isUtc: true,
);
if (_points.isEmpty) {
_accept(fix, time, 0);
return FixVerdict.accepted;
}
final last = _points.last;
final gap = time.difference(last.time).inSeconds;
if (gap <= 0) return FixVerdict.outOfOrder;
if (_segmentBreak) {
_segmentBreak = false;
_accept(fix, time, 0);
return FixVerdict.accepted;
}
final step = haversineM(
last.latitude,
last.longitude,
fix.latitude,
fix.longitude,
);
if (step / gap > maxSpeedMps(sport)) {
_jumps++;
if (_jumps < kMaxConsecutiveJumps) return FixVerdict.tooFast;
// The anchor, not the fixes, was wrong: continue from here, no credit.
_accept(fix, time, 0);
return FixVerdict.accepted;
}
final moving =
gap <= kMaxCreditGapSeconds && step / gap >= kMinMovingSpeedMps;
_accept(fix, time, moving ? step : 0);
return FixVerdict.accepted;
}
void _accept(GpsFix fix, DateTime time, double credited) {
_jumps = 0;
_points.add(
RunPoint(
time: time,
latitude: fix.latitude,
longitude: fix.longitude,
altitudeM: fix.altitudeM,
distanceM: distanceM + credited,
),
);
}
}

View File

@ -0,0 +1,76 @@
/// The OSM tile source and its on-disk cache.
///
/// Tiles come from tile.openstreetmap.org and are kept in the app's cache
/// directory (flutter_map_cache over dio_cache_interceptor) with a one-year
/// max-stale, so an area visited once draws offline later. OSM's tile usage
/// policy needs a real User-Agent: the [TileLayer] sends
/// [osmUserAgentPackage].
library;
import 'dart:async';
import 'dart:developer' as developer;
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_cache/flutter_map_cache.dart';
import 'package:http_cache_file_store/http_cache_file_store.dart';
import 'package:path_provider/path_provider.dart';
/// The OSM raster tile template.
const osmTileUrl = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
/// Sent as the tile User-Agent, as OSM's tile policy asks.
const osmUserAgentPackage = 'com.kuhy.workout_app';
/// How long a cached tile may be served when the network cannot refresh it.
const tileMaxStale = Duration(days: 365);
/// Opens a [TileProvider]; swapped for a fake in tests.
typedef TileProviderOpener = Future<TileProvider> Function();
/// A provider that caches into [cacheDir] (and serves stale tiles offline).
TileProvider buildCachedTileProvider(String cacheDir, {Dio? dio}) =>
CachedTileProvider(
store: FileCacheStore(cacheDir),
maxStale: tileMaxStale,
dio: dio,
);
Future<String?>? _cacheDir;
/// A disk-cached OSM provider; each map gets its own.
///
/// Only the cache directory is looked up once per process. A provider is
/// never shared: `TileLayer` disposes its provider when the map goes away
/// (a `NetworkTileProvider` closes its HTTP client then), so a shared one
/// would be dead for the second map.
///
/// If the cache directory cannot be had, the map still works over the
/// network without a cache, and the reason is logged once at warning level.
Future<TileProvider> openOsmTileProvider() async {
final dir = await (_cacheDir ??= _resolveCacheDir());
return dir == null ? NetworkTileProvider() : buildCachedTileProvider(dir);
}
/// Forgets the looked-up cache directory (tests only).
@visibleForTesting
void resetOsmTileProvider() => _cacheDir = null;
Future<String?> _resolveCacheDir() async {
try {
final dir = await getApplicationCacheDirectory();
return '${dir.path}/osm_tiles';
} on Object catch (error) {
final message = 'map tile cache unavailable, tiles not persisted: $error';
developer.log(message, name: 'RunMap', level: 900);
debugPrint('RunMap WARNING: $message');
return null;
}
}
/// Logs [message] at warning level (900), loud in `flutter logs` too.
void logMapWarning(String message) {
developer.log(message, name: 'RunMap', level: 900);
debugPrint('RunMap WARNING: $message');
}

View File

@ -0,0 +1,38 @@
/// The seam between the recorder and the platform's location provider.
///
/// Everything above this interface (recorder, map, sandbox replay) is pure
/// Dart and runs on the Linux test host and the desktop target; only
/// `GeolocatorPositionSource` touches the geolocator plugin.
library;
import 'package:workout_app/services/gps_filter.dart';
/// Whether the app may read the location right now.
enum LocationAccess {
/// Permission granted and the location service is on.
granted,
/// Permission refused this time; asking again may work.
denied,
/// Permission refused for good; only the system settings can change it.
deniedForever,
/// Permission is fine but the device's location switch is off.
serviceOff;
/// Whether fixes can be read right now.
bool get isGranted => this == LocationAccess.granted;
}
/// A stream of GPS fixes plus the permission handshake that guards it.
abstract class PositionSource {
/// Asks for (or re-checks) location permission; never throws for a refusal.
Future<LocationAccess> requestAccess();
/// Fixes roughly every [interval], best accuracy, until cancelled.
///
/// [interval] must stay well under the PC's 30 s credit gap
/// (`kMaxCreditGapSeconds`): a quieter stream earns nothing.
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)});
}

View File

@ -0,0 +1,57 @@
/// The real [PositionSource], backed by the geolocator plugin.
library;
import 'package:geolocator/geolocator.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
/// Reads fixes through [GeolocatorPlatform.instance], so a test can swap the
/// platform and drive this class without a device.
class GeolocatorPositionSource implements PositionSource {
/// Creates the source; [forceLocationManager] skips Google Play services.
GeolocatorPositionSource({this.forceLocationManager = false});
/// Android: use the legacy LocationManager instead of the fused provider.
final bool forceLocationManager;
GeolocatorPlatform get _platform => GeolocatorPlatform.instance;
@override
Future<LocationAccess> requestAccess() async {
if (!await _platform.isLocationServiceEnabled()) {
return LocationAccess.serviceOff;
}
var permission = await _platform.checkPermission();
if (permission == LocationPermission.denied) {
permission = await _platform.requestPermission();
}
return switch (permission) {
LocationPermission.always ||
LocationPermission.whileInUse => LocationAccess.granted,
LocationPermission.deniedForever => LocationAccess.deniedForever,
LocationPermission.denied ||
LocationPermission.unableToDetermine => LocationAccess.denied,
};
}
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
_platform
.getPositionStream(
locationSettings: AndroidSettings(
accuracy: LocationAccuracy.bestForNavigation,
intervalDuration: interval,
forceLocationManager: forceLocationManager,
),
)
.map(
(p) => GpsFix(
time: p.timestamp,
latitude: p.latitude,
longitude: p.longitude,
altitudeM: p.altitude,
accuracyM: p.accuracy,
isMocked: p.isMocked,
),
);
}

View File

@ -0,0 +1,43 @@
/// A [PositionSource] that replays a fixed list of fixes.
///
/// For widget and recorder tests and for the sandbox flavor's replayed run:
/// no plugin, no permission prompt, deterministic.
library;
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
/// Emits [script] once, in order, then closes the stream.
class ScriptedPositionSource implements PositionSource {
/// Creates a source that answers [access] and replays [script].
///
/// With [fixDelay] set, each fix is emitted that long after the previous
/// one (a real-time replay); otherwise they arrive back to back.
ScriptedPositionSource(
this.script, {
this.access = LocationAccess.granted,
this.fixDelay,
});
/// The fixes to replay.
final List<GpsFix> script;
/// What [requestAccess] answers.
final LocationAccess access;
/// Pause before each fix, or null for none.
final Duration? fixDelay;
@override
Future<LocationAccess> requestAccess() async => access;
@override
Stream<GpsFix> fixes({
Duration interval = const Duration(seconds: 2),
}) async* {
for (final fix in script) {
if (fixDelay != null) await Future<void>.delayed(fixDelay!);
yield fix;
}
}
}

View File

@ -0,0 +1,163 @@
/// Wires one recording to the phone: permission, foreground service, cues,
/// notification and the save at the end.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_notification.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
/// Owns a [RunRecorder] and everything that must happen around it.
///
/// Order matters at the start: location access first (the recorder asks), then
/// the foreground service (Android 14 refuses a `location` service without
/// the permission), then the first fix.
class RunController extends ChangeNotifier {
/// Creates a controller; it builds its own [recorder] over [sourceFor].
RunController({
required PositionSource Function(RunSport sport) sourceFor,
required this._service,
required this._cues,
required this._save,
}) {
recorder = RunRecorder(sourceFor: sourceFor, onKilometre: _onKilometre)
..addListener(_onRecorderChanged);
}
/// The state machine; the live map reads its points.
late final RunRecorder recorder;
final ForegroundRunClient _service;
final FeedbackCues _cues;
final Future<RunSaveResult> Function(RunTrack track) _save;
RunServiceState _serviceState = RunServiceState.none;
RunSaveResult? _saved;
bool _saving = false;
String _lastCopy = '';
/// Whether the foreground service is up (and with a notification).
RunServiceState get serviceState => _serviceState;
/// What saving the finished run did, once it ran.
RunSaveResult? get saved => _saved;
/// True while the finished run is being written.
bool get saving => _saving;
/// True from start to finish: the screen must not be left meanwhile.
bool get active => recorder.phase.isActive;
/// Asks for access, starts the service, begins recording.
Future<void> start() async {
await _cues.load();
await recorder.start(afterAccess: _startService);
}
/// Pauses crediting.
void pause() => recorder.pause();
/// Resumes crediting.
void resume() => recorder.resume();
/// Ends the run, stops the service and saves the track.
Future<void> finish() async {
final track = await recorder.finish();
await _stopService();
if (track == null) return;
unawaited(_cues.workoutFinished());
_saving = true;
notifyListeners();
try {
_saved = await _save(track);
} on Exception catch (error, stack) {
log(
'RunController: saving ${track.id} failed ($error) -- the run is '
'lost unless it is recorded again.',
level: 1000,
error: error,
stackTrace: stack,
);
_saved = RunSaveResult(stored: false, reason: 'save failed: $error');
}
_saving = false;
notifyListeners();
}
Future<void> _startService() async {
if (!_service.isSupported) {
_serviceState = RunServiceState.unsupported;
return;
}
var shown = await _service.hasNotificationPermission();
if (!shown) shown = await _service.requestNotificationPermission();
if (!shown) {
log(
'RunController: notification permission denied. The run still '
'records, but the status-bar distance and time cannot be shown.',
level: 1000,
);
}
final copy = runNotificationCopy(metres: 0, movingSeconds: 0);
_lastCopy = '${copy.title}|${copy.body}';
final started = await _service.start(
withLocation: !Sandbox.enabled,
title: copy.title,
text: copy.body,
);
if (!started) {
_serviceState = RunServiceState.failed;
log(
'RunController: the foreground service refused to start. GPS fixes '
'may stop when the screen turns off -- keep the app open.',
level: 1000,
);
return;
}
_serviceState = shown
? RunServiceState.running
: RunServiceState.runningHidden;
}
Future<void> _stopService() async {
if (!_serviceState.isUp) return;
await _service.stop();
_serviceState = RunServiceState.none;
notifyListeners();
}
void _onKilometre(int km) => unawaited(_cues.kilometreReached(km));
void _onRecorderChanged() {
if (_serviceState == RunServiceState.running) {
final copy = runNotificationCopy(
metres: recorder.distanceM,
movingSeconds: recorder.seconds,
);
// Only when the words changed: an update per fix would redraw twice a
// second for nothing.
if ('${copy.title}|${copy.body}' != _lastCopy) {
_lastCopy = '${copy.title}|${copy.body}';
unawaited(_service.update(title: copy.title, text: copy.body));
}
}
notifyListeners();
}
@override
void dispose() {
recorder
..removeListener(_onRecorderChanged)
..dispose();
if (active) unawaited(_service.stop());
super.dispose();
}
}

View File

@ -0,0 +1,40 @@
/// Number formatting for run tiles and the run detail screen.
///
/// Numbers only: textgate bans words in the UI, so there are no unit
/// suffixes. The icon next to a value (distance, clock, pace) names it.
library;
String _two(int v) => v.toString().padLeft(2, '0');
/// Kilometres with two decimals, e.g. `5.20`.
String formatDistanceKm(double distanceM) =>
(distanceM / 1000).toStringAsFixed(2);
/// `m:ss`, or `h:mm:ss` from an hour up; [seconds] is moving time.
String formatDuration(int seconds) {
final h = seconds ~/ 3600;
final m = (seconds ~/ 60).remainder(60);
final s = seconds % 60;
return h > 0 ? '$h:${_two(m)}:${_two(s)}' : '$m:${_two(s)}';
}
/// Average pace as `m:ss` per kilometre, or `-:--` when under 10 m was
/// covered (the quotient is meaningless, and 0 would divide by zero).
String formatPace({required int seconds, required double distanceM}) {
if (distanceM < 10) return '-:--';
final perKm = (seconds / (distanceM / 1000)).round();
return '${perKm ~/ 60}:${_two(perKm % 60)}';
}
/// `dd.MM` of [when] in the device's local time.
String formatRunDay(DateTime when) {
final l = when.toLocal();
return '${_two(l.day)}.${_two(l.month)}';
}
/// `yyyy-MM-dd HH:mm` of [when] in the device's local time.
String formatFullDate(DateTime when) {
final l = when.toLocal();
return '${l.year}-${_two(l.month)}-${_two(l.day)} '
'${_two(l.hour)}:${_two(l.minute)}';
}

View File

@ -0,0 +1,59 @@
/// Merges the phone's own runs into the history list without doubling them.
///
/// The PC pushes a `runnerup_verified` calendar entry for every day it
/// credited a RunnerUp run or walk. Once the app records (or imports) the same
/// run itself, that entry says nothing the local run does not, and the local
/// one has the map. This hides the duplicate.
///
/// The key is **day + sport**, not a start time, because that is all the PC
/// entry carries: its record id is `runnerup_verified:<YYYY-MM-DD>` (one slot
/// per day, runs and walks merged), and the payload holds `date`,
/// `distance_km`, `duration_minutes`, an optional `completed_at` (the *end*,
/// often absent) and `activity: walking` for a day of walks. There is no
/// start time to match within a window. Sport keeps a stock-RunnerUp run
/// visible next to an app-recorded walk on the same day.
///
/// When nothing matches, both stay visible: a duplicate is a nuisance, a
/// hidden credited run is a lie.
library;
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/done_today.dart';
/// The `kind` the PC gives its run/walk entries.
const kRunnerUpVerifiedKind = 'runnerup_verified';
String _key(RunSport sport, String day) => '${sport.tcxName}|$day';
/// The `YYYY-MM-DD` part of a PC entry's `date`.
String _entryDay(Map<String, dynamic> payload) {
final date = '${payload['date']}';
return date.length > 10 ? date.substring(0, 10) : date;
}
/// The sport a PC entry stands for: a day of walks says so, anything else is
/// a run.
RunSport _entrySport(Map<String, dynamic> payload) =>
payload['activity'] == 'walking' ? RunSport.walking : RunSport.running;
/// [synced] without the `runnerup_verified` entries that [runs] already
/// cover (same local day and same sport).
///
/// Days are the device's local calendar days, the calendar the PC dates its
/// records by (`dayKey`). Other kinds pass through untouched.
List<Map<String, dynamic>> withoutLocalRuns(
List<Map<String, dynamic>> synced,
Iterable<RunRecord> runs,
) {
final covered = {
for (final r in runs)
_key(r.track.sport, dayKey(r.track.startedAt.toLocal())),
};
return [
for (final p in synced)
if (p['kind'] != kRunnerUpVerifiedKind ||
!covered.contains(_key(_entrySport(p), _entryDay(p))))
p,
];
}

View File

@ -0,0 +1,74 @@
/// Distance and moving-time maths for recorded tracks (pure, no I/O).
library;
import 'dart:math' as math;
import 'package:workout_app/models/run_track.dart';
/// Mean Earth radius in metres (IUGG), the haversine constant.
const double kEarthRadiusM = 6371008.8;
/// A pair of fixes further apart in time than this earns neither distance
/// nor moving time: a GPS dropout whose motion is unknown.
///
/// Mirrors `WALK_MAX_GAP_SECONDS` in the PC's `screen_locker/_constants.py`.
/// This is a mirror of the rule the PC applies to a walk's trackpoints, so the
/// app never reports moving time the PC would discard -- it is NOT a crediting
/// threshold (those stay on the PC).
const int kMaxCreditGapSeconds = 30;
/// A pair slower than this is standing still, not moving.
///
/// Mirrors the lower bound of `WALK_SPEED_MPS` on the PC.
const double kMinMovingSpeedMps = 0.5;
/// Speed cap above which a fix is a GPS jump, 25 km/h for a run.
const double kRunningMaxSpeedMps = 25 / 3.6;
/// Speed cap above which a fix is a GPS jump, 8 km/h for a walk.
const double kWalkingMaxSpeedMps = 8 / 3.6;
/// The jump cap for [sport].
double maxSpeedMps(RunSport sport) => switch (sport) {
RunSport.running => kRunningMaxSpeedMps,
RunSport.walking => kWalkingMaxSpeedMps,
};
double _rad(double degrees) => degrees * math.pi / 180;
/// Great-circle distance in metres between two WGS-84 positions.
double haversineM(double lat1, double lon1, double lat2, double lon2) {
final dLat = _rad(lat2 - lat1);
final dLon = _rad(lon2 - lon1);
final a =
math.pow(math.sin(dLat / 2), 2) +
math.cos(_rad(lat1)) *
math.cos(_rad(lat2)) *
math.pow(math.sin(dLon / 2), 2);
return 2 * kEarthRadiusM * math.asin(math.min(1, math.sqrt(a)));
}
/// Whether the step from [a] to [b] counts as moving: seen within
/// [kMaxCreditGapSeconds] and travelled at a speed in
/// `[kMinMovingSpeedMps, maxSpeed]`.
///
/// Speed comes from the cumulative `distanceM` difference, exactly as the PC
/// reads a TCX, so app and PC agree on which steps count.
bool isMovingStep(RunPoint a, RunPoint b, double maxSpeed) {
final gap = b.time.difference(a.time).inMilliseconds / 1000;
if (gap <= 0 || gap > kMaxCreditGapSeconds) return false;
final speed = (b.distanceM - a.distanceM) / gap;
return speed >= kMinMovingSpeedMps && speed <= maxSpeed;
}
/// Moving seconds over [points]: the summed gaps of every moving step.
int movingSeconds(List<RunPoint> points, RunSport sport) {
final cap = maxSpeedMps(sport);
var total = 0.0;
for (var i = 1; i < points.length; i++) {
if (isMovingStep(points[i - 1], points[i], cap)) {
total += points[i].time.difference(points[i - 1].time).inSeconds;
}
}
return total.round();
}

View File

@ -0,0 +1,15 @@
/// The two lines of the ongoing run notification (numbers only, textgate).
library;
import 'package:workout_app/services/run_format.dart';
/// Distance as the title; moving time and average pace as the body.
({String title, String body}) runNotificationCopy({
required double metres,
required int movingSeconds,
}) => (
title: formatDistanceKm(metres),
body:
'${formatDuration(movingSeconds)} '
'${formatPace(seconds: movingSeconds, distanceM: metres)}',
);

View File

@ -0,0 +1,44 @@
/// The phases and problems of a GPS recording.
library;
/// Where a recording stands.
enum RunPhase {
/// Nothing recorded yet; the sport can still be chosen.
idle,
/// Fixes are being kept and credited.
recording,
/// Fixes are ignored; nothing is credited until [RunRecorder.resume].
paused,
/// Over; [RunRecorder.finish] has returned the track.
finished;
/// True from start to finish: recording or paused.
bool get isActive => this == recording || this == paused;
}
/// What is wrong with the recording right now (shown as an icon, logged).
enum RunIssue {
/// Nothing.
none,
/// Location permission refused; asking again may work.
denied,
/// Location permission refused for good; only system settings can fix it.
deniedForever,
/// The device's location switch is off.
serviceOff,
/// The newest fix came from a mock-location provider and was dropped.
mockedLocation,
/// The location stream reported an error.
streamError,
/// Finished with too few usable fixes to make a track; nothing was saved.
tooShort,
}

View File

@ -0,0 +1,235 @@
/// The GPS run/walk state machine: idle, recording, paused, finished.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_math.dart';
import 'package:workout_app/services/run_phase.dart';
export 'package:workout_app/services/run_phase.dart';
/// Records one run or walk from a [PositionSource].
///
/// A pause ignores fixes and breaks the filter's segment, so the stretch
/// walked while paused and the first fix after it credit nothing. Moving time
/// is the PC's rule ([movingSeconds]) applied as fixes arrive, so the number
/// on screen is the number the PC will credit.
class RunRecorder extends ChangeNotifier {
/// Creates a recorder; [sourceFor] builds the fix stream for the chosen
/// sport when [start] is called (the sandbox's replay speed follows it).
RunRecorder({required this.sourceFor, this.onKilometre});
/// Builds the source for one recording.
final PositionSource Function(RunSport sport) sourceFor;
/// Called with 1, 2, 3 ... as each whole kilometre is credited.
final void Function(int km)? onKilometre;
RunSport _sport = RunSport.running;
RunPhase _phase = RunPhase.idle;
RunIssue _issue = RunIssue.none;
GpsFilter? _filter;
StreamSubscription<GpsFix>? _sub;
bool _starting = false;
int _moving = 0;
int _km = 0;
final _live = ValueNotifier<List<RunPoint>>(const []);
final _seenVerdicts = <FixVerdict>{};
/// Running or walking.
RunSport get sport => _sport;
/// The state machine's phase.
RunPhase get phase => _phase;
/// The current problem, or [RunIssue.none].
RunIssue get issue => _issue;
/// Accepted points so far, for the live map.
ValueListenable<List<RunPoint>> get livePoints => _live;
/// Credited moving time in seconds.
int get seconds => _moving;
/// Credited distance in metres.
double get distanceM => _filter?.distanceM ?? 0;
/// Picks the sport; only possible while [RunPhase.idle].
bool selectSport(RunSport sport) {
if (_phase != RunPhase.idle) return false;
_sport = sport;
notifyListeners();
return true;
}
/// Asks for location access, runs [afterAccess] (where the caller starts the
/// foreground service, which Android 14 only allows once access is held),
/// then begins recording. False when access was refused or a start is
/// already under way; [issue] says why.
Future<bool> start({Future<void> Function()? afterAccess}) async {
if (_phase != RunPhase.idle || _starting) return false;
_starting = true;
try {
final source = sourceFor(_sport);
final access = await source.requestAccess();
if (!access.isGranted) {
_refuse(access);
return false;
}
await afterAccess?.call();
_filter = GpsFilter(sport: _sport);
_sub = source
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
.listen(_onFix, onError: _onError, onDone: _onDone);
_issue = RunIssue.none;
_phase = RunPhase.recording;
SandboxLog.event('run started', {'sport': _sport.tcxName});
notifyListeners();
return true;
} finally {
_starting = false;
}
}
/// Stops crediting until [resume].
void pause() {
if (_phase != RunPhase.recording) return;
_filter!.breakSegment();
_phase = RunPhase.paused;
SandboxLog.event('run paused', {'km': distanceM});
notifyListeners();
}
/// Continues after [pause].
void resume() {
if (_phase != RunPhase.paused) return;
_phase = RunPhase.recording;
SandboxLog.event('run resumed', {'km': distanceM});
notifyListeners();
}
/// Ends the recording and returns the track, or null when there were too
/// few usable fixes (then [issue] is [RunIssue.tooShort]).
Future<RunTrack?> finish() async {
if (!_phase.isActive) return null;
await _sub?.cancel();
_sub = null;
_phase = RunPhase.finished;
final points = _filter!.points;
_moving = movingSeconds(points, _sport);
RunTrack? track;
if (points.length < 2) {
_issue = RunIssue.tooShort;
log(
'RunRecorder: finished with ${points.length} usable GPS fix(es) '
'-- not enough for a track, so nothing is saved.',
level: 1000,
);
} else {
track = RunTrack.started(
sport: _sport,
startedAt: points.first.time,
points: points,
totalSeconds: _moving,
distanceM: _filter!.distanceM,
);
}
SandboxLog.event('run finished', {
'km': distanceM,
'secs': _moving,
'points': points.length,
'saved': track != null,
});
notifyListeners();
return track;
}
void _refuse(LocationAccess access) {
_issue = switch (access) {
LocationAccess.deniedForever => RunIssue.deniedForever,
LocationAccess.serviceOff => RunIssue.serviceOff,
_ => RunIssue.denied,
};
final fix = access == LocationAccess.serviceOff
? 'Switch location on'
: 'Grant location to the app in system settings';
log(
'RunRecorder: not recording -- location access is ${access.name}. '
'$fix and start again.',
level: 1000,
);
notifyListeners();
}
void _onFix(GpsFix fix) {
if (_phase != RunPhase.recording) return;
final verdict = _filter!.add(fix);
if (verdict != FixVerdict.accepted) {
_noteDropped(verdict);
return;
}
_issue = RunIssue.none;
final points = _filter!.points;
final n = points.length;
if (n >= 2 &&
isMovingStep(points[n - 2], points[n - 1], maxSpeedMps(_sport))) {
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
}
_live.value = points;
while (distanceM ~/ 1000 > _km) {
_km++;
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
onKilometre?.call(_km);
}
notifyListeners();
}
void _noteDropped(FixVerdict verdict) {
if (verdict == FixVerdict.mocked) {
_issue = RunIssue.mockedLocation;
notifyListeners();
}
// Said once per kind and run: a bad tunnel would otherwise flood the log.
if (!_seenVerdicts.add(verdict)) return;
log(
'RunRecorder: dropped a GPS fix (${verdict.name}); further drops of '
'this kind are not logged. Mock fixes never count towards a run.',
level: 900,
);
}
void _onError(Object error, StackTrace stack) {
_issue = RunIssue.streamError;
log(
'RunRecorder: the location stream failed ($error) -- fixes may have '
'stopped; time and distance are not crediting until they resume.',
level: 1000,
error: error,
stackTrace: stack,
);
notifyListeners();
}
void _onDone() {
if (!_phase.isActive) return;
log(
'RunRecorder: the location stream ended while still recording; '
'finish the run to save what was captured.',
level: 900,
);
SandboxLog.event('run stream ended', {'km': distanceM});
}
@override
void dispose() {
unawaited(_sub?.cancel());
_live.dispose();
super.dispose();
}
}

View File

@ -0,0 +1,52 @@
/// Stores a finished recording and queues it for upload.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/tcx_codec.dart';
/// What [saveRecordedRun] did.
@immutable
class RunSaveResult {
/// Creates a result.
const RunSaveResult({required this.stored, required this.reason});
/// Whether a new row was written.
final bool stored;
/// A sentence saying what happened.
final String reason;
}
/// Writes [track] to the `runs` table as an app-recorded, pending-upload run
/// and calls [enqueue] (without awaiting it) so the upload starts now.
Future<RunSaveResult> saveRecordedRun(
RunTrack track, {
required StorageService storage,
required Future<Object?> Function() enqueue,
}) async {
final tcx = encodeTcx(track);
final name = tcxFilename(track);
final stored = await storage.insertRun(
track,
tcxFilename: name,
tcxSha256: tcxSha256(tcx),
uploadState: RunUploadState.pending,
);
if (!stored) {
final reason =
'run ${track.id} is already stored (same id or same TCX), so '
'nothing new was saved or queued.';
log('RunSaver: $reason', level: 1000);
return RunSaveResult(stored: false, reason: reason);
}
SandboxLog.event('run saved', {'id': track.id, 'file': name});
unawaited(enqueue());
return RunSaveResult(stored: true, reason: 'saved $name');
}

View File

@ -0,0 +1,117 @@
/// Where finished runs are uploaded, and the login for it.
///
/// The login is a dufs account scoped to the PC's `/RunnerUp` folder. It is
/// never typed on the phone: `scripts/provision_run_upload.sh` pushes a
/// `dufs_login.json` into the app's external files directory, and
/// [RunCredentialStore.importProvisionFile] moves it into secure storage and
/// deletes the file.
library;
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:path_provider/path_provider.dart';
import 'package:workout_app/services/dufs_credentials.dart';
/// File name the provisioning script pushes.
const String kProvisionFileName = 'dufs_login.json';
/// What an import attempt found.
enum ProvisionStatus {
/// No file: the normal case on every start after the first.
absent,
/// Login stored and the file deleted.
imported,
/// A file was there but unusable; it was left in place.
invalid,
}
/// Result of [RunCredentialStore.importProvisionFile].
@immutable
class ProvisionOutcome {
/// Creates an outcome.
const ProvisionOutcome(this.status, this.reason);
/// What happened.
final ProvisionStatus status;
/// A sentence saying why.
final String reason;
}
Future<Directory?> _externalFilesDir() async {
// coverage:ignore-start
// Android-only plugin call; path_provider throws on every other platform.
if (Platform.isAndroid) return await getExternalStorageDirectory();
// coverage:ignore-end
return null;
}
/// Imports the upload login into secure storage (the slots of
/// [DufsCredentials], shared with the history importer).
class RunCredentialStore {
/// Creates a store; the arguments are test seams.
RunCredentialStore({
this._secure = const FlutterSecureStorage(),
this._externalDir = _externalFilesDir,
});
final FlutterSecureStorage _secure;
final Future<Directory?> Function() _externalDir;
/// The stored login, or null when none was provisioned yet.
Future<DufsCredentials?> read() => DufsCredentials.load(storage: _secure);
/// Moves `<external files dir>/dufs_login.json` into secure storage and
/// deletes it. An unusable file stays put and is reported, so a typo in the
/// script's output cannot silently leave uploads switched off.
Future<ProvisionOutcome> importProvisionFile() async {
final dir = await _externalDir();
if (dir == null) {
return const ProvisionOutcome(
ProvisionStatus.absent,
'no external files directory on this platform',
);
}
final file = File('${dir.path}/$kProvisionFileName');
if (!file.existsSync()) {
return const ProvisionOutcome(ProvisionStatus.absent, 'no login file');
}
final login = _parse(await file.readAsString());
if (login == null) {
const reason =
'$kProvisionFileName is not {"url","user","password"} with an '
'http(s) url, so run uploads stay switched off. Re-run '
'scripts/provision_run_upload.sh.';
log('RunCredentialStore: $reason', level: 1000);
return const ProvisionOutcome(ProvisionStatus.invalid, reason);
}
await login.save(storage: _secure);
await file.delete();
log('RunCredentialStore: imported the run-upload login for ${login.user}.');
return ProvisionOutcome(
ProvisionStatus.imported,
'imported the login for ${login.user}',
);
}
DufsCredentials? _parse(String text) {
final Object? decoded;
try {
decoded = jsonDecode(text);
} on FormatException catch (error) {
log('RunCredentialStore: $kProvisionFileName is not JSON ($error)');
return null;
}
if (decoded is! Map<String, dynamic>) return null;
final login = DufsCredentials.fromJson(decoded);
final uri = login == null ? null : Uri.tryParse(login.url);
if (uri == null || !uri.hasAuthority) return null;
return const {'http', 'https'}.contains(uri.scheme) ? login : null;
}
}

View File

@ -0,0 +1,242 @@
/// Uploads recorded runs to the PC's dufs inbox.
///
/// The PC credits a run from the TCX it finds in `/RunnerUp`; the credit is
/// anchored on the run's own time, so a late upload still counts in full. The
/// queue is the `runs` table itself (upload_state `pending`), so nothing here
/// can lose a run: a failure just leaves the row pending for the next try.
library;
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/dufs_credentials.dart';
import 'package:workout_app/services/run_upload_credentials.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/tcx_codec.dart';
/// Server folder the PC watches.
const String kRunInboxFolder = 'RunnerUp';
/// How long one PUT may take.
const Duration kUploadTimeout = Duration(seconds: 30);
/// How long after a failure the queue tries again while the app is open.
const Duration kUploadRetryAfter = Duration(minutes: 1);
/// Where the queue stands (shown as an icon).
enum UploadHealth {
/// Nothing waiting, or everything went through.
idle,
/// A pass is running.
uploading,
/// The last pass failed; a retry is scheduled.
retrying,
/// Runs are waiting but no login was provisioned.
notConfigured,
/// The sandbox flavor: runs are kept, nothing is ever sent.
sandbox,
}
/// A snapshot of the queue.
@immutable
class RunUploadStatus {
/// Creates a status.
const RunUploadStatus(this.health, this.pending, [this.reason = '']);
/// What the queue is doing.
final UploadHealth health;
/// Runs still waiting.
final int pending;
/// A sentence for the log.
final String reason;
}
/// The pending-run upload queue.
class RunUploader {
/// Creates a queue; the arguments are test seams.
RunUploader({
RunCredentialStore? credentials,
this._client,
this._storage,
Timer Function(Duration, void Function())? scheduler,
}) : _credentials = credentials ?? RunCredentialStore(),
_schedule = scheduler ?? Timer.new;
/// The app-wide queue.
static final RunUploader instance = RunUploader();
final RunCredentialStore _credentials;
final http.Client? _client;
final StorageService? _storage;
final Timer Function(Duration, void Function()) _schedule;
final _status = ValueNotifier<RunUploadStatus>(
const RunUploadStatus(UploadHealth.idle, 0),
);
Future<RunUploadStatus>? _inFlight;
Timer? _retry;
/// The queue's state, for the badge.
ValueListenable<RunUploadStatus> get status => _status;
StorageService get _db => _storage ?? StorageService.instance;
/// Uploads every pending run, oldest first. One pass at a time: a call
/// while one runs joins it instead of racing it.
Future<RunUploadStatus> uploadPending() =>
_inFlight ??= _guarded().whenComplete(() => _inFlight = null);
/// A pass that cannot throw: callers fire it and forget it, and an error
/// nobody awaits would vanish. It is logged loudly and retried instead.
Future<RunUploadStatus> _guarded() async {
try {
return await _pass();
} on Exception catch (error, stack) {
log(
'RunUploader: the upload pass threw',
level: 1000,
error: error,
stackTrace: stack,
);
return _fail(
UploadHealth.retrying,
_status.value.pending,
'the upload pass crashed ($error); runs stay pending and are retried.',
);
}
}
Future<RunUploadStatus> _pass() async {
_retry?.cancel();
final pending = (await _db.listRuns(
uploadState: RunUploadState.pending,
)).reversed.toList();
if (pending.isEmpty) return _set(UploadHealth.idle, 0);
if (Sandbox.enabled) {
SandboxLog.event('upload skipped', {'pending': pending.length});
return _set(UploadHealth.sandbox, pending.length, 'sandbox: no uploads');
}
final login = await _credentials.read();
if (login == null) {
return _fail(
UploadHealth.notConfigured,
pending.length,
'${pending.length} run(s) wait for upload but no login is '
'provisioned. Run scripts/provision_run_upload.sh.',
retry: false,
);
}
_set(UploadHealth.uploading, pending.length);
var left = pending.length;
final client = _client ?? http.Client();
try {
for (final record in pending) {
final problem = await _upload(client, login, record);
if (problem != null) {
return _fail(UploadHealth.retrying, left, problem);
}
left--;
}
} finally {
if (_client == null) client.close();
}
return _set(UploadHealth.idle, 0);
}
/// A sentence naming the failure, or null once the run is uploaded.
Future<String?> _upload(
http.Client client,
DufsCredentials login,
RunRecord record,
) async {
final full = await _db.getRun(record.track.id);
if (full == null) return null;
final tcx = encodeTcx(full.track);
if (tcxSha256(tcx) != record.tcxSha256) {
log(
'RunUploader: ${record.tcxFilename} re-encodes to different bytes '
'than were stored (the encoder changed since recording). Uploading '
'the current encoding; the PC dedupes on the run id.',
level: 900,
);
}
final url = Uri.parse(
'${login.url}/$kRunInboxFolder/${record.tcxFilename}',
);
final http.Response response;
try {
response = await client
.put(
url,
headers: {
'Authorization': login.authorization,
'Content-Type': 'application/vnd.garmin.tcx+xml',
},
body: tcx,
)
.timeout(kUploadTimeout);
} on Exception catch (error, stack) {
log(
'RunUploader: PUT ${record.tcxFilename} threw',
level: 1000,
error: error,
stackTrace: stack,
);
return 'PUT ${record.tcxFilename} failed ($error); the run stays '
'pending and is retried.';
}
if (response.statusCode < 200 || response.statusCode > 299) {
return 'PUT ${record.tcxFilename} was answered ${response.statusCode}'
'${response.statusCode == 401 ? ' (login rejected: re-run '
'scripts/provision_run_upload.sh)' : ''}; the run stays '
'pending and is retried.';
}
if (!await _db.setRunUploadState(
record.track.id,
RunUploadState.uploaded,
)) {
log(
'RunUploader: ${record.tcxFilename} was uploaded but its row is '
'gone, so it could not be marked uploaded.',
level: 900,
);
}
return null;
}
RunUploadStatus _set(UploadHealth health, int pending, [String why = '']) {
final status = RunUploadStatus(health, pending, why);
_status.value = status;
return status;
}
RunUploadStatus _fail(
UploadHealth health,
int pending,
String reason, {
bool retry = true,
}) {
log('RunUploader: $reason', level: 1000);
if (retry) {
_retry = _schedule(kUploadRetryAfter, () => unawaited(uploadPending()));
}
return _set(health, pending, reason);
}
/// Stops the retry timer.
void dispose() {
_retry?.cancel();
_status.dispose();
}
}

View File

@ -0,0 +1,122 @@
/// The WebDAV half of the RunnerUp history import: list, fetch, marker PUT.
library;
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:workout_app/services/dufs_credentials.dart';
import 'package:xml/xml.dart';
/// Folder on the PC that holds the already-handled RunnerUp exports.
const String kRunnerUpProcessedPath = '/RunnerUp/processed/';
/// The ONE file the app ever writes to the PC for the import: the
/// import-complete marker.
///
/// A dotfile at the top of `/RunnerUp` is invisible to `runnerup_watch.sh`
/// (it skips names starting with '.') and to every `*.tcx` glob, so it can
/// never be credited as a workout. [putImportMarker] is the importer's only
/// PUT and its path is this constant, never built from a file name.
const String kImportMarkerPath = '/RunnerUp/.workout_app_import.json';
/// Per-request ceiling, so a half-open connection cannot hang the import.
const Duration kDavTimeout = Duration(seconds: 20);
/// A request the server did not answer with success.
class DavException implements Exception {
/// Creates the exception.
const DavException(this.what);
/// A sentence naming the request and why it failed.
final String what;
@override
String toString() => what;
}
/// The `.tcx` file names directly inside `/RunnerUp/processed/`.
///
/// One PROPFIND with `Depth: 1`. Throws [DavException] on a non-multistatus
/// answer (401 included) and an `XmlException` on unreadable XML.
Future<List<String>> listProcessedTcx(
http.Client client,
DufsCredentials login,
) async {
final request = http.Request(
'PROPFIND',
Uri.parse('${login.url}$kRunnerUpProcessedPath'),
)..headers.addAll({'Authorization': login.authorization, 'Depth': '1'});
final response = await _send(client, request);
if (response.statusCode != 207) {
throw DavException(
'PROPFIND $kRunnerUpProcessedPath answered ${response.statusCode}',
);
}
return tcxNamesFromMultistatus(utf8.decode(response.bodyBytes));
}
/// The `.tcx` basenames named by the `href`s of a multistatus [xml].
///
/// Hrefs may be absolute paths or full URLs and are percent-encoded; the
/// collection itself (a trailing slash) has no name and is skipped.
List<String> tcxNamesFromMultistatus(String xml) {
final names = <String>{};
for (final href in XmlDocument.parse(
xml,
).descendantElements.where((e) => e.localName == 'href')) {
final path = Uri.decodeFull(Uri.parse(href.innerText.trim()).path);
final name = path.substring(path.lastIndexOf('/') + 1);
if (name.toLowerCase().endsWith('.tcx') && !name.startsWith('.')) {
names.add(name);
}
}
return names.toList()..sort();
}
/// Downloads one export from `/RunnerUp/processed/` as raw bytes (the caller
/// decides what a non-UTF-8 file means).
Future<Uint8List> fetchProcessedTcx(
http.Client client,
DufsCredentials login,
String name,
) async {
final request = http.Request(
'GET',
Uri.parse(
'${login.url}$kRunnerUpProcessedPath${Uri.encodeComponent(name)}',
),
)..headers['Authorization'] = login.authorization;
final response = await _send(client, request);
if (response.statusCode != 200) {
throw DavException('GET $name answered ${response.statusCode}');
}
return response.bodyBytes;
}
/// PUTs [body] to [kImportMarkerPath]; throws [DavException] unless 2xx.
Future<void> putImportMarker(
http.Client client,
DufsCredentials login,
String body,
) async {
final request =
http.Request('PUT', Uri.parse('${login.url}$kImportMarkerPath'))
..headers.addAll({
'Authorization': login.authorization,
'Content-Type': 'application/json',
})
..body = body;
final response = await _send(client, request);
if (response.statusCode < 200 || response.statusCode > 299) {
throw DavException(
'PUT $kImportMarkerPath answered ${response.statusCode}',
);
}
}
Future<http.Response> _send(http.Client client, http.Request request) async {
final streamed = await client.send(request).timeout(kDavTimeout);
return await http.Response.fromStream(streamed);
}

View File

@ -0,0 +1,83 @@
/// What the RunnerUp import remembers and reports: prefs keys, the live
/// status the badge shows, and the per-pass tally.
library;
import 'package:flutter/foundation.dart';
/// Where RunnerUp itself leaves exports on the phone.
const String kRunnerUpLocalDir = '/sdcard/Documents/RunnerUp';
/// `shared_preferences` key: every remote export is in the database.
const String kImportDoneKey = 'runnerup_import_done';
/// `shared_preferences` key: the marker JSON, kept until the PC has it.
const String kImportMarkerKey = 'runnerup_import_marker';
/// What the badge shows.
enum RunnerUpImportStatus {
/// Not started, or not applicable here (sandbox, desktop).
idle,
/// Importing right now.
running,
/// Imported and the PC has been told.
done,
/// Something failed; the next app start retries.
failed,
}
/// The live status; the badge listens to it.
final ValueNotifier<RunnerUpImportStatus> runnerUpImportStatus = ValueNotifier(
RunnerUpImportStatus.idle,
);
/// What one [RunnerUpImporter.runIfNeeded] pass did.
typedef RunnerUpImportReport = ({
int imported,
int duplicates,
int skipped,
List<String> failures,
});
/// The report of a pass that did nothing.
const RunnerUpImportReport kNothingImported = (
imported: 0,
duplicates: 0,
skipped: 0,
failures: [],
);
/// The report of a pass that did nothing but fail for [reason].
RunnerUpImportReport failedReport(String reason) =>
(imported: 0, duplicates: 0, skipped: 0, failures: [reason]);
/// Counts one import pass and logs each failure as it happens.
class ImportTally {
/// Runs stored this pass.
int imported = 0;
/// Exports already stored (same hash or id).
int duplicates = 0;
/// Files that are no usable run, skipped for good.
int skipped = 0;
/// Why the pass is incomplete; empty means it can finish.
final List<String> failures = [];
/// Records [reason] and logs it as a warning.
void fail(String reason) {
failures.add(reason);
debugPrint('WorkoutApp: RunnerUp import WARNING: $reason');
}
/// The tally as a report.
RunnerUpImportReport get report => (
imported: imported,
duplicates: duplicates,
skipped: skipped,
failures: failures,
);
}

View File

@ -0,0 +1,250 @@
/// One-time import of the RunnerUp history into the app's `runs` table.
///
/// Imported runs are display-only: [RunSource.runnerupImport] with
/// [RunUploadState.never]. Nothing here ever PUTs a `.tcx` anywhere; the only
/// write to the PC is the dotfile marker (see [kImportMarkerPath]) that tells
/// the PC the import finished.
library;
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/dufs_credentials.dart';
import 'package:workout_app/services/runnerup_dav.dart';
import 'package:workout_app/services/runnerup_import_state.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/tcx_codec.dart';
export 'package:workout_app/services/runnerup_import_state.dart';
/// Imports the RunnerUp history once, on app start.
class RunnerUpImporter {
/// Creates an importer; every collaborator can be replaced in tests.
RunnerUpImporter({
http.Client? client,
Future<DufsCredentials?> Function()? loadLogin,
Future<bool> Function()? canReadStorage,
this.localDir = kRunnerUpLocalDir,
bool? isAndroid,
DateTime Function()? now,
}) : _client = client ?? http.Client(),
_loadLogin = loadLogin ?? DufsCredentials.load,
_canReadStorage =
canReadStorage ?? BackupService.instance.hasStoragePermission,
_isAndroid = isAndroid ?? Platform.isAndroid,
_now = now ?? DateTime.now;
final http.Client _client;
final Future<DufsCredentials?> Function() _loadLogin;
final Future<bool> Function() _canReadStorage;
final bool _isAndroid;
final DateTime Function() _now;
/// Where RunnerUp's own exports are looked for (when storage is readable).
final String localDir;
/// Runs the import unless it already completed, this is the sandbox, or
/// this is not the phone (a desktop run would write the marker before the
/// phone ever imported).
Future<RunnerUpImportReport> runIfNeeded() async {
if (Sandbox.enabled) {
SandboxLog.event('runnerup import skipped: sandbox never imports');
return kNothingImported;
}
if (!_isAndroid) {
debugPrint('WorkoutApp: RunnerUp import skipped: not the phone.');
return kNothingImported;
}
final prefs = await SharedPreferences.getInstance();
if (prefs.getBool(kImportDoneKey) ?? false) {
final marker = prefs.getString(kImportMarkerKey);
if (marker == null) {
runnerUpImportStatus.value = RunnerUpImportStatus.done;
return kNothingImported;
}
return (
imported: 0,
duplicates: 0,
skipped: 0,
failures: await _deliver(prefs, marker),
);
}
runnerUpImportStatus.value = RunnerUpImportStatus.running;
final report = await _importAll(prefs);
runnerUpImportStatus.value = report.failures.isEmpty
? RunnerUpImportStatus.done
: RunnerUpImportStatus.failed;
return report;
}
/// [runIfNeeded] that cannot leave the badge spinning: anything thrown
/// outside the per-file handling (a platform error, a prefs write) becomes
/// a logged failure and the `failed` state, retried next start.
Future<RunnerUpImportReport> runGuarded() async {
try {
return await runIfNeeded();
} on Object catch (error) {
debugPrint('WorkoutApp: RunnerUp import WARNING: aborted: $error');
runnerUpImportStatus.value = RunnerUpImportStatus.failed;
return failedReport('aborted: $error');
}
}
Future<RunnerUpImportReport> _importAll(SharedPreferences prefs) async {
final tally = ImportTally();
final login = await _loadLogin();
final names = <String>[];
if (login == null) {
tally.fail('no dufs login in secure storage, so nothing was fetched');
} else {
names.addAll(await _importRemote(login, tally));
}
await _importLocal(tally);
if (tally.failures.isEmpty && login != null) {
final marker = jsonEncode({
'completed_at': _now().toUtc().toIso8601String(),
'count': names.length,
'tcx_names': names,
});
await prefs.setString(kImportMarkerKey, marker);
await prefs.setBool(kImportDoneKey, true);
tally.failures.addAll(await _deliver(prefs, marker));
}
return tally.report;
}
/// Fetches and stores every remote export; returns the names now accounted
/// for (stored, or already stored). A file that is not a usable run is
/// skipped for good and left out; a network failure is a failure.
Future<List<String>> _importRemote(
DufsCredentials login,
ImportTally tally,
) async {
final List<String> remote;
try {
remote = await listProcessedTcx(_client, login);
} on Exception catch (error) {
debugPrint('WorkoutApp: RunnerUp import WARNING: listing failed: $error');
tally.failures.add('listing the PC history failed: $error');
return const [];
}
final accounted = <String>[];
final seen = <String>{};
for (final name in remote) {
try {
final bytes = await fetchProcessedTcx(_client, login, name);
final source = await _ingest(name, bytes, tally);
// The marker lists each distinct RunnerUp run once (the phone's
// `Pixel_6a_` twin of a file is the same run) and never an
// app-authored file.
if (source == RunSource.runnerupImport &&
seen.add(name.replaceFirst('Pixel_6a_', ''))) {
accounted.add(name);
}
} on Exception catch (error) {
debugPrint('WorkoutApp: RunnerUp import WARNING: $name: $error');
tally.failures.add('$name: $error');
}
await Future<void>.delayed(Duration.zero);
}
return accounted;
}
/// Best effort: only if storage is already readable, and never a failure.
Future<void> _importLocal(ImportTally tally) async {
if (!await _canReadStorage()) {
debugPrint(
'WorkoutApp: RunnerUp import: storage not readable, skipping '
'$localDir (the PC copy is the source).',
);
return;
}
try {
final dir = Directory(localDir);
if (!dir.existsSync()) return;
for (final file in dir.listSync().whereType<File>().where(
(f) => f.path.toLowerCase().endsWith('.tcx'),
)) {
final name = file.path.substring(file.path.lastIndexOf('/') + 1);
await _ingest(name, await file.readAsBytes(), tally);
}
} on Exception catch (error) {
debugPrint(
'WorkoutApp: RunnerUp import WARNING: reading $localDir failed '
'($error); the PC copy still completes the import.',
);
}
}
/// Stores one export; returns what its file says made it (before it is
/// forced to history), or null when it is not a usable run.
Future<RunSource?> _ingest(
String name,
Uint8List bytes,
ImportTally tally,
) async {
final String xml;
final RunTrack decoded;
try {
xml = utf8.decode(bytes);
decoded = decodeTcx(xml, fileName: name);
} on FormatException catch (error) {
tally.skipped++;
debugPrint(
'WorkoutApp: RunnerUp import WARNING: $name is not a usable run '
'($error); skipped for good.',
);
return null;
}
// Forced, whatever the file says: an app-made TCX that came back through
// processed/ must not be re-uploaded, so it is history, never pending.
final track = RunTrack(
id: decoded.id,
sport: decoded.sport,
startedAt: decoded.startedAt,
points: decoded.points,
totalSeconds: decoded.totalSeconds,
distanceM: decoded.distanceM,
source: RunSource.runnerupImport,
);
final added = await StorageService.instance.insertRun(
track,
tcxFilename: name,
tcxSha256: tcxSha256(xml),
uploadState: RunUploadState.never,
);
added ? tally.imported++ : tally.duplicates++;
return decoded.source;
}
/// PUTs the marker; returns the failures (empty once the PC has it).
Future<List<String>> _deliver(SharedPreferences prefs, String marker) async {
final login = await _loadLogin();
String? failure;
if (login == null) {
failure = 'no dufs login in secure storage, so the PC was not told';
} else {
try {
await putImportMarker(_client, login, marker);
} on Exception catch (error) {
failure = 'telling the PC failed: $error';
}
}
if (failure != null) {
debugPrint('WorkoutApp: RunnerUp import WARNING: $failure');
runnerUpImportStatus.value = RunnerUpImportStatus.failed;
return [failure];
}
await prefs.remove(kImportMarkerKey);
runnerUpImportStatus.value = RunnerUpImportStatus.done;
return const [];
}
}

View File

@ -14,6 +14,8 @@ import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/manual_deload.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/manual_workout_port.dart';
@ -31,6 +33,8 @@ part 'storage_service_exercises.dart';
part 'storage_service_export.dart';
part 'storage_service_import.dart';
part 'storage_service_pc_link.dart';
part 'storage_service_runs.dart';
part 'storage_service_runs_transfer.dart';
part 'storage_service_sandbox.dart';
part 'storage_service_schema.dart';
part 'storage_service_sessions.dart';
@ -94,7 +98,7 @@ class StorageService {
// coverage:ignore-end
_db = await openDatabase(
dbPath,
version: 8,
version: 9,
onCreate: _createSchema,
onUpgrade: _migrateSchema,
// In tests resetForTesting() reopens a ':memory:' DB per test; sqflite's

View File

@ -22,16 +22,23 @@ extension StorageServiceBackup on StorageService {
final historyRows = await _db.query('workout_history');
final settingsRows = await _db.query('settings');
final eventRows = await _db.query('progression_events');
final runRows = await _runsForTransfer(appOnly: true);
if (historyRows.isEmpty) {
final existing = await BackupService.instance.readBackup();
final existingHistory =
(existing?['workout_history'] as List?) ?? const [];
if (existingHistory.isNotEmpty) {
final existingRuns = (existing?['runs'] as List?) ?? const [];
// A recorded run must not lift the history guard (a seeded DB that
// then records a run would erase months of sessions); only a DB with
// neither is also barred from erasing a runs-only backup.
if (existingHistory.isNotEmpty ||
(runRows.isEmpty && existingRuns.isNotEmpty)) {
debugPrint(
'WorkoutApp: REFUSING to overwrite the backup — this DB has no '
'workout history but the backup holds ${existingHistory.length} '
'session(s). A restore almost certainly failed; keeping the backup '
'workout history or runs but the backup holds '
'${existingHistory.length} session(s) and ${existingRuns.length} '
'run(s). A restore almost certainly failed; keeping the backup '
'so the data stays recoverable.',
);
return;
@ -43,6 +50,7 @@ extension StorageServiceBackup on StorageService {
'workout_history': historyRows,
'settings': settingsRows,
'progression_events': eventRows,
'runs': runRows,
});
}
@ -173,6 +181,8 @@ extension StorageServiceBackup on StorageService {
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// Absent from older backups; null merges as nothing.
await _mergeRuns(txn, backup['runs']);
});
}
}

View File

@ -7,8 +7,9 @@ part of 'storage_service.dart';
const kExportFormat = 'workout_app-export';
/// The format written now. Version 2 adds `updated_at` to `exercise_state` and
/// `settings` rows plus `manual_workouts`; version 1 files still import.
const kExportVersion = 2;
/// `settings` rows plus `manual_workouts`; version 3 adds `runs` (with their
/// points); version 1 and 2 files still import.
const kExportVersion = 3;
const _exportTables = [
'workout_history',
@ -47,6 +48,7 @@ extension StorageServiceExport on StorageService {
for (final row in settings)
if (!_isPerInstallSetting(row['key']! as String)) row,
],
'runs': await _runsForTransfer(appOnly: false),
'manual_workouts': manual == null
? null
: [

View File

@ -24,7 +24,7 @@ extension StorageServiceImport on StorageService {
/// [ImportReport.manualSkipped] says so. Idempotent.
Future<ImportReport> importDataReport(Map<String, dynamic> data) async {
if (!_exportTables.any((t) => data[t] is List)) {
if (data['manual_workouts'] is! List) {
if (data['manual_workouts'] is! List && data['runs'] is! List) {
throw const FormatException('not a workout_app export');
}
}
@ -36,6 +36,7 @@ extension StorageServiceImport on StorageService {
for (final table in _exportTables) {
rows += await _mergeTable(txn, table, data[table], fileWins, stamped);
}
rows += await _mergeRuns(txn, data['runs']);
});
if (rows > 0) unawaited(_backupNow());
final manual = await _importManual(data['manual_workouts']);

View File

@ -0,0 +1,188 @@
// Recorded and imported runs: the v9 `runs` / `run_points` tables.
//
// A `part` of StorageService for the same reason as the other parts: it needs
// `_db`, and runs must not grow a second storage layer next to the schema.
part of 'storage_service.dart';
/// The v9 tables, shared by create and migrate.
///
/// `tcx_sha256` is UNIQUE so the same export can never be stored twice (an
/// import re-run, or a recorded run that also came back from the PC). The
/// CHECK keeps the one rule that must hold even if app code is wrong: an
/// imported run is never uploaded.
const _runsTables = [
'''
CREATE TABLE IF NOT EXISTS runs (
id TEXT PRIMARY KEY,
sport TEXT NOT NULL,
started_at INTEGER NOT NULL,
total_seconds INTEGER NOT NULL,
distance_m REAL NOT NULL,
source TEXT NOT NULL CHECK (source IN ('app', 'runnerup_import')),
upload_state TEXT NOT NULL
CHECK (upload_state IN ('pending', 'uploaded', 'never')),
tcx_filename TEXT NOT NULL,
tcx_sha256 TEXT NOT NULL UNIQUE,
CHECK (source <> 'runnerup_import' OR upload_state = 'never')
)
''',
'''
CREATE TABLE IF NOT EXISTS run_points (
run_id TEXT NOT NULL,
seq INTEGER NOT NULL,
time_ms INTEGER NOT NULL,
lat REAL NOT NULL,
lon REAL NOT NULL,
alt REAL,
distance_m REAL NOT NULL,
PRIMARY KEY (run_id, seq)
) WITHOUT ROWID
''',
];
/// Run persistence.
extension StorageServiceRuns on StorageService {
/// Stores [track]; returns false (storing nothing) when a run with the same
/// [tcxSha256] or id is already there.
///
/// Throws [ArgumentError] for an imported run that is not
/// [RunUploadState.never].
Future<bool> insertRun(
RunTrack track, {
required String tcxFilename,
required String tcxSha256,
required RunUploadState uploadState,
}) async {
if (track.source == RunSource.runnerupImport &&
uploadState != RunUploadState.never) {
throw ArgumentError.value(
uploadState,
'uploadState',
'an imported run must be RunUploadState.never',
);
}
final added = await _db.transaction((txn) async {
final clash = await txn.query(
'runs',
columns: ['id'],
where: 'id = ? OR tcx_sha256 = ?',
whereArgs: [track.id, tcxSha256],
);
if (clash.isNotEmpty) return false;
await txn.insert('runs', {
'id': track.id,
'sport': track.sport.tcxName,
'started_at': track.startedAt.millisecondsSinceEpoch,
'total_seconds': track.totalSeconds,
'distance_m': track.distanceM,
'source': track.source.storageKey,
'upload_state': uploadState.storageKey,
'tcx_filename': tcxFilename,
'tcx_sha256': tcxSha256,
});
final batch = txn.batch();
for (final (seq, p) in track.points.indexed) {
batch.insert('run_points', {
'run_id': track.id,
'seq': seq,
'time_ms': p.time.millisecondsSinceEpoch,
'lat': p.latitude,
'lon': p.longitude,
'alt': p.altitudeM,
'distance_m': p.distanceM,
});
}
await batch.commit(noResult: true);
return true;
});
// A recorded run exists nowhere else yet; the RunnerUp history does (PC).
if (added && track.source == RunSource.app) unawaited(_backupNow());
return added;
}
/// Whether a run with this TCX hash is stored.
Future<bool> runExistsBySha(String tcxSha256) async => (await _db.query(
'runs',
columns: ['id'],
where: 'tcx_sha256 = ?',
whereArgs: [tcxSha256],
)).isNotEmpty;
/// Every run, newest first, without points.
Future<List<RunRecord>> listRuns({RunUploadState? uploadState}) async {
final rows = await _db.query(
'runs',
where: uploadState == null ? null : 'upload_state = ?',
whereArgs: uploadState == null ? null : [uploadState.storageKey],
orderBy: 'started_at DESC',
);
return rows.map((r) => _runFromRow(r, const [])).toList();
}
/// The run [id] with its points, or null.
Future<RunRecord?> getRun(String id) async {
final rows = await _db.query('runs', where: 'id = ?', whereArgs: [id]);
if (rows.isEmpty) return null;
final pointRows = await _db.query(
'run_points',
where: 'run_id = ?',
whereArgs: [id],
orderBy: 'seq',
);
final points = pointRows
.map(
(r) => RunPoint(
time: DateTime.fromMillisecondsSinceEpoch(
r['time_ms']! as int,
isUtc: true,
),
latitude: r['lat']! as double,
longitude: r['lon']! as double,
altitudeM: r['alt'] as double?,
distanceM: r['distance_m']! as double,
),
)
.toList();
return _runFromRow(rows.first, points);
}
/// Moves run [id] to [state]; false when it does not exist.
///
/// An imported run cannot leave [RunUploadState.never] (the table's CHECK
/// rejects it).
Future<bool> setRunUploadState(String id, RunUploadState state) async =>
await _db.update(
'runs',
{'upload_state': state.storageKey},
where: 'id = ?',
whereArgs: [id],
) >
0;
/// Deletes run [id] and its points; false when it does not exist.
Future<bool> deleteRun(String id) async => await _db.transaction((txn) async {
await txn.delete('run_points', where: 'run_id = ?', whereArgs: [id]);
return await txn.delete('runs', where: 'id = ?', whereArgs: [id]) > 0;
});
RunRecord _runFromRow(Map<String, Object?> r, List<RunPoint> points) =>
RunRecord(
track: RunTrack(
id: r['id']! as String,
sport: RunSport.fromTcxName(r['sport']! as String)!,
startedAt: DateTime.fromMillisecondsSinceEpoch(
r['started_at']! as int,
isUtc: true,
),
points: points,
totalSeconds: r['total_seconds']! as int,
distanceM: r['distance_m']! as double,
source: RunSource.fromStorageKey(r['source']! as String),
),
uploadState: RunUploadState.fromStorageKey(
r['upload_state']! as String,
),
tcxFilename: r['tcx_filename']! as String,
tcxSha256: r['tcx_sha256']! as String,
);
}

View File

@ -0,0 +1,137 @@
// Runs in backup.json and the user export: the `runs` / `run_points` half of
// both, written and merged by one code path.
//
// A `part` of StorageService (it needs `_db`). The generic table merge cannot
// be reused: it strips every `id` column and falls back to a progression
// event key, which would store runs with NULL ids.
part of 'storage_service.dart';
/// Runs as portable rows.
extension StorageServiceRunsTransfer on StorageService {
/// Every run as a `runs` row plus `points`: ONE compact JSON string of
/// `[time_ms, lat, lon, alt, distance_m]` rows. A string, not nested lists,
/// so pretty-printing the document does not put every fix on its own line
/// (a year of runs would otherwise be tens of MB, re-encoded on every
/// backup).
///
/// [appOnly] leaves the RunnerUp history out: it is reproducible from the
/// PC, so the automatic backup carries only what exists nowhere else.
Future<List<Map<String, Object?>>> _runsForTransfer({
required bool appOnly,
}) async {
final rows = await _db.query(
'runs',
where: appOnly ? "source = 'app'" : null,
orderBy: 'started_at, id',
);
return [
for (final row in rows)
{...row, 'points': await _encodePoints(row['id']! as String)},
];
}
Future<String> _encodePoints(String runId) async {
final points = await _db.query(
'run_points',
where: 'run_id = ?',
whereArgs: [runId],
orderBy: 'seq',
);
return jsonEncode([
for (final p in points)
[p['time_ms'], p['lat'], p['lon'], p['alt'], p['distance_m']],
]);
}
/// Merges transferred [raw] runs into the database and returns how many
/// were new. Idempotent: a run whose id OR TCX hash is already stored is
/// left alone (and so are its points); a malformed entry is counted and
/// skipped, never fatal. An imported run is stored as `never` whatever the
/// file claims, since the table's CHECK would reject anything else.
Future<int> _mergeRuns(Transaction txn, Object? raw) async {
if (raw is! List) {
if (raw != null) _warnSkipped('runs', 1);
return 0;
}
final known = await txn.query('runs', columns: ['id', 'tcx_sha256']);
final ids = {for (final r in known) r['id']! as String};
final shas = {for (final r in known) r['tcx_sha256']! as String};
var written = 0;
var malformed = 0;
for (final entry in raw) {
final parsed = entry is Map<String, dynamic> ? _parseRun(entry) : null;
if (parsed == null) {
malformed++;
continue;
}
final (row, points) = parsed;
final id = row['id']! as String;
final sha = row['tcx_sha256']! as String;
if (ids.contains(id) || shas.contains(sha)) continue;
ids.add(id);
shas.add(sha);
await txn.insert('runs', row);
final batch = txn.batch();
for (final (seq, p) in points.indexed) {
batch.insert('run_points', {
'run_id': row['id'],
'seq': seq,
'time_ms': p[0],
'lat': p[1],
'lon': p[2],
'alt': p[3],
'distance_m': p[4],
});
}
await batch.commit(noResult: true);
written++;
}
if (malformed > 0) _warnSkipped('runs', malformed);
return written;
}
/// The `runs` row and decoded points of [e], or null when it is malformed.
(Map<String, Object?>, List<List<Object?>>)? _parseRun(
Map<String, dynamic> e,
) {
try {
final source = RunSource.fromStorageKey(e['source'] as String);
final state = source == RunSource.runnerupImport
? RunUploadState.never
: RunUploadState.fromStorageKey(e['upload_state'] as String);
final points = [
for (final p in jsonDecode(e['points'] as String) as List<dynamic>)
[
(p as List<dynamic>)[0] as int,
(p[1] as num).toDouble(),
(p[2] as num).toDouble(),
(p[3] as num?)?.toDouble(),
(p[4] as num).toDouble(),
],
];
final sport = RunSport.fromTcxName(e['sport'] as String)!.tcxName;
final id = e['id'] as String;
final sha = e['tcx_sha256'] as String;
if (id.isEmpty || sha.isEmpty) return null;
return (
{
'id': id,
'sport': sport,
'started_at': e['started_at'] as int,
'total_seconds': e['total_seconds'] as int,
'distance_m': (e['distance_m'] as num).toDouble(),
'source': source.storageKey,
'upload_state': state.storageKey,
'tcx_filename': e['tcx_filename'] as String,
'tcx_sha256': sha,
},
points,
);
} on Object catch (error) {
// Wrong shape, unknown enum key, or a points string that is not JSON;
// the caller also logs the total via _warnSkipped.
debugPrint('WorkoutApp: malformed run entry skipped: $error');
return null;
}
}
}

View File

@ -8,6 +8,9 @@ part of 'storage_service.dart';
/// Settings key the sandbox's rest length is stored under.
const String kSandboxRestSecsKey = 'sandbox_rest_secs';
/// Settings key the sandbox's GPS replay speed-up is stored under.
const String kSandboxReplayFactorKey = 'sandbox_run_replay_x';
/// Sandbox-only maintenance on the (sandbox's own) database.
///
/// Nothing here checks `Sandbox.enabled`: the Settings screen only offers
@ -19,6 +22,8 @@ extension StorageServiceSandbox on StorageService {
Future<void> wipeAll() async {
for (final table in const [
'workout_history',
'run_points',
'runs',
'progression_events',
'active_session',
'settings',
@ -52,4 +57,14 @@ extension StorageServiceSandbox on StorageService {
/// Persists the rest override used by every sandbox break.
Future<void> setSandboxRestSecs(int secs) =>
_setSetting(kSandboxRestSecsKey, '$secs');
/// The saved GPS replay speed-up, or [fallback] when none has been saved.
Future<int> getSandboxReplayFactor(int fallback) async {
final raw = await _getSetting(kSandboxReplayFactorKey);
return raw == null ? fallback : int.parse(raw);
}
/// Persists the speed-up the sandbox replays its GPS run at.
Future<void> setSandboxReplayFactor(int factor) =>
_setSetting(kSandboxReplayFactorKey, '$factor');
}

View File

@ -83,6 +83,9 @@ extension StorageServiceSchema on StorageService {
)
''');
await db.execute(_progressionEventsTable);
for (final ddl in _runsTables) {
await db.execute(ddl);
}
}
Future<void> _migrateSchema(
@ -146,6 +149,12 @@ extension StorageServiceSchema on StorageService {
await db.execute('ALTER TABLE $table ADD COLUMN $_updatedAtColumn');
}
}
if (oldVersion < 9) {
// New tables, nothing to backfill: runs before v9 were RunnerUp's.
for (final ddl in _runsTables) {
await db.execute(ddl);
}
}
}
Future<void> _seedDefaultsIfNeeded() async {

View File

@ -0,0 +1,243 @@
/// Reads and writes the TCX files the PC's RunnerUp verifier credits.
///
/// The contract is the PC's parser (`screen_locker/_runnerup_tcx.py`,
/// `_walk_tcx.py`), pinned by a shared golden fixture on both sides:
///
/// * File name `RunnerUp_YYYY-MM-DD-HH-MM-SS_<Sport>.tcx`, stamp in LOCAL
/// time (the PC globs today's local date in the name), suffix `Running` or
/// `Walking` (a walk is recognised by that suffix or `Sport="Walking"`; the
/// encoder writes `Sport="Other"` for it, as RunnerUp does).
/// * `<Id>` and every `<Time>` are UTC with a `Z`; one Lap whose
/// `TotalTimeSeconds` is moving time and `DistanceMeters` the credited
/// distance; every Trackpoint carries `Time` and a cumulative
/// `DistanceMeters` (the PC derives a walk's speed from those).
/// * The source tag is `Author/Name` and `Creator/Name`
/// ([kRunSourceName]); the PC ignores both.
library;
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:xml/xml.dart';
/// Written into `Author/Name` and `Creator/Name`; marks an app-made file.
const String kRunSourceName = 'kuhy workout_app';
const String _ns = 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2';
const String _xsi = 'http://www.w3.org/2001/XMLSchema-instance';
String _utcStamp(DateTime t) => RunTrack.idFor(t);
String _num(double v, int digits) => v.toStringAsFixed(digits);
/// Encodes [track] as a TCX document the PC accepts unchanged.
String encodeTcx(RunTrack track) {
final b = XmlBuilder()..processing('xml', 'version="1.0" encoding="UTF-8"');
b.element(
'TrainingCenterDatabase',
attributes: {
'xmlns': _ns,
'xmlns:xsi': _xsi,
'xsi:schemaLocation':
'$_ns http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd',
},
nest: () {
b
..element('Activities', nest: () => _activity(b, track))
..element(
'Author',
attributes: {'xsi:type': 'Application_t'},
nest: () {
b
..element('Name', nest: kRunSourceName)
..element('Build', nest: () => _version(b))
..element('LangID', nest: 'en')
..element('PartNumber', nest: '000-00000-00');
},
);
},
);
return b.buildDocument().toXmlString(pretty: true, indent: ' ');
}
void _activity(XmlBuilder b, RunTrack track) => b.element(
'Activity',
attributes: {'Sport': track.sport.tcxSport},
nest: () {
b.element('Id', nest: track.id);
_lap(b, track);
b.element(
'Creator',
attributes: {'xsi:type': 'Device_t'},
nest: () {
b
..element('Name', nest: kRunSourceName)
..element('UnitId', nest: '0')
..element('ProductID', nest: '0');
_version(b);
},
);
},
);
void _version(XmlBuilder b) => b.element(
'Version',
nest: () {
b
..element('VersionMajor', nest: '1')
..element('VersionMinor', nest: '0');
},
);
void _lap(XmlBuilder b, RunTrack track) => b.element(
'Lap',
attributes: {'StartTime': _utcStamp(track.startedAt)},
nest: () {
b
..element('TotalTimeSeconds', nest: '${track.totalSeconds}')
..element('DistanceMeters', nest: _num(track.distanceM, 3))
// Required by the TCX schema, as in RunnerUp's own files.
..element('Calories', nest: '0')
..element('Intensity', nest: 'Active')
..element('TriggerMethod', nest: 'Manual')
..element('Track', nest: () => track.points.forEach(_point(b)));
},
);
void Function(RunPoint) _point(XmlBuilder b) =>
(p) => b.element(
'Trackpoint',
nest: () {
b
..element('Time', nest: _utcStamp(p.time))
..element(
'Position',
nest: () {
b
..element('LatitudeDegrees', nest: _num(p.latitude, 7))
..element('LongitudeDegrees', nest: _num(p.longitude, 7));
},
);
if (p.altitudeM != null) {
b.element('AltitudeMeters', nest: _num(p.altitudeM!, 1));
}
b.element('DistanceMeters', nest: _num(p.distanceM, 3));
},
);
/// The export file name for [track]: `RunnerUp_<local stamp>_<Sport>.tcx`.
///
/// The stamp is local time. [utcOffset] overrides the device zone (tests,
/// and any caller that knows the zone the run happened in).
String tcxFilename(RunTrack track, {Duration? utcOffset}) {
final local = utcOffset == null
? track.startedAt.toLocal()
: track.startedAt.add(utcOffset);
String two(int v) => v.toString().padLeft(2, '0');
final stamp =
'${local.year.toString().padLeft(4, '0')}-${two(local.month)}-'
'${two(local.day)}-${two(local.hour)}-${two(local.minute)}-'
'${two(local.second)}';
return 'RunnerUp_${stamp}_${track.sport.tcxName}.tcx';
}
/// Hex SHA-256 of the TCX text: the dedupe key of the `runs` table.
String tcxSha256(String tcx) => sha256.convert(utf8.encode(tcx)).toString();
/// Decodes a RunnerUp or app-made TCX.
///
/// [fileName] is the ORIGINAL export name: RunnerUp writes `Sport="Other"`
/// for a walk and only the `_Walking.tcx` suffix says so. Throws
/// [FormatException] for malformed XML, a missing Activity, or a sport the
/// app does not record (cycling and the rest).
///
/// Trackpoints without a `Position` are skipped: the map and the
/// distance maths need coordinates. Laps are summed, as the PC sums them.
RunTrack decodeTcx(String tcx, {String? fileName}) {
final XmlDocument doc;
try {
doc = XmlDocument.parse(tcx);
} on XmlException catch (e) {
throw FormatException('TCX is not valid XML: ${e.message}');
}
final activity = doc.descendantElements
.where((e) => e.localName == 'Activity')
.firstOrNull;
if (activity == null) throw const FormatException('TCX has no Activity');
final sport = _sportOf(activity.getAttribute('Sport'), fileName);
var seconds = 0.0;
var metres = 0.0;
DateTime? lapStart;
for (final lap in activity.childElements.where((e) => e.localName == 'Lap')) {
seconds += double.tryParse(_text(lap, 'TotalTimeSeconds') ?? '') ?? 0;
metres += double.tryParse(_text(lap, 'DistanceMeters') ?? '') ?? 0;
lapStart ??= DateTime.tryParse(lap.getAttribute('StartTime') ?? '');
}
final points = _points(activity);
final startedAt =
DateTime.tryParse(_text(activity, 'Id') ?? '') ??
lapStart ??
(points.isEmpty ? null : points.first.time);
if (startedAt == null) throw const FormatException('TCX has no start time');
return RunTrack(
id: _text(activity, 'Id') ?? RunTrack.idFor(startedAt),
sport: sport,
startedAt: startedAt,
points: points,
totalSeconds: seconds.round(),
distanceM: metres,
source: _isOurs(doc) ? RunSource.app : RunSource.runnerupImport,
);
}
RunSport _sportOf(String? attribute, String? fileName) {
for (final sport in RunSport.values) {
if (fileName != null && fileName.endsWith('_${sport.tcxName}.tcx')) {
return sport;
}
}
return RunSport.fromTcxName(attribute) ??
(throw FormatException('Unsupported TCX sport "$attribute"'));
}
bool _isOurs(XmlDocument doc) => doc.descendantElements.any(
(e) =>
(e.localName == 'Author' || e.localName == 'Creator') &&
_text(e, 'Name') == kRunSourceName,
);
String? _text(XmlElement parent, String name) => parent.childElements
.where((e) => e.localName == name)
.firstOrNull
?.innerText
.trim();
List<RunPoint> _points(XmlElement activity) {
final points = <RunPoint>[];
for (final tp in activity.descendantElements.where(
(e) => e.localName == 'Trackpoint',
)) {
final time = DateTime.tryParse(_text(tp, 'Time') ?? '');
final position = tp.childElements
.where((e) => e.localName == 'Position')
.firstOrNull;
final lat = double.tryParse(
position == null ? '' : _text(position, 'LatitudeDegrees') ?? '',
);
final lon = double.tryParse(
position == null ? '' : _text(position, 'LongitudeDegrees') ?? '',
);
if (time == null || lat == null || lon == null) continue;
points.add(
RunPoint(
time: time,
latitude: lat,
longitude: lon,
altitudeM: double.tryParse(_text(tp, 'AltitudeMeters') ?? ''),
distanceM: double.tryParse(_text(tp, 'DistanceMeters') ?? '') ?? 0,
),
);
}
return points..sort((a, b) => a.time.compareTo(b.time));
}

View File

@ -0,0 +1,203 @@
/// The map of a run: route polyline, start/end markers, live position.
///
/// Two constructors, both drop-ins (no other required argument):
///
/// * `RunMap.route(points: track.points)` -- a finished run. The camera
/// fits the whole route ([fitPadding] keeps it clear of overlays).
/// * `RunMap.live(pointsListenable: recorder.livePoints)` -- the live
/// screen. Pass a `ValueListenable<List<RunPoint>>` (the recorder's
/// accepted points, oldest first); the route
/// redraws on every change and, in follow mode (the default), the camera
/// keeps the last point centred. Dragging the map ends follow mode; the
/// recentre button (icon only) turns it back on. The listenable must stay
/// the same object for the widget's lifetime (give it a new `Key` to swap).
///
/// Tiles are OSM raster tiles from tile.openstreetmap.org, cached on disk
/// (`map_tile_cache.dart`) so revisited areas draw offline. The OSM credit is
/// a collapsed info icon; its text shows only when tapped. When no tile
/// loads (offline, first visit) the route still draws on the plain
/// background and ONE warning-level line is logged per map.
///
/// Tests inject `tileProviderOpener` with a fake provider: nothing here
/// touches the network by itself.
library;
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/map_tile_cache.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map_layers.dart';
/// Where an empty map starts: Poland, zoomed out, until a first fix.
const _fallbackCenter = LatLng(52, 19);
const _fallbackZoom = 5.0;
/// The zoom a one-point track or a first live fix gets.
const _closeZoom = 17.0;
/// A map of a run; see the library comment for the two constructors.
class RunMap extends StatefulWidget {
/// A finished run: [points] drawn and fitted.
const RunMap.route({
required List<RunPoint> this.points,
super.key,
this.fitPadding = const EdgeInsets.all(40),
this.tileProviderOpener = openOsmTileProvider,
}) : pointsListenable = null;
/// A live run: follows the last point in [pointsListenable].
const RunMap.live({
required ValueListenable<List<RunPoint>> this.pointsListenable,
super.key,
this.tileProviderOpener = openOsmTileProvider,
}) : points = null,
fitPadding = const EdgeInsets.all(40);
/// The route in detail mode; null in live mode.
final List<RunPoint>? points;
/// The accepted points in live mode; null in detail mode.
final ValueListenable<List<RunPoint>>? pointsListenable;
/// Space kept free around the fitted route (detail mode).
final EdgeInsets fitPadding;
/// Where the tile provider comes from; tests pass a fake.
final TileProviderOpener tileProviderOpener;
@override
State<RunMap> createState() => _RunMapState();
}
class _RunMapState extends State<RunMap> {
final _controller = MapController();
TileProvider? _tiles;
bool _ready = false;
bool _follow = true;
bool _warned = false;
bool get _live => widget.pointsListenable != null;
List<RunPoint> get _points => _live
? widget.pointsListenable!.value
: widget.points!;
@override
void initState() {
super.initState();
widget.pointsListenable?.addListener(_followLast);
unawaited(
widget.tileProviderOpener().then((p) {
if (mounted) setState(() => _tiles = p);
}),
);
}
@override
void dispose() {
widget.pointsListenable?.removeListener(_followLast);
_controller.dispose();
super.dispose();
}
void _followLast() {
final coords = toLatLngs(_points);
if (!_ready || !_follow || coords.isEmpty) return;
final zoom = _controller.camera.zoom;
_controller.move(coords.last, zoom < 12 ? _closeZoom : zoom);
}
void _warnOnce(Object error) {
if (_warned) return;
_warned = true;
logMapWarning(
'map tiles failed to load ($error); drawing the route on a plain '
'background',
);
}
MapOptions _options(List<LatLng> coords, ColorScheme scheme) {
final fit = !_live && coords.length > 1
? CameraFit.coordinates(
coordinates: coords,
padding: widget.fitPadding,
maxZoom: _closeZoom,
)
: null;
return MapOptions(
initialCenter: coords.isEmpty ? _fallbackCenter : coords.last,
initialZoom: coords.isEmpty ? _fallbackZoom : _closeZoom,
initialCameraFit: fit,
backgroundColor: scheme.surfaceContainerHigh,
onMapReady: () {
_ready = true;
_followLast();
},
onPositionChanged: (camera, byGesture) {
if (_live && byGesture && _follow) setState(() => _follow = false);
},
);
}
Widget _map(BuildContext context, List<RunPoint> points) {
final scheme = Theme.of(context).colorScheme;
final coords = toLatLngs(points);
return FlutterMap(
mapController: _controller,
options: _options(coords, scheme),
children: [
if (_tiles != null)
TileLayer(
urlTemplate: osmTileUrl,
userAgentPackageName: osmUserAgentPackage,
tileProvider: _tiles,
errorTileCallback: (tile, error, stack) => _warnOnce(error),
),
if (coords.length > 1) routeLayer(coords, scheme),
if (coords.isNotEmpty)
endpointLayer(
coords,
live: _live,
scheme: scheme,
status: Theme.of(context).extension<AppStatusColors>()!,
),
attributionButton(scheme),
],
);
}
@override
Widget build(BuildContext context) {
final listenable = widget.pointsListenable;
if (listenable == null) return _map(context, widget.points!);
return Stack(
fit: StackFit.expand,
children: [
ValueListenableBuilder<List<RunPoint>>(
valueListenable: listenable,
builder: (context, points, _) => _map(context, points),
),
if (!_follow)
Positioned(
left: AppSpacing.sm,
bottom: AppSpacing.sm,
child: IconButton.filled(
onPressed: () {
setState(() => _follow = true);
_followLast();
},
icon: const Icon(
Icons.my_location,
semanticLabel: 'Follow position',
),
),
),
],
);
}
}

View File

@ -0,0 +1,82 @@
/// The route, endpoint markers and attribution button drawn by `RunMap`.
library;
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/ui/theme.dart';
/// [points] as map coordinates.
List<LatLng> toLatLngs(List<RunPoint> points) => [
for (final p in points) LatLng(p.latitude, p.longitude),
];
/// The route as one polyline; drawn even when no tile ever loads.
PolylineLayer routeLayer(List<LatLng> coords, ColorScheme scheme) =>
PolylineLayer(
polylines: [
Polyline(
points: coords,
strokeWidth: 5,
color: scheme.primary,
borderStrokeWidth: 2,
borderColor: scheme.surface,
),
],
);
Marker _dot(LatLng at, Color fill, IconData icon, Color ink) => Marker(
point: at,
child: DecoratedBox(
decoration: BoxDecoration(
color: fill,
shape: BoxShape.circle,
border: Border.all(color: ink, width: 2),
),
child: Icon(icon, size: 16, color: ink),
),
);
/// Start marker (green play), and either the live position (accent dot) or
/// the finish flag (red); no end marker for a one-point track.
MarkerLayer endpointLayer(
List<LatLng> coords, {
required bool live,
required ColorScheme scheme,
required AppStatusColors status,
}) {
final start = _dot(
coords.first,
status.success,
Icons.play_arrow,
scheme.surface,
);
final last = coords.last;
return MarkerLayer(
markers: [
start,
if (live)
_dot(last, scheme.primary, Icons.navigation, scheme.surface)
else if (coords.length > 1)
_dot(last, scheme.error, Icons.flag, scheme.surface),
],
);
}
/// The collapsed, icon-only OSM credit; the (c) text shows only when tapped.
RichAttributionWidget attributionButton(ColorScheme scheme) =>
RichAttributionWidget(
showFlutterMapAttribution: false,
attributions: const [TextSourceAttribution('OpenStreetMap contributors')],
popupBackgroundColor: scheme.surfaceContainerHigh,
openButton: (context, open) => IconButton(
onPressed: open,
icon: Icon(
Icons.info_outline,
size: 20,
color: scheme.onSurface,
semanticLabel: 'Map attribution',
),
),
);

View File

@ -0,0 +1,45 @@
/// The place on the run screen where the live map goes.
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/map_tile_cache.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map.dart';
/// The live map on the run screen: [RunMap.live] over the recorder's points,
/// clipped to the card shape.
///
/// `RunScreen` fills this space from `mapBuilder`, defaulting to this widget.
class RunMapSlot extends StatelessWidget {
/// Creates the slot; [points] updates with every accepted GPS fix.
const RunMapSlot({
required this.points,
super.key,
this.tileProviderOpener = openOsmTileProvider,
});
/// The accepted points of the run so far, oldest first.
final ValueListenable<List<RunPoint>> points;
/// Where the map's tiles come from; tests pass a fake.
final TileProviderOpener tileProviderOpener;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Container(
key: const Key('run_map_slot'),
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(AppRadius.md),
),
clipBehavior: Clip.antiAlias,
child: RunMap.live(
pointsListenable: points,
tileProviderOpener: tileProviderOpener,
),
);
}
}

View File

@ -0,0 +1,69 @@
/// The upload queue as an icon (and, while runs wait, a count).
library;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:workout_app/services/run_uploader.dart';
import 'package:workout_app/ui/theme.dart';
/// The icon for a queue state; shared by the badge and its tests.
IconData uploadBadgeIcon(UploadHealth health) => switch (health) {
UploadHealth.idle => Icons.cloud_done,
UploadHealth.uploading => Icons.cloud_upload,
UploadHealth.retrying => Icons.cloud_off,
UploadHealth.notConfigured => Icons.link_off,
UploadHealth.sandbox => Icons.cloud_queue,
};
/// Shows [uploader]'s state; a tap runs the queue again right now.
class RunUploadBadge extends StatelessWidget {
/// Creates a badge over [uploader].
const RunUploadBadge({required this.uploader, super.key});
/// The queue shown.
final RunUploader uploader;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
return ValueListenableBuilder<RunUploadStatus>(
valueListenable: uploader.status,
builder: (context, s, _) {
final color = switch (s.health) {
UploadHealth.idle => status.success,
UploadHealth.uploading => scheme.primary,
UploadHealth.retrying => status.warning,
UploadHealth.notConfigured => scheme.error,
UploadHealth.sandbox => scheme.onSurfaceVariant,
};
return InkResponse(
key: const Key('run_upload_badge'),
onTap: () => unawaited(uploader.uploadPending()),
child: Padding(
padding: const EdgeInsets.all(AppSpacing.sm),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
uploadBadgeIcon(s.health),
color: color,
semanticLabel: s.health.name,
),
if (s.pending > 0) ...[
const SizedBox(width: AppSpacing.xs),
Text(
'${s.pending}',
key: const Key('run_upload_pending'),
style: TextStyle(color: color, fontSize: AppTextSize.body),
),
],
],
),
),
);
},
);
}
}

View File

@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'package:workout_app/services/runnerup_importer.dart';
/// The RunnerUp history import's state as a glyph, never as words: a small
/// spinner while it runs, a warning glyph when it failed (the next start
/// retries), nothing when it is idle or finished.
class RunnerUpImportBadge extends StatelessWidget {
/// Creates the badge; [status] defaults to the importer's live status.
const RunnerUpImportBadge({super.key, this.status});
/// Overrides [runnerUpImportStatus] (tests).
final ValueNotifier<RunnerUpImportStatus>? status;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<RunnerUpImportStatus>(
valueListenable: status ?? runnerUpImportStatus,
builder: (context, state, _) => switch (state) {
RunnerUpImportStatus.running => const Padding(
padding: EdgeInsets.all(14),
child: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
RunnerUpImportStatus.failed => Padding(
padding: const EdgeInsets.all(14),
child: Icon(
Icons.sync_problem,
color: Theme.of(context).colorScheme.error,
),
),
RunnerUpImportStatus.idle ||
RunnerUpImportStatus.done => const SizedBox.shrink(),
},
);
}
}

View File

@ -5,10 +5,10 @@ packages:
dependency: transitive
description:
name: android_file_picker
sha256: "03d3dd3cb578ab26b1e528aeea27bf6b976942f5a24e3da82d270369b8e161a8"
sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
version: "2.1.5"
archive:
dependency: transitive
description:
@ -149,11 +149,11 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.12.0"
resolved-ref: "59b33949e4a130bb76c77e7434ddf4bbf8cde3a3"
ref: "crdt_sync_dart-v0.12.1"
resolved-ref: "6641d85f0550ca60433fc8e0d13a3dafdbb664d6"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.12.0"
version: "0.12.1"
cross_file:
dependency: transitive
description:
@ -170,23 +170,39 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.8"
dart_earcut:
dependency: transitive
description:
name: dart_earcut
sha256: e485001bfc05dcbc437d7bfb666316182e3522d4c3f9668048e004d0eb2ce43b
url: "https://pub.dev"
source: hosted
version: "1.2.0"
dart_polylabel2:
dependency: transitive
description:
name: dart_polylabel2
sha256: "7eeab15ce72894e4bdba6a8765712231fc81be0bd95247de4ad9966abc57adc6"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
data_transfer_flutter:
dependency: "direct main"
description:
path: data_transfer_flutter
ref: "data_transfer_flutter-v0.2.0"
resolved-ref: bbb7f0f0c0cd891518418472955c8a2ac6cbca4d
ref: "data_transfer_flutter-v0.2.1"
resolved-ref: d4fca83c9f2ed33b3315cd838b9ca532ae8e559c
url: "https://github.com/kuhyx/utils"
source: git
version: "0.2.0"
version: "0.2.1"
dbus:
dependency: transitive
description:
name: dbus
sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612
sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383
url: "https://pub.dev"
source: hosted
version: "0.8.0"
version: "0.7.15"
device_info_plus:
dependency: transitive
description:
@ -203,6 +219,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "8.1.0"
dio:
dependency: "direct main"
description:
name: dio
sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1"
url: "https://pub.dev"
source: hosted
version: "5.11.1"
dio_cache_interceptor:
dependency: "direct main"
description:
name: dio_cache_interceptor
sha256: "9472f9f3dcaa384ae68e60606c1d04e6314dea5eab39f18d94ff9b0a300dbbe4"
url: "https://pub.dev"
source: hosted
version: "4.0.7"
dio_web_adapter:
dependency: transitive
description:
name: dio_web_adapter
sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc"
url: "https://pub.dev"
source: hosted
version: "2.2.2"
fake_async:
dependency: transitive
description:
@ -239,26 +279,26 @@ packages:
dependency: transitive
description:
name: file_picker
sha256: "02f2945a7f29535c735f6b283c3c5553810566d3052d730429aec78fe9d06592"
sha256: c64036857780d7125f011d543f89eedcb5df61da473668bace4eee9ab875284d
url: "https://pub.dev"
source: hosted
version: "13.3.1"
version: "13.3.2"
file_picker_darwin:
dependency: transitive
description:
name: file_picker_darwin
sha256: b845af092ca7a3cff0e768029f835157d371a8341750f4158a7ad358143b0e54
sha256: b7d3a6bd26a18c503d29070fc2d7b26fbfe918d08a6bcd984b6e806ff5ad923f
url: "https://pub.dev"
source: hosted
version: "2.4.1"
version: "2.5.1"
file_picker_linux:
dependency: transitive
description:
name: file_picker_linux
sha256: c6562fc7d426db2fb85ea66fe2627953d2709932df5584ceaacf0aa5e39cf4da
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
version: "2.0.4"
file_picker_platform_interface:
dependency: transitive
description:
@ -416,6 +456,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.0.0"
flutter_map:
dependency: "direct main"
description:
name: flutter_map
sha256: "9bbe5472f66ae648d2ca2efbce97fcaa04e71261fabd3e062f26728222d7f767"
url: "https://pub.dev"
source: hosted
version: "8.3.2"
flutter_map_cache:
dependency: "direct main"
description:
name: flutter_map_cache
sha256: "5c6e91c5b6a3880f4f148dc9fb0ec81bee5bad2b76e91fe1ac3e2dfe8bc4c28b"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
flutter_secure_storage:
dependency: "direct main"
description:
@ -474,6 +530,70 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
geoclue:
dependency: transitive
description:
name: geoclue
sha256: c2a998c77474fc57aa00c6baa2928e58f4b267649057a1c76738656e9dbd2a7f
url: "https://pub.dev"
source: hosted
version: "0.1.1"
geolocator:
dependency: "direct main"
description:
name: geolocator
sha256: "2b3bc0f7320d5a5fa02f8209ffcf1aaa7c2cabb7b2bedbc0cfeb5ff2778b8b09"
url: "https://pub.dev"
source: hosted
version: "14.1.2"
geolocator_android:
dependency: transitive
description:
name: geolocator_android
sha256: e67583809a1fab5f4a2255902978e2bc095ace9451fde0d9624e54facd0a5c22
url: "https://pub.dev"
source: hosted
version: "5.2.1"
geolocator_apple:
dependency: transitive
description:
name: geolocator_apple
sha256: a1e177f3081089724f2095856aeb96eb8d7d1c59e425aed8dd4de7aa2c11ab66
url: "https://pub.dev"
source: hosted
version: "2.4.3"
geolocator_linux:
dependency: transitive
description:
name: geolocator_linux
sha256: "3da7420f11c3496511a5bd3c18fd67b88e5659f12e46b7ce00a788f6996e850a"
url: "https://pub.dev"
source: hosted
version: "0.2.6"
geolocator_platform_interface:
dependency: transitive
description:
name: geolocator_platform_interface
sha256: e012af6b7e2674e7500237ab11e44ac9119e87fd0105e7bb55cde1750e8e5d80
url: "https://pub.dev"
source: hosted
version: "4.4.1"
geolocator_web:
dependency: transitive
description:
name: geolocator_web
sha256: "19e485a0f8d6a88abcf9c53cba3a4105e14b7435ed8ac1c108c067b938fe8429"
url: "https://pub.dev"
source: hosted
version: "4.1.4"
geolocator_windows:
dependency: transitive
description:
name: geolocator_windows
sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6"
url: "https://pub.dev"
source: hosted
version: "0.2.5"
glob:
dependency: transitive
description:
@ -482,54 +602,23 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.3"
google_identity_services_web:
dependency: transitive
description:
name: google_identity_services_web
sha256: "5d187c46dc59e02646e10fe82665fc3884a9b71bc1c90c2b8b749316d33ee454"
url: "https://pub.dev"
source: hosted
version: "0.3.3+1"
google_sign_in:
google_account_token:
dependency: "direct main"
description:
name: google_sign_in
sha256: "521031b65853b4409b8213c0387d57edaad7e2a949ce6dea0d8b2afc9cb29763"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
google_sign_in_android:
path: google_account_token
ref: "google_account_token-v0.1.0"
resolved-ref: db70ba204d124c6eadf9b8808cd3d3b3e70363d1
url: "https://github.com/kuhyx/utils"
source: git
version: "0.1.0"
gsettings:
dependency: transitive
description:
name: google_sign_in_android
sha256: "57782125965ca87b03d42a147d40b046f1fd6a09141a58913e1b86671a5ef22e"
name: gsettings
sha256: "1b0ce661f5436d2db1e51f3c4295a49849f03d304003a7ba177d01e3a858249c"
url: "https://pub.dev"
source: hosted
version: "7.2.16"
google_sign_in_ios:
dependency: transitive
description:
name: google_sign_in_ios
sha256: ac1e4c1205267cb7999d1d81333fccffdfda29e853f434bbaf71525498bb6950
url: "https://pub.dev"
source: hosted
version: "6.3.0"
google_sign_in_platform_interface:
dependency: transitive
description:
name: google_sign_in_platform_interface
sha256: "7f59208c42b415a3cca203571128d6f84f885fead2d5b53eb65a9e27f2965bb5"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
google_sign_in_web:
dependency: transitive
description:
name: google_sign_in_web
sha256: d473003eeca892f96a01a64fc803378be765071cb0c265ee872c7f8683245d14
url: "https://pub.dev"
source: hosted
version: "1.1.3"
version: "0.2.8"
hooks:
dependency: transitive
description:
@ -546,6 +635,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http_cache_core:
dependency: transitive
description:
name: http_cache_core
sha256: d6de4ca6680e70f4eacd79e073d6a73734eb1da86305409e495adfabf404eddf
url: "https://pub.dev"
source: hosted
version: "1.1.4"
http_cache_file_store:
dependency: "direct main"
description:
name: http_cache_file_store
sha256: b83bc178226d82a52f56b97801639ff8d94caeaf5464d25cc96082015111f375
url: "https://pub.dev"
source: hosted
version: "2.0.2"
http_parser:
dependency: transitive
description:
@ -562,6 +667,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.9.2"
intl:
dependency: transitive
description:
name: intl
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.dev"
source: hosted
version: "0.20.3"
jni:
dependency: transitive
description:
@ -594,6 +707,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.12.0"
latlong2:
dependency: "direct main"
description:
name: latlong2
sha256: "84b776b100a84a684a0aaa3fa4dc2c9b1931c658de533701ee4e09bfa991f8dc"
url: "https://pub.dev"
source: hosted
version: "0.10.1"
leak_tracker:
dependency: transitive
description:
@ -654,10 +775,18 @@ packages:
dependency: transitive
description:
name: meta
sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.3"
version: "1.19.0"
mgrs_dart:
dependency: transitive
description:
name: mgrs_dart
sha256: "385e7168ecc77eb545220223c49eef8ab249da7bf57f22781c40a04d23fb196f"
url: "https://pub.dev"
source: hosted
version: "3.0.0"
mime:
dependency: transitive
description:
@ -690,6 +819,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.0"
package_info_plus:
dependency: transitive
description:
name: package_info_plus
sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908"
url: "https://pub.dev"
source: hosted
version: "10.2.2"
package_info_plus_platform_interface:
dependency: transitive
description:
name: package_info_plus_platform_interface
sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4
url: "https://pub.dev"
source: hosted
version: "4.1.0"
path:
dependency: "direct main"
description:
@ -798,10 +943,10 @@ packages:
dependency: transitive
description:
name: petitparser
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790"
url: "https://pub.dev"
source: hosted
version: "7.0.2"
version: "7.1.0"
platform:
dependency: transitive
description:
@ -826,6 +971,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.5.2"
proj4dart:
dependency: transitive
description:
name: proj4dart
sha256: ddcedc1f7876e62717de43ab3491e2829bdad0b028261805f94aa080967e5859
url: "https://pub.dev"
source: hosted
version: "3.0.0"
pub_semver:
dependency: transitive
description:
@ -914,6 +1067,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.4.1"
simple_sparse_list:
dependency: transitive
description:
name: simple_sparse_list
sha256: aa648fd240fa39b49dcd11c19c266990006006de6699a412de485695910fbc1f
url: "https://pub.dev"
source: hosted
version: "0.1.4"
sky_engine:
dependency: transitive
description: flutter
@ -931,50 +1092,50 @@ packages:
dependency: "direct main"
description:
name: sqflite
sha256: "21a9750de2deb464946e9f41c7ddf176e25553618afdfc774868cd454990c06a"
sha256: ed2ff27268e051bde8f0848d6ab86e0f6c01566484d3d358a46ff5e842b36216
url: "https://pub.dev"
source: hosted
version: "2.4.5"
version: "2.4.6"
sqflite_android:
dependency: transitive
description:
name: sqflite_android
sha256: "3986f4cbdde19ca538aae877981c5a53400dcc4601499df18e7ed9e848a0bdd4"
sha256: e75917dbfe721e6938fc4ff18d3e61549f17cf88a4eba189e2b270290d0c9be3
url: "https://pub.dev"
source: hosted
version: "2.4.5"
version: "2.4.6"
sqflite_common:
dependency: transitive
description:
name: sqflite_common
sha256: "5bf6a55c166e73bf651ba7ec3ed486e577620e3dc8f3a9c6a258a8031b624590"
sha256: "35a65713b6695fbc5f3596921c8af1dfe767942c96b6c5c80a739b16a10d47eb"
url: "https://pub.dev"
source: hosted
version: "2.5.11"
version: "2.5.17"
sqflite_common_ffi:
dependency: "direct main"
description:
name: sqflite_common_ffi
sha256: "119d730460264a1f11f414d9eaa43fb686789357e81ce35f9e8ccb66ddd040e4"
sha256: "26911d808e4d33b3965da8821440ef4b021d3bc7282f5eb76e6621827995dd86"
url: "https://pub.dev"
source: hosted
version: "2.4.5"
version: "2.4.6"
sqflite_darwin:
dependency: transitive
description:
name: sqflite_darwin
sha256: c86ca18b8f666bbf903924687fe21cc16fc385d086005067e26619ca530bef9f
sha256: "6ef57df819b502e306d0b58ba6cb614952d294b825c003feba3c47764c20a825"
url: "https://pub.dev"
source: hosted
version: "2.4.3+1"
version: "2.4.6"
sqflite_platform_interface:
dependency: transitive
description:
name: sqflite_platform_interface
sha256: "5b611dbcb9bab33e7073594ecac111bf0a86ffc342652c2081160d7038a45fb6"
sha256: "7bfeb7f9e09761147e8e3a4ff3f1d8979fe46a736f03f3805f572599ade69308"
url: "https://pub.dev"
source: hosted
version: "2.4.3"
version: "2.4.4"
sqlite3:
dependency: transitive
description:
@ -1011,11 +1172,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.6.0"
resolved-ref: "3121639732fac85f7e25f3df4e081a228d63aa74"
ref: "sync_settings_ui-v0.6.2"
resolved-ref: "95cd3731ede686114353d32ae6c286ad1694b488"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.6.0"
version: "0.6.2"
synchronized:
dependency: transitive
description:
@ -1056,6 +1217,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
unicode:
dependency: transitive
description:
name: unicode
sha256: a6f7bcfc8ea1d5ce1f6c0b1c39117a9919f4953edd9fd7a64090a9796c499b57
url: "https://pub.dev"
source: hosted
version: "1.1.9"
url_launcher:
dependency: "direct main"
description:
@ -1200,6 +1369,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.1"
wkt_parser:
dependency: transitive
description:
name: wkt_parser
sha256: "8a555fc60de3116c00aad67891bcab20f81a958e4219cc106e3c037aa3937f13"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
xdg_directories:
dependency: transitive
description:
@ -1209,13 +1386,13 @@ packages:
source: hosted
version: "1.1.0"
xml:
dependency: transitive
dependency: "direct main"
description:
name: xml
sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"
sha256: "0fe8cc98946def31cbcbc8734aa4067031e6f65ea3a78a508060bfed2200bfeb"
url: "https://pub.dev"
source: hosted
version: "7.0.1"
version: "7.1.0"
yaml:
dependency: transitive
description:

View File

@ -12,7 +12,7 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.12.0
ref: crdt_sync_dart-v0.12.1
path: crdt_sync_dart
# HMAC-SHA256 for the signed phone->PC workout poke (pc_poke_wire.dart).
crypto: 3.0.8
@ -20,8 +20,11 @@ dependencies:
data_transfer_flutter:
git:
url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.0
ref: data_transfer_flutter-v0.2.1
path: data_transfer_flutter
# Persistent tile cache for the run map (flutter_map_cache talks to dio).
dio: 5.11.1
dio_cache_interceptor: 4.0.7
flutter:
sdk: flutter
# Keeps the rest-period deadline ticking with the screen off, and owns the
@ -32,28 +35,41 @@ dependencies:
# The break-end alert itself, on its own high-importance channel so the OS
# rings even if the Flutter isolate is busy.
flutter_local_notifications: 23.0.0
# The run map and its tile disk cache.
flutter_map: 8.3.2
flutter_map_cache: 2.1.2
flutter_secure_storage: 11.2.0
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
# Dart so it keeps working on Linux desktop and headless.
google_sign_in: 7.2.0
# GPS fixes, behind the PositionSource seam (lib/services/position_source).
geolocator: 14.1.2
# One-tap sign-in for the sync account (AccountManager ID token; no Play
# Services SDK in the APK). App-side only: crdt_sync stays pure Dart so it
# keeps working on Linux desktop and headless.
google_account_token:
git:
url: https://github.com/kuhyx/utils
ref: google_account_token-v0.1.0
path: google_account_token
http: 1.6.0
http_cache_file_store: 2.0.2
latlong2: 0.10.1
path: 1.9.1
path_provider: 2.1.6
permission_handler: 13.0.2
shared_preferences: 2.5.6
sqflite: 2.4.5
sqflite: 2.4.6
# Linux desktop has no sqflite plugin; the FFI factory drives the same
# schema (and already backed the test suite before the desktop target).
sqflite_common_ffi: 2.4.5
sqflite_common_ffi: 2.4.6
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.6.0
ref: sync_settings_ui-v0.6.2
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0
vibration: 3.2.1
# TCX read/write (lib/services/tcx_codec.dart).
xml: 7.1.0
dev_dependencies:
audioplayers_platform_interface: 7.2.0

View File

@ -0,0 +1,107 @@
#!/bin/bash
# provision_run_upload.sh — give the workout app its own dufs login for run
# uploads, without anyone typing a password.
#
# 1. creates (idempotently) a dufs login `workout_app` scoped `/RunnerUp rw`
# via ~/src/dufs-cloud/scripts/add_dufs_login.sh. That script needs sudo
# (it restarts dufs.service the first time, and may `pacman -S` openssl/
# curl/xclip); an existing login is left alone. It never touches the
# `runnerup` login the stock RunnerUp app depends on, and this script
# never passes --rotate.
# 2. writes {"url","user","password"} (url = the BARE origin, the app
# appends /RunnerUp/<file>) to a 0600 temp file,
# 3. adb-pushes it to the app's external files dir, where the app imports it
# into secure storage on the next start and deletes it.
#
# The app uploads each finished run as a TCX; a PC-side watcher credits it.
# Run only when the phone is attached and the app has been started once.
#
# Usage: provision_run_upload.sh [--print-only]
# ADB_SERIAL phone serial (default 23181JEGR08034)
set -euo pipefail
readonly LOGIN_USER="workout_app"
readonly LOGIN_PATH="/RunnerUp"
readonly ADD_LOGIN="${ADD_DUFS_LOGIN:-${HOME}/src/dufs-cloud/scripts/add_dufs_login.sh}"
readonly ENV_FILE="${DUFS_LOGINS_DIR:-${HOME}/.config/dufs/logins}/${LOGIN_USER}.env"
readonly SERIAL="${ADB_SERIAL:-23181JEGR08034}"
readonly APP_ID="com.kuhy.workout_app"
readonly REMOTE_DIR="/sdcard/Android/data/${APP_ID}/files"
readonly REMOTE_FILE="${REMOTE_DIR}/dufs_login.json"
PRINT_ONLY=0
TMP_JSON=""
die() {
printf '[FAIL] %s\n' "$*" >&2
exit 1
}
cleanup() {
if [[ -n ${TMP_JSON} && -f ${TMP_JSON} ]]; then
rm -f "${TMP_JSON}"
fi
}
trap cleanup EXIT
# Reads KEY from the login's .env without sourcing it (no code execution).
env_value() {
local key="$1" line
line="$(grep -m1 "^${key}=" "${ENV_FILE}")" || die "${key} missing in ${ENV_FILE}"
printf '%s' "${line#*=}"
}
check_tools() {
local tool
for tool in jq adb; do
command -v "${tool}" >/dev/null || die "${tool} is required (sudo pacman -S ${tool})"
done
[[ -x ${ADD_LOGIN} ]] || die "missing ${ADD_LOGIN}"
}
ensure_login() {
"${ADD_LOGIN}" "${LOGIN_USER}" "${LOGIN_PATH}" rw
[[ -f ${ENV_FILE} ]] || die "${ENV_FILE} was not written"
}
write_json() {
TMP_JSON="$(mktemp)"
chmod 600 "${TMP_JSON}"
jq -n \
--arg url "$(env_value DUFS_URL)" \
--arg user "$(env_value DUFS_USER)" \
--arg password "$(env_value DUFS_PASSWORD)" \
'{url: $url, user: $user, password: $password}' >"${TMP_JSON}"
jq -e '.url | test("^https?://[^/]+$")' "${TMP_JSON}" >/dev/null ||
die "url must be a bare origin without a path"
}
push_json() {
adb -s "${SERIAL}" get-state >/dev/null || die "phone ${SERIAL} is not attached"
adb -s "${SERIAL}" shell mkdir -p "${REMOTE_DIR}"
adb -s "${SERIAL}" push "${TMP_JSON}" "${REMOTE_FILE}" >/dev/null
adb -s "${SERIAL}" shell ls -l "${REMOTE_FILE}"
printf '[ OK ] pushed; open the app once: it imports the login and deletes the file\n'
}
main() {
if [[ ${1:-} == --print-only ]]; then
PRINT_ONLY=1
elif [[ $# -gt 0 ]]; then
die "usage: provision_run_upload.sh [--print-only]"
fi
check_tools
# --print-only must not need sudo: reuse an existing login's .env.
if [[ ${PRINT_ONLY} -eq 0 || ! -f ${ENV_FILE} ]]; then
ensure_login
fi
write_json
if [[ ${PRINT_ONLY} -eq 1 ]]; then
jq '.password = "***"' "${TMP_JSON}"
return 0
fi
push_json
}
main "$@"

View File

@ -0,0 +1,96 @@
/// A recording fake for the run foreground service.
library;
import 'package:audioplayers/audioplayers.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
/// Stands in for `flutter_foreground_task` on the run screen's side.
class FakeForegroundRunClient implements ForegroundRunClient {
/// Creates a fake describing a healthy Android device.
FakeForegroundRunClient({
this.isSupported = true,
this.permissionGranted = true,
this.grantOnRequest = true,
this.startSucceeds = true,
this.onStart,
});
@override
bool isSupported;
/// Whether notifications are already allowed.
bool permissionGranted;
/// Whether asking for them succeeds.
bool grantOnRequest;
/// Whether the service starts.
bool startSucceeds;
/// Runs inside [start], to record what had happened by then.
void Function()? onStart;
/// `withLocation` of each start.
final starts = <bool>[];
/// Notification redraws as `title|text`, the first being the start.
final drawn = <String>[];
/// Calls recorded in order.
final calls = <String>[];
@override
Future<bool> hasNotificationPermission() async {
calls.add('has');
return permissionGranted;
}
@override
Future<bool> requestNotificationPermission() async {
calls.add('request');
return permissionGranted = grantOnRequest;
}
@override
Future<bool> start({
required bool withLocation,
required String title,
required String text,
}) async {
calls.add('start');
onStart?.call();
starts.add(withLocation);
drawn.add('$title|$text');
return startSucceeds;
}
@override
Future<void> update({required String title, required String text}) async {
drawn.add('$title|$text');
}
@override
Future<void> stop() async => calls.add('stop');
}
/// Cues that touch neither the database nor a speaker, and count kilometres.
class QuietCues extends FeedbackCues {
/// Creates cues over a player (needs the fake audio platform installed).
QuietCues() : super(AudioPlayer());
/// Kilometres announced.
final kilometres = <int>[];
/// How many times the finish cue fired.
int finishes = 0;
@override
Future<void> load() async {}
@override
Future<void> kilometreReached(int km) async => kilometres.add(km);
@override
Future<void> workoutFinished() async => finishes++;
}

View File

@ -0,0 +1,28 @@
/// A queue whose state the test sets by hand.
library;
import 'package:flutter/foundation.dart';
import 'package:workout_app/services/run_uploader.dart';
/// Stands in for [RunUploader] where a widget only reads its state.
class FakeRunUploader extends RunUploader {
/// Creates a fake queue at [initial].
FakeRunUploader([
RunUploadStatus initial = const RunUploadStatus(UploadHealth.idle, 0),
]) : state = ValueNotifier(initial);
/// The state the badge listens to; assign `.value` to change it.
final ValueNotifier<RunUploadStatus> state;
/// How many times a pass was requested.
int passes = 0;
@override
ValueListenable<RunUploadStatus> get status => state;
@override
Future<RunUploadStatus> uploadPending() async {
passes++;
return state.value;
}
}

View File

@ -1,14 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
void main() {
test('reports whether the programmatic Google flow exists here', () {
// Android is the only platform shipping it. Asked as a platform question
// rather than of the plugin, because GoogleSignIn.supportsAuthenticate()
// itself throws UnimplementedError where no implementation is registered
// -- an Error, not an Exception, so it would escape an ordinary catch and
// take down the settings screen's build(). The test host is Linux, so
// this is false here and the password path stays visible.
expect(googleSignInSupported, isFalse);
});
}

View File

@ -1,13 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_platform_web.dart';
void main() {
test('the web half always reports the programmatic flow unsupported', () {
// The conditional export in google_platform.dart never pulls this file
// in on the Linux test host (it resolves to google_platform_io.dart
// instead), so it would otherwise never appear in coverage at all.
// Imported directly here for that reason, same pattern as
// sync_state_factory_web_test.dart elsewhere in this app family.
expect(googleSignInSupported, isFalse);
});
}

View File

@ -1,7 +1,19 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
const _channel = MethodChannel('dev.kuhy/google_account_token');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
tearDown(() {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, null);
});
group('googleIdToken', () {
test('returns the token the sign-in function yields', () async {
// The injected path: proves the closure is what feeds crdt_sync, and
@ -19,15 +31,54 @@ void main() {
});
test('reports "not configured" when the client id is missing', () async {
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID must fall back
// rather than failing deep inside the plugin with an opaque message.
// An empty id must not reach the OS account chooser.
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(await googleIdToken(serverClientId: ''), isNull);
});
test('warns loudly when the client id is empty', () async {
final warnings = <String>[];
expect(
await googleIdToken(serverClientId: '', warn: warnings.add),
isNull,
);
expect(warnings, hasLength(1));
expect(warnings.single, contains('kServerClientId'));
});
test('logs via dart:developer when no warn hook is given', () async {
// Default path (no seam): must not throw and must still return null.
expect(await googleIdToken(serverClientId: ''), isNull);
});
test('asks the account-token plugin for the Web client id', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
Object? sent;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
sent = call.arguments;
return 'plugin-token';
});
expect(await googleIdToken(), 'plugin-token');
expect(sent, {'serverClientId': kServerClientId});
});
test('pins the uid the security rules expect', () {
// If this ever drifts from database.rules.json, a Google sign-in would
// be accepted here and then denied every read and write.
expect(kSyncUid, 'OvA2REQyLIhAHOEjzwS1o877rgG3');
});
});
group('googleSignInSupported', () {
test('is true on Android', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(googleSignInSupported, isTrue);
});
test('is false on Linux desktop, so the password path stays', () {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
expect(googleSignInSupported, isFalse);
});
});
}

View File

@ -0,0 +1,80 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
void main() {
group('RunSport', () {
test('maps the TCX sport name both ways', () {
expect(RunSport.fromTcxName('Running'), RunSport.running);
expect(RunSport.fromTcxName('Walking'), RunSport.walking);
expect(RunSport.fromTcxName('Other'), isNull);
expect(RunSport.fromTcxName(null), isNull);
expect(RunSport.walking.tcxName, 'Walking');
});
});
group('storage keys', () {
test('RunSource round-trips and rejects unknown keys', () {
for (final s in RunSource.values) {
expect(RunSource.fromStorageKey(s.storageKey), s);
}
expect(RunSource.runnerupImport.storageKey, 'runnerup_import');
expect(() => RunSource.fromStorageKey('nope'), throwsStateError);
});
test('RunUploadState round-trips and rejects unknown keys', () {
for (final s in RunUploadState.values) {
expect(RunUploadState.fromStorageKey(s.storageKey), s);
}
expect(() => RunUploadState.fromStorageKey('nope'), throwsStateError);
});
});
group('RunTrack', () {
test('idFor is the UTC second-precision Z stamp', () {
expect(
RunTrack.idFor(DateTime.utc(2026, 11, 9, 16, 30, 5, 999)),
'2026-11-09T16:30:05Z',
);
expect(
RunTrack.idFor(DateTime.parse('2026-11-09T17:30:05+01:00')),
'2026-11-09T16:30:05Z',
);
});
test('started derives the id and normalises times to UTC', () {
final local = DateTime.parse('2026-11-09T17:30:00+01:00');
final track = RunTrack.started(
sport: RunSport.walking,
startedAt: local,
points: [
RunPoint(time: local, latitude: 1, longitude: 2, distanceM: 0),
],
totalSeconds: 0,
distanceM: 0,
);
expect(track.id, '2026-11-09T16:30:00Z');
expect(track.startedAt.isUtc, isTrue);
expect(track.points.single.time.isUtc, isTrue);
expect(track.source, RunSource.app);
});
});
group('RunPoint', () {
final t = DateTime.utc(2026, 11, 9);
RunPoint make({double? alt = 1}) => RunPoint(
time: t,
latitude: 1,
longitude: 2,
altitudeM: alt,
distanceM: 3,
);
test('has value equality', () {
expect(make(), make());
expect(make().hashCode, make().hashCode);
expect(make(), isNot(make(alt: null)));
expect(make(), isNot('x'));
});
});
}

View File

@ -0,0 +1,77 @@
/// Shared fakes for the run recorder, controller and screen tests.
library;
import 'dart:async';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
/// One degree of latitude in metres, so tests place fixes by distance.
const double kDegM = 111194.9;
/// A fix [seconds] after 12:00:00 UTC, [northM] metres north of the origin.
GpsFix fixAt(
int seconds,
double northM, {
double accuracy = 5,
bool mocked = false,
}) => GpsFix(
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: seconds)),
latitude: 48.8584 + northM / kDegM,
longitude: 2.2945,
altitudeM: 30,
accuracyM: accuracy,
isMocked: mocked,
);
/// [count] fixes 2 s apart moving north at 3 m/s (a 10.8 km/h run).
List<GpsFix> straightRun(int count, {int startSecond = 0}) => [
for (var i = 0; i < count; i++)
fixAt(startSecond + i * 2, (startSecond + i * 2) * 3.0),
];
/// A source the test feeds by hand, so a pause can fall between two fixes.
class ManualPositionSource implements PositionSource {
/// Creates a source answering [access].
ManualPositionSource({this.access = LocationAccess.granted});
/// What [requestAccess] answers.
final LocationAccess access;
/// The stream the recorder listens to.
final controller = StreamController<GpsFix>.broadcast();
/// How many times [fixes] was called.
int subscriptions = 0;
@override
Future<LocationAccess> requestAccess() async => access;
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) {
subscriptions++;
return controller.stream;
}
}
/// A small stored-run shaped track starting at [start] (UTC).
RunTrack sampleTrack({String start = '2026-11-09T12:00:00Z'}) {
final t = DateTime.parse(start);
return RunTrack.started(
sport: RunSport.running,
startedAt: t,
totalSeconds: 20,
distanceM: 60,
points: [
for (var i = 0; i < 3; i++)
RunPoint(
time: t.add(Duration(seconds: i * 10)),
latitude: 48.8584 + i * 0.00027,
longitude: 2.2945,
altitudeM: 31,
distanceM: i * 30.0,
),
],
);
}

View File

@ -0,0 +1,89 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source_geolocator.dart';
import 'package:workout_app/services/position_source_scripted.dart';
import 'package:workout_app/services/run_math.dart';
void main() {
tearDown(() {
Sandbox.enabled = false;
Sandbox.runReplayFactor = Sandbox.defaultReplayFactor;
});
final start = DateTime.utc(2026, 11, 10, 8);
for (final sport in RunSport.values) {
test('the ${sport.tcxName} loop is a legal ~4 km track for the filter', () {
final fixes = sandboxLoopFixes(start, sport);
final filter = GpsFilter(sport: sport);
for (final fix in fixes) {
expect(filter.add(fix), FixVerdict.accepted);
}
expect(filter.distanceM, closeTo(kLoopLengthM, 20));
expect(movingSeconds(filter.points, sport), fixes.length * 2 - 2);
expect(fixes.first.time, start);
// A closed loop: the lap ends where it began.
expect(
haversineM(
fixes.first.latitude,
fixes.first.longitude,
fixes.last.latitude,
fixes.last.longitude,
),
lessThan(5),
);
});
}
test('a run laps at 10 km/h (24 minutes of fixes), a walk at 5 km/h', () {
final run = sandboxLoopFixes(start, RunSport.running);
final walk = sandboxLoopFixes(start, RunSport.walking);
expect(run.last.time.difference(start), const Duration(minutes: 24));
expect(walk.last.time.difference(start), const Duration(minutes: 48));
});
test('replay times follow the start, so two replays never share an id', () {
final a = sandboxLoopFixes(start, RunSport.running);
final b = sandboxLoopFixes(
start.add(const Duration(seconds: 1)),
RunSport.running,
);
expect(RunTrack.idFor(a.first.time), isNot(RunTrack.idFor(b.first.time)));
});
test('the speed-up divides the 2 s fix interval', () async {
for (final (factor, micros) in [(1, 2000000), (10, 200000), (60, 33333)]) {
Sandbox.runReplayFactor = factor;
final source = sandboxRunSource(RunSport.running, now: start);
expect(source, isA<ScriptedPositionSource>());
expect(
(source as ScriptedPositionSource).fixDelay,
Duration(microseconds: micros),
);
}
});
test('the default speed-up replays a whole run in under a minute', () {
expect(Sandbox.runReplayFactor, 60);
final fixes = sandboxLoopFixes(start, RunSport.running).length;
expect(fixes * 2 / Sandbox.runReplayFactor, lessThan(60));
expect(
sandboxLoopFixes(start, RunSport.walking).length * 2 / 60,
lessThan(60),
);
expect(Sandbox.replayFactors, [1, 10, 60]);
});
test('the sandbox replays; the daily build reads the real GPS', () async {
Sandbox.enabled = true;
expect(positionSourceFor(RunSport.running), isA<ScriptedPositionSource>());
Sandbox.enabled = false;
expect(
positionSourceFor(RunSport.running),
isA<GeolocatorPositionSource>(),
);
});
}

Some files were not shown because too many files have changed in this diff Show More