Skip to content

Instantly share code, notes, and snippets.

@mattburesh
Created June 27, 2026 19:45
Show Gist options
  • Select an option

  • Save mattburesh/b23be39e7b8643028e7a953246094e2e to your computer and use it in GitHub Desktop.

Select an option

Save mattburesh/b23be39e7b8643028e7a953246094e2e to your computer and use it in GitHub Desktop.
Tracking plays in rmpc
#!/usr/bin/env python3
import os, sys, json, subprocess, csv
from datetime import datetime, timezone
from pathlib import Path
LOG = Path.home() / ".local/share/rmpc/plays.tsv"
prev = os.environ.get("PREV_SONG")
if not prev:
sys.exit(0) # first track of session, nothing prior to log
try:
elapsed = float(os.environ.get("PREV_ELAPSED", "0"))
except ValueError:
elapsed = 0.0
# Ask rmpc for the previous song's metadata as JSON.
try:
raw = subprocess.run(
["rmpc", "song", "--path", prev],
capture_output=True, text=True, timeout=5, check=True,
).stdout
meta = json.loads(raw)
except (FileNotFoundError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
print(f"on_song_change: rmpc query failed: {e}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"on_song_change: could not parse rmpc output: {e}", file=sys.stderr)
sys.exit(1)
duration = (meta.get("duration") or {}).get("secs", 0)
# Count if >=240s played, or >=50% of a known duration.
counted = elapsed >= 240 or (duration > 0 and elapsed >= duration / 2)
if not counted:
sys.exit(0)
tags = meta.get("metadata", {})
row = [
datetime.now(timezone.utc).isoformat(timespec="seconds"),
tags.get("artist", "?"),
tags.get("album", "?"),
tags.get("title", "?"),
prev,
]
LOG.parent.mkdir(parents=True, exist_ok=True)
with LOG.open("a", newline="") as f:
csv.writer(f, delimiter="\t").writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment