forked from otommod/browser-mpris2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chrome-mpris2
executable file
·522 lines (406 loc) · 16.9 KB
/
chrome-mpris2
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/usr/bin/env python3
import json
import struct
import sys
from collections import defaultdict
from gi.repository import Gio, GLib
def debug(msg):
print(msg, file=sys.stderr, flush=True)
def make_streams_binary():
sys.stdin = sys.stdin.detach()
sys.stdout = sys.stdout.detach()
def escape_object_path(objpath):
# We basically URI escape but instead of % we use _
return (GLib.uri_escape_string(objpath, None, False)
.replace(".", "%2E")
.replace("-", "%2D")
.replace("~", "%7E")
.replace("_", "%5F")
.replace("%", "_"))
def unescape_object_path(objpath):
return GLib.uri_unescape_string(objpath.replace("_", "%"))
def encode_msg(msg):
try:
text = json.dumps(msg)
except ValueError:
return 0
data = text.encode("utf-8")
length_bytes = struct.pack("@i", len(data))
written = sys.stdout.write(length_bytes) + sys.stdout.write(data)
# We flush to make sure that Chrome gets the message *right now*
sys.stdout.flush()
return written
def decode_msg():
# Read the message length (first 4 bytes).
length_bytes = sys.stdin.read(4)
if len(length_bytes) < 4:
raise ValueError("unexpected end of input")
# Unpack message length as 4 byte integer.
length = struct.unpack('@i', length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(length).decode("utf-8")
return json.loads(text)
class DBusService:
def __init__(self, conn, name, path, flags=Gio.BusNameOwnerFlags.NONE):
self._conn = conn
self._name = name
self._path = path
self.__reg_ids = []
self._properties = {}
self._methods = {
# "org.freedesktop.DBus.Properties": {
# "Get": ("ss", ("v",)),
# "GetAll": ("s", ("a{sv}",)),
# "Set": ("ssv", ()),
# }
}
node_info = Gio.DBusNodeInfo.new_for_xml(self.__doc__)
for iface in node_info.interfaces:
self._methods[iface.name] = {
meth.name: (tuple(a.signature for a in meth.out_args),
tuple(a.signature for a in meth.in_args))
for meth in iface.methods
}
self._properties[iface.name] = {
prop.name: prop.signature
for prop in iface.properties
if prop.flags & Gio.DBusPropertyInfoFlags.READABLE
}
self.__reg_ids.append(
self._conn.register_object(path, iface, self.on_method_call)
)
self.__own_id = Gio.bus_own_name_on_connection(self._conn, name, flags)
def unpublish(self):
for i in self.__reg_ids:
self._conn.unregister_object(i)
Gio.bus_unown_name(self.__own_id)
self._conn.close_sync()
def on_method_call(self, conn, sender, objpath, iface_name, method_name,
params, invocation):
# FIXME: move somewhere else
if iface_name == "org.freedesktop.DBus.Properties":
if method_name == "Get":
self.get_property(conn, sender, objpath, *params, invocation)
elif method_name == "GetAll":
self.get_all_properties(conn, sender, objpath, *params,
invocation)
elif method_name == "Set":
self.set_property(conn, sender, objpath, *params, invocation)
return
in_args, out_args = self._methods[iface_name][method_name]
fd_list = invocation.get_message().get_unix_fd_list()
args = [fd_list.get(a) if sig == "h" else a
for a, sig in zip(params.unpack(), in_args)]
try:
res = getattr(self, method_name)(*args)
if not out_args:
res = None
elif len(out_args) == 1:
res = GLib.Variant("(%s)" % "".join(out_args), (res,))
else:
res = GLib.Variant("(%s)" % "".join(out_args), res)
invocation.return_value(res)
except Exception as e:
e_type = type(e).__name__
if "." not in e_type:
e_type = "org.python." + e_type
invocation.return_dbus_error(e_type, str(e))
def get_property(self, conn, sender, objpath, iface_name, prop_name,
invocation):
typ = self._properties[iface_name][prop_name]
variant = GLib.Variant(typ, getattr(self, prop_name))
invocation.return_value(GLib.Variant("(v)", (variant,)))
def get_all_properties(self, conn, sender, objpath, iface_name,
invocation):
all_props = {p: GLib.Variant(t, getattr(self, p))
for p, t in self._properties[iface_name].items()}
invocation.return_value(GLib.Variant("(a{sv})", (all_props,)))
def set_property(self, conn, sender, objpath, iface_name, prop_name, value,
invocation):
setattr(self, prop_name, value)
invocation.return_value(None)
# SIGNALS
def PropertiesChanged(self, iface_name, changed_props, invalidated_props):
# we assume readable properties
typed_changed_props = {
p: GLib.Variant(self._properties[iface_name][p], v)
for p, v in changed_props.items()
}
self._conn.emit_signal(
None,
self._path,
"org.freedesktop.DBus.Properties",
"PropertiesChanged",
GLib.Variant.new_tuple(
GLib.Variant("s", iface_name),
GLib.Variant("a{sv}", typed_changed_props),
GLib.Variant("as", invalidated_props)))
class MediaPlayer2(DBusService):
"""
<node>
<interface name="org.mpris.MediaPlayer2">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
<method name="Raise"/>
<method name="Quit"/>
<property name="Identity" type="s" access="read"/>
<!--
<property name="DesktopEntry" type="s" access="read">
<annotation name="org.mpris.MediaPlayer2.property.optional" value="true"/>
</property>
-->
<property name="CanRaise" type="b" access="read"/>
<property name="CanQuit" type="b" access="read"/>
<property name="Fullscreen" type="b" access="readwrite"/>
<property name="CanSetFullscreen" type="b" access="read"/>
<property name="SupportedUriSchemes" type="as" access="read"/>
<property name="SupportedMimeTypes" type="as" access="read"/>
<property name="HasTrackList" type="b" access="read"/>
</interface>
<interface name="org.mpris.MediaPlayer2.Player">
<method name="Play"/>
<method name="Pause"/>
<method name="PlayPause"/>
<method name="Stop"/>
<method name="Next"/>
<method name="Previous"/>
<method name="Seek">
<arg direction="in" type="x" name="Offset"/>
</method>
<method name="SetPosition">
<arg direction="in" type="o" name="TrackId"/>
<arg direction="in" type="x" name="Position"/>
</method>
<method name="OpenUri">
<arg direction="in" type="s" name="Uri"/>
</method>
<property name="PlaybackStatus" type="s" access="read"/>
<property name="Position" type="x" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
</property>
<property name="Metadata" type="a{sv}" access="read"/>
<property name="Volume" type="d" access="readwrite"/>
<property name="Rate" type="d" access="readwrite"/>
<property name="MinimumRate" type="d" access="read"/>
<property name="MaximumRate" type="d" access="read"/>
<property name="CanGoNext" type="b" access="read"/>
<property name="CanGoPrevious" type="b" access="read"/>
<property name="CanPlay" type="b" access="read"/>
<property name="CanPause" type="b" access="read"/>
<property name="CanSeek" type="b" access="read"/>
<property name="CanControl" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
</property>
<property name="Shuffle" type="b" access="readwrite">
<annotation name="org.mpris.MediaPlayer2.property.optional" value="true"/>
</property>
<property name="LoopStatus" type="s" access="readwrite">
<annotation name="org.mpris.MediaPlayer2.property.optional" value="true"/>
</property>
<signal name="Seeked">
<arg name="Position" type="x"/>
</signal>
</interface>
</node>
"""
def __init__(self, conn, tabid, name, objpath):
self.__tabid = tabid
self.__callbacks = defaultdict(list)
self.CanRaise = False
self.CanQuit = False
self.SupportedUriSchemes = ["http", "https", "ftp", "file"]
self.SupportedMimeTypes = [
"audio/mpeg",
"audio/x-flac",
# TODO: add more
]
self.HasTrackList = False
self.Fullscreen = False
self.Metadata = {}
self.PlaybackStatus = "Stopped"
self.Rate = 1
self.Volume = 1
self.Shuffle = False
self.LoopStatus = "None"
super().__init__(conn, name, objpath)
def _set_callback_on(self, prop, callback):
self.__callbacks[prop].append(callback)
# PROPERTIES
def get_property(self, conn, sender, objpath, iface_name, prop_name,
invocation):
if (iface_name == "org.mpris.MediaPlayer2.Player"
and prop_name == "Position"):
def callback(pos):
variant = GLib.Variant("x", pos)
invocation.return_value(GLib.Variant("(v)", (variant,)))
self._set_callback_on("position", callback)
self._send_message("query", "position")
else:
super().get_property(conn, sender, objpath, iface_name, prop_name,
invocation)
def get_all_properties(self, conn, sender, objpath, iface_name,
invocation):
if iface_name == "org.mpris.MediaPlayer2.Player":
non_async = {p: GLib.Variant(t, getattr(self, p))
for p, t in self._properties[iface_name].items()
if p != "Position"}
def callback(pos):
non_async["Position"] = GLib.Variant("x", pos)
invocation.return_value(GLib.Variant("(a{sv})", (non_async,)))
self._set_callback_on("position", callback)
self._send_message("query", "position")
else:
super().get_all_properties(conn, sender, objpath, iface_name,
invocation)
def set_property(self, conn, sender, objpath, iface_name, prop_name, value,
invocation):
if prop_name in ("Fullscreen", "Volume", "LoopStatus", "Shuffle", "Rate"):
self._send_message(prop_name, value)
else:
setattr(self, prop_name, value)
invocation.return_value(None)
# SIGNALS
def Seeked(self, position):
self._conn.emit_signal(
None,
# FIXME: don't hardcode these
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player",
"Seeked",
GLib.Variant.new_tuple(GLib.Variant("x", position)))
# METHODS
def Raise(self):
pass
def Quit(self):
pass
def OpenUri(self, url):
pass
def Play(self):
self._send_message("Play")
def Pause(self):
self._send_message("Pause")
def PlayPause(self):
self._send_message("PlayPause")
def Stop(self):
self._send_message("Stop")
def Seek(self, offset):
self._send_message("Seek", offset)
def SetPosition(self, trackid, position):
if trackid != "/org/mpris/MediaPlayer2/TrackList/NoTrack":
ytid = unescape_object_path(trackid[4:])
self._send_message("SetPosition",
{"id": ytid, "position": position})
def Next(self):
self._send_message("Next")
def Previous(self):
self._send_message("Prev")
def _send_message(self, cmd, data=None):
msg = {
"tabId": self.__tabid,
"cmd": cmd,
}
if data is not None:
msg["data"] = data
encode_msg(msg)
def _handle_msg(self, msg):
changes = []
for key, val in msg["data"].items():
if key == "id":
track_path = "/ID/" + escape_object_path(val)
self.Metadata["mpris:trackid"] = GLib.Variant("o", track_path)
changes.append("Metadata")
elif key == "url":
self.Metadata["xesam:url"] = GLib.Variant("s", val)
changes.append("Metadata")
elif key == "thumb":
self.Metadata["mpris:artUrl"] = GLib.Variant("s", val)
changes.append("Metadata")
elif key == "title":
self.Metadata["xesam:title"] = GLib.Variant("s", val)
changes.append("Metadata")
elif key == "duration":
self.Metadata["mpris:length"] = GLib.Variant("x", val)
changes.append("Metadata")
elif key == "position":
pass
# Position should *not* emit a Changed signal
elif key == "seekedTo":
self.Seeked(val)
else:
setattr(self, key, val)
changes.append(key)
if key in self.__callbacks:
for cb in self.__callbacks[key]:
cb(val)
del self.__callbacks[key]
if "Fullscreen" in changes:
changes.remove("Fullscreen")
self.PropertiesChanged("org.mpris.MediaPlayer2",
{"Fullscreen": self.Fullscreen}, [])
if changes:
self.PropertiesChanged("org.mpris.MediaPlayer2.Player",
{c: getattr(self, c) for c in changes}, [])
class Youtube(MediaPlayer2):
# FIXME:
__doc__ = MediaPlayer2.__doc__
def __init__(self, conn, tabid, name, objpath):
super().__init__(conn, tabid, name, objpath)
self.Identity = "youtube"
self.CanControl = True
self.CanPlay = True
self.CanPause = True
self.CanSeek = True
self.CanSetFullscreen = False
self.MinimumRate = 0.25
self.MaximumRate = 2
# these are set correctly on song change
self.CanGoNext = False
self.CanGoPrevious = False
self.Shuffle = False
self.LoopStatus = "None"
def main():
mainloop = GLib.MainLoop()
make_streams_binary()
players = {}
def message_handler(chan, condition):
msg = decode_msg()
debug(msg)
if msg["type"] not in ("change", "update", "quit"):
return True
tabid = msg["tabId"]
try:
player = players[tabid]
except KeyError:
# Many terrible things can happen to tabs; they can crash or be
# discarded. For these cases out background.js should still inform
# us. However it may be that that tab has already quit e.g. it may
# be in YouTube's main page when it crashes. In these cases we
# don't want to create a player just to immediately destroy it.
if msg["type"] == "quit":
return True
connflags = (Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT
| Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION)
addr = Gio.dbus_address_get_for_bus_sync(Gio.BusType.SESSION)
conn = Gio.DBusConnection.new_for_address_sync(addr, connflags)
conn.set_exit_on_close(True)
name = "org.mpris.MediaPlayer2.chrome"
if players:
# if we are exposing more than one player we need to give them
# unique names
name += ".tab%d" % tabid
player = Youtube(conn, tabid, name, "/org/mpris/MediaPlayer2")
players[tabid] = player
if msg["type"] == "change":
player._handle_msg(msg)
if msg["type"] == "update":
player._handle_msg(msg)
if msg["type"] == "quit":
players[tabid].unpublish()
del players[tabid]
# otherwise GLib will remove our watch
return True
chan = GLib.IOChannel.unix_new(sys.stdin.fileno())
chan.add_watch(GLib.IOCondition.IN, message_handler)
chan.add_watch(GLib.IOCondition.HUP, lambda *_: mainloop.quit())
mainloop.run()
if __name__ == '__main__':
main()