Files
dotfiles/scripts/notification-sounds.py
Ziad ArafatandClaude Opus 5.5 195d9d6c6f Sounds actually audible: unmute the event stream, Konsole bell via notifications, chime for every app notification
- The WirePlumber 'Notification' role stream was saved muted, silencing every
  theme sound except Plasma's volume tick; dot sounds build/test/notify now
  unmutes it at 100% (ensure_event_stream).
- Konsole profiles: BellMode=1 (notification) — the default system beep is silent on Wayland.
- notification-sounds: user service watching Notify calls via dbus-monitor; plays
  message-new-instant for notifications without their own sound (skips
  KNotification events, sound hints, and apps with in-app sounds: Telegram, Vesktop).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013UzjWUxheYfqqjWGH7Ktmc
2026-10-30 15:21:56 -06:00

105 lines
3.8 KiB
Python

"""Give every desktop notification a sound.
Plasma only plays a sound for a freedesktop notification when the sender asks
for one, so most apps (Chrome PWAs, notify-send, Electron apps) are silent.
This watches org.freedesktop.Notifications.Notify calls via `dbus-monitor`
(read-only) and plays the theme's message-new-instant sound unless:
* the sender is a KNotification (x-kde-eventId hint) - KDE plays those itself,
* the notification carries sound-file / sound-name / suppress-sound,
* the app plays its own sound (SKIP_APPS, override with NOTIFICATION_SOUNDS_SKIP).
"""
import os
import re
import select
import subprocess
import time
from pathlib import Path
SKIP_APPS = {
a.strip().lower()
for a in os.environ.get("NOTIFICATION_SOUNDS_SKIP", "Telegram Desktop,Telegram,vesktop,Vesktop,discord").split(",")
if a.strip()
}
SOUND = os.environ.get("NOTIFICATION_SOUNDS_EVENT", "message-new-instant")
OWN_SOUND_HINTS = ('"x-kde-eventId"', '"sound-file"', '"sound-name"', '"suppress-sound"')
MIN_GAP = 0.4 # seconds; a burst of notifications gets one sound
last = 0.0
def sound_file() -> str | None:
theme = subprocess.run(
["kreadconfig6", "--file", "kdeglobals", "--group", "Sounds", "--key", "Theme", "--default", "ocean"],
capture_output=True, text=True,
).stdout.strip()
for base in (Path.home() / ".local/share/sounds", Path("/usr/share/sounds")):
for t in (theme, "ocean", "freedesktop"):
hits = sorted((base / t / "stereo").glob(f"{SOUND}.*"))
if hits:
return str(hits[0])
return None
def play() -> None:
global last
now = time.monotonic()
if now - last < MIN_GAP:
return
last = now
f = sound_file()
if f:
# Same "event" role stream as KDE's own sounds, so the Notification Sounds slider applies.
subprocess.Popen(["paplay", "--property=media.role=event", "--property=application.name=notification-sounds", f])
def judge(block: list[str]) -> None:
"""block = dbus-monitor lines of one Notify call: header, app_name, ..., hints dict."""
strings = [m.group(1) for line in block if (m := re.match(r'\s*string "(.*)"$', line))]
if not strings:
return
app = strings[0]
text = "\n".join(block)
# suppress-sound may be present but false; only treat true as "has its own sound".
suppressed = re.search(r'"suppress-sound"\s*\n\s*variant\s+boolean true', text)
own = any(h in text for h in OWN_SOUND_HINTS[:3]) or suppressed
if not own and app.lower() not in SKIP_APPS:
print(f"ding for {app!r}", flush=True)
play()
def main() -> None:
mon = subprocess.Popen(
["dbus-monitor", "--session", "type='method_call',interface='org.freedesktop.Notifications',member='Notify'"],
stdout=subprocess.PIPE,
)
fd = mon.stdout.fileno()
print(f"listening; skipping {sorted(SKIP_APPS)}", flush=True)
pending = b""
block: list[str] = []
while True:
# Raw fd + select (no buffered readline, which would hide lines from select).
ready, _, _ = select.select([fd], [], [], 0.15)
if not ready:
if block: # quiet for 150 ms: the call is complete
judge(block)
block = []
continue
chunk = os.read(fd, 65536)
if not chunk:
raise SystemExit(f"dbus-monitor exited ({mon.wait()})")
pending += chunk
*lines, pending = pending.split(b"\n")
for raw in lines:
line = raw.decode(errors="replace")
if line.startswith(("method call", "signal", "method return", "error")):
if block:
judge(block)
block = [line] if "member=Notify" in line else []
elif block:
block.append(line)
if __name__ == "__main__":
main()