-
Notifications
You must be signed in to change notification settings - Fork 2
/
waybar-media.py
executable file
·275 lines (221 loc) · 7.99 KB
/
waybar-media.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python3
import json
import math
import os
import sys
import textwrap
import traceback
import psutil
from gi.repository import GLib
from pydbus import SessionBus
MPRIS_PLAYER_OBJ_PATH = '/org/mpris/MediaPlayer2'
MPRIS_PLAYER_IFACE = 'org.mpris.MediaPlayer2.Player'
KNOWN_SERVICES = [
'org.mpris.MediaPlayer2.mpv',
'org.kde.plasma.browser_integration'
]
KNOWN_BROWSER_MAP = {
'mozilla': 'Firefox',
'chromium': 'Chromium',
'chrome': 'Google Chrome'
}
class Player:
def __init__(self, bus, owner_name):
self._bus = bus
self.owner_name = owner_name
self.owner_process = self._get_owner_process()
self._obj = self._bus.get(owner_name, MPRIS_PLAYER_OBJ_PATH)
def _get_owner_process(self):
obj = self._bus.get('org.freedesktop.DBus', '/org/freedesktop/DBus')
pid = obj.GetConnectionUnixProcessID(self.owner_name)
if pid is None:
return None
return psutil.Process(pid)
@staticmethod
def _identify_browser_by_cmdline(cmdline):
for fragment, browser in KNOWN_BROWSER_MAP.items():
if fragment in cmdline:
return browser
return None
@property
def name(self):
name = self.owner_process.name()
if name == 'plasma-browser-integration-host':
cmdline = ' '.join(self.owner_process.cmdline())
return self._identify_browser_by_cmdline(cmdline)
return name
@property
def status(self):
return self._obj.PlaybackStatus.lower()
@property
def title(self):
return self._obj.Metadata.get('xesam:title')
@property
def album(self):
return self._obj.Metadata.get('xesam:album')
@property
def artist(self):
artists = self._obj.Metadata.get('xesam:artist')
return ', '.join(artists) if isinstance(artists, list) else artists
def playpause(self):
if self._obj.CanPlay or self._obj.CanPause:
self._obj.PlayPause()
def play(self):
if self._obj.CanPlay:
self._obj.Play()
def pause(self):
if self._obj.CanPause:
self._obj.Pause()
def previous(self):
if self._obj.CanGoPrevious:
self._obj.Previous()
def next(self):
if self._obj.CanGoNext:
self._obj.Next()
class MediaWatcher:
def __init__(self, bus, do_print_status=False):
self._bus = bus
self._owner_to_player = self._find_players()
self.player = self._find_active_player()
if do_print_status:
self.status_builder = MediaWatcherStatusBuilder(self)
self.status_builder.print_status()
else:
self.status_builder = None
def __enter__(self):
self._subscription = self._bus.subscribe(
iface='org.freedesktop.DBus.Properties',
signal='PropertiesChanged',
object=MPRIS_PLAYER_OBJ_PATH,
arg0=MPRIS_PLAYER_IFACE,
signal_fired=self._mpris_signal_handler,
)
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None:
traceback.print_exception(exc_type, exc_value, tb)
self._subscription.unsubscribe()
def _find_players(self):
owner_to_player = {}
for service in KNOWN_SERVICES:
try:
owner_name = self._bus.dbus.GetNameOwner(service)
except GLib.Error:
continue
owner_to_player[owner_name] = Player(bus=self._bus, owner_name=owner_name)
return owner_to_player
def _group_players_by_status(self):
status_to_players = {}
for player in self._owner_to_player.values():
if player.status in status_to_players:
status_to_players[player.status].append(player)
else:
status_to_players[player.status] = [player]
return status_to_players
def _find_active_player(self):
players_by_status = self._group_players_by_status()
if players_by_status.get('playing'):
players_by_status['playing'].sort(key=lambda x: x.owner_process.create_time(), reverse=True)
return players_by_status['playing'][0]
elif players_by_status.get('paused'):
return players_by_status['paused'][0]
elif players_by_status.get('stopped'):
return players_by_status['stopped'][0]
return None
def _mpris_signal_handler(self, sender_name, *_):
if sender_name not in self._owner_to_player:
self._owner_to_player[sender_name] = Player(bus=self._bus, owner_name=sender_name)
self.player = self._find_active_player()
if self.status_builder:
self.status_builder.print_status()
class MediaWatcherStatusBuilder:
def __init__(self, watcher):
self.watcher = watcher
def _build_tooltip(self):
tooltip = []
player = self.watcher.player
if player.status in ['playing', 'paused']:
tooltip.append(player.status.title() + ':')
if player.title:
tooltip.append(player.title)
if player.album:
tooltip.append(player.album)
if player.artist:
tooltip.append(player.artist)
if player.name:
tooltip.append('(' + player.name + ')')
return '\n'.join(tooltip) if tooltip else None
def _build_text(self, max_width, title_to_artist_ratio=2 / 3, separator=' - ', placeholder='…'):
max_width = max_width - len(separator)
player = self.watcher.player
if player.title and player.artist:
title_width = math.floor(max_width * title_to_artist_ratio)
artist_width = max_width - title_width
elif player.title and not player.artist:
title_width = max_width
artist_width = 0
elif player.artist and not player.title:
title_width = 0
artist_width = max_width
else:
return None
short_title = (
None if title_width == 0 else textwrap.shorten(player.title, width=title_width, placeholder=placeholder)
)
short_artist = (
None if artist_width == 0 else textwrap.shorten(player.artist, width=artist_width, placeholder=placeholder)
)
if short_title and short_artist:
return separator.join((short_title, short_artist))
elif short_title and not short_artist:
return short_title
elif short_artist and not short_title:
return short_artist
def _build_classes(self):
classes = []
player = self.watcher.player
if player.status in ['playing', 'paused']:
classes.append(player.status)
else:
classes.append('stopped')
return classes
def build_status(self):
return json.dumps(
{'tooltip': self._build_tooltip(), 'text': self._build_text(max_width=80), 'class': self._build_classes()}
)
def print_status(self):
print(self.build_status())
sys.stdout.flush()
def print_usage():
name = os.path.basename(sys.argv[0])
print('Usage:\n\t{} (status|playpause|previous|next)\n'.format(name))
def main():
bus = SessionBus()
loop = GLib.MainLoop()
if len(sys.argv) == 2:
arg = sys.argv[1]
else:
print_usage()
return
with MediaWatcher(bus, do_print_status=(arg == 'status')) as media_watcher:
if arg == 'status':
while True:
try:
loop.run()
except GLib.Error:
pass
elif arg == 'playpause':
media_watcher.player.playpause()
elif arg == 'play':
media_watcher.player.play()
elif arg == 'pause':
media_watcher.player.pause()
elif arg == 'previous':
media_watcher.player.previous()
elif arg == 'next':
media_watcher.player.next()
else:
print_usage()
return
if __name__ == '__main__':
main()