Created
June 27, 2026 19:45
-
-
Save mattburesh/b23be39e7b8643028e7a953246094e2e to your computer and use it in GitHub Desktop.
Tracking plays in rmpc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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