forked from eonpatapon/mpDris2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpDris2
executable file
·945 lines (825 loc) · 33 KB
/
mpDris2
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
#!/usr/bin/env python
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Erik Karlsson <pilo@ayeon.org>, Jean-Philippe Braun <eon@patapon.info>
# Some bits taken from quodlibet mpris plugin by <christoph.reiter@gmx.at>
import os
import sys
import re
import shlex
import signal
import socket
import getopt
import mpd
import gobject
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
import ConfigParser
import logging
identity = "Music Player Daemon"
params = {
'host': 'localhost',
'port': 6600,
'password': None,
'progname': sys.argv[0],
'music_dir': '',
'mmkeys': True,
'notify': True,
}
try:
import pynotify
except:
params['notify'] = False
notification = None
# MPRIS allowed metadata tags
allowed_tags = {
'mpris:trackid': str,
'mpris:length': long,
'mpris:artUrl': str,
'xesam:album': str,
'xesam:albumArtist': list,
'xesam:artist': list,
'xesam:asText': str,
'xesam:audioBPM': int,
'xesam:comment': list,
'xesam:composer': list,
'xesam:contentCreated': str,
'xesam:discNumber': int,
'xesam:firstUsed': str,
'xesam:genre': list,
'xesam:lastUsed': str,
'xesam:lyricist': str,
'xesam:title': str,
'xesam:trackNumber': int,
'xesam:url': str,
'xesam:useCount': int,
'xesam:userRating': float,
}
# python dbus bindings don't include annotations and properties
MPRIS2_INTROSPECTION = \
"""<node name="/org/mpris/MediaPlayer2">
<interface name="org.freedesktop.DBus.Introspectable">
<method name="Introspect">
<arg direction="out" name="xml_data" type="s"/>
</method>
</interface>
<interface name="org.freedesktop.DBus.Properties">
<method name="Get">
<arg direction="in" name="interface_name" type="s"/>
<arg direction="in" name="property_name" type="s"/>
<arg direction="out" name="value" type="v"/>
</method>
<method name="GetAll">
<arg direction="in" name="interface_name" type="s"/>
<arg direction="out" name="properties" type="a{sv}"/>
</method>
<method name="Set">
<arg direction="in" name="interface_name" type="s"/>
<arg direction="in" name="property_name" type="s"/>
<arg direction="in" name="value" type="v"/>
</method>
<signal name="PropertiesChanged">
<arg name="interface_name" type="s"/>
<arg name="changed_properties" type="a{sv}"/>
<arg name="invalidated_properties" type="as"/>
</signal>
</interface>
<interface name="org.mpris.MediaPlayer2">
<method name="Raise"/>
<method name="Quit"/>
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
<property name="CanQuit" type="b" access="read"/>
<property name="CanRaise" type="b" access="read"/>
<property name="HasTrackList" type="b" access="read"/>
<property name="Identity" type="s" access="read"/>
<property name="DesktopEntry" type="s" access="read"/>
<property name="SupportedUriSchemes" type="as" access="read"/>
<property name="SupportedMimeTypes" type="as" access="read"/>
</interface>
<interface name="org.mpris.MediaPlayer2.Player">
<method name="Next"/>
<method name="Previous"/>
<method name="Pause"/>
<method name="PlayPause"/>
<method name="Stop"/>
<method name="Play"/>
<method name="Seek">
<arg direction="in" name="Offset" type="x"/>
</method>
<method name="SetPosition">
<arg direction="in" name="TrackId" type="o"/>
<arg direction="in" name="Position" type="x"/>
</method>
<method name="OpenUri">
<arg direction="in" name="Uri" type="s"/>
</method>
<signal name="Seeked">
<arg name="Position" type="x"/>
</signal>
<property name="PlaybackStatus" type="s" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="LoopStatus" type="s" access="readwrite">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="Rate" type="d" access="readwrite">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="Shuffle" type="b" access="readwrite">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="Metadata" type="a{sv}" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="Volume" type="d" access="readwrite">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
</property>
<property name="Position" type="x" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
</property>
<property name="MinimumRate" type="d" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="MaximumRate" type="d" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="CanGoNext" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="CanGoPrevious" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="CanPlay" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="CanPause" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="CanSeek" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="true"/>
</property>
<property name="CanControl" type="b" access="read">
<annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
</property>
</interface>
<interface name='org.mpris.MediaPlayer2.Playlists'>
<method name='ActivatePlaylist'>
<arg direction='in' name='PlaylistId' type='o'/>
</method>
<method name='GetPlaylists'>
<arg direction='in' name='Index' type='u'/>
<arg direction='in' name='MaxCount' type='u'/>
<arg direction='in' name='Order' type='s'/>
<arg direction='in' name='ReverseOrder' type='b'/>
<arg direction='out' name='Playlists' type='a(oss)'/>
</method>
<property name='PlaylistCount' type='u' access='read'/>
<property name='Orderings' type='as' access='read'/>
<property name='ActivePlaylist' type='(b(oss))' access='read'/>
</interface>
</node>"""
# Default url handlers if MPD doesn't support 'urlhandlers' command
urlhandlers = [ 'http://' ]
downloaded_covers = [ '.covers/%s-%s.jpg' ]
local_covers = [ 'cover.jpg', 'album.jpg', 'front.jpg', 'folder.jpg',
'.folder.jpg', '.folder.png', 'AlbumArt.jpg', 'AlbumArtSmall.jpg' ]
# Wrapper to handle socket errors and similar
class MPDWrapper(mpd.MPDClient):
def __init__(self, params):
mpd.MPDClient.__init__(self)
self._dbus = dbus
self._params = params
self._monitor = False
self._status = False
self._position = 0
self._dbus_service = False
self._errors = 0
# init mmkeys, if configured
if self._params['mmkeys']:
try:
gsd_object = dbus.SessionBus().get_object('org.gnome.SettingsDaemon',
'/org/gnome/SettingsDaemon/MediaKeys')
# this is what gives us the multi media keys.
gsd_object.GrabMediaPlayerKeys('mpDris2', 0,
dbus_interface='org.gnome.SettingsDaemon.MediaKeys')
# connect_to_signal registers our callback function.
gsd_object.connect_to_signal('MediaPlayerKeyPressed', self.on_mediakey)
except:
logger.error('Failed to connect to GNOME Settings Daemon.' \
' Disabling multimedia key support')
params['mmkeys'] = False
def run(self):
""" Try to connect to MPD """
if self.my_connect():
# If connection fail retry in 5 seconds
gobject.timeout_add(5000, self.my_connect)
def detach_dbus(self):
# Release the Dbus name
self._dbus_service.release_name();
# Disconnect service from the session bus
self._dbus_service.remove_from_connection();
# Stop monitoring
gobject.source_remove(self._monitor)
def my_connect(self):
""" Init MPD connection """
try:
# Clean mpd client state
self._reset()
# Connect to host
self.connect(self._params['host'], self._params['port'])
if params['password']:
self.password(self._params['password'])
# Get URL handlers supported by MPD
if 'urlhandlers' in self.commands():
urlhandlers = self.urlhandlers()
if self._errors > 0:
notification.rnotify(identity, 'Reconnected')
logger.debug('Reconnected to MPD server.')
else:
logger.debug('Connected to MPD server.')
# Make the socket non blocking to detect deconnections
self._sock.settimeout(5.0)
# Export our DBUS service
if not self._dbus_service:
self._dbus_service = MPRISInterface(self._params['music_dir'])
else:
# Add our service to the session bus
self._dbus_service.add_to_connection(dbus.SessionBus(),
'/org/mpris/MediaPlayer2')
self._dbus_service.aquire_name()
# Init internal state to throw events at start
self.init_state()
# Add periodic status check for sending MPRIS events
self._monitor = gobject.timeout_add(1000, self.monitor)
# Reset error counter
self._errors = 0
# Return False to stop trying to connect
return False
except socket.error as e:
self._errors += 1
if self._errors < 6:
logger.error('Could not connect to MPD: %s' % e)
if self._errors == 6:
logger.info('Continue to connect but going silent')
return True
except mpd.CommandError as e:
logger.error('MPD command error: %s' % e)
return True
def init_state(self):
# Get current state
self._status = self.status()
# Invalid some fields to throw events at start
self._status['state'] = 'invalid'
self._status['songid'] = '-1'
self._position = 0
def monitor(self):
old_status = self._status
old_position = self._position
try:
self._status = self.status()
if 'time' in self._status:
self._position = int(self._status['time'].split(':')[0])
else:
self._position = 0
except (socket.error, mpd.MPDError):
logger.warning("Disconnected")
notification.rnotify(identity, 'Disconnected', 'error')
self.detach_dbus()
# Try to reconnect
self.run()
if self._status['state'] != 'stop' and old_status['state'] != 'stop':
if old_status['songid'] != self._status['songid']:
metadata = self._dbus_service.update_property('org.mpris.MediaPlayer2.Player', 'Metadata')
if self._params['notify']:
uri = 'sound'
if 'mpris:artUrl' in metadata:
uri = metadata['mpris:artUrl']
title = 'Unknown Title'
if 'xesam:title' in metadata:
title = metadata['xesam:title']
artist = 'Unknown Artist'
if 'xesam:artist' in metadata:
artist = metadata['xesam:artist'][0]
notification.notify(title, 'by %s' % artist, uri)
if (abs(self._position - old_position) > 2 and \
old_status['songid'] == self._status['songid']) or \
old_status['songid'] == '-1':
self._dbus_service.Seeked(self._position * 1000000)
if old_status['volume'] != self._status['volume']:
self._dbus_service.update_property('org.mpris.MediaPlayer2.Player', 'Volume')
if old_status['state'] != self._status['state']:
self._dbus_service.update_property('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')
if old_status['random'] != self._status['random']:
self._dbus_service.update_property('org.mpris.MediaPlayer2.Player', 'Shuffle')
if old_status['repeat'] != self._status['repeat']:
self._dbus_service.update_property('org.mpris.MediaPlayer2.Player', 'LoopStatus')
# Return True to continue polling
return True
def on_mediakey(self, appname, key):
""" GNOME media key handler """
self.monitor() # for zipping faster than 1s
status = self._status['state']
logger.debug('Got GNOME mmkey "%s" for "%s" (%s)' % (key, appname, status))
if key in ['Play', 'Pause', 'PlayPause']: # vendor specific
if status == 'play':
notification.rnotify(identity, 'Paused')
self.pause()
else:
notification.rnotify(identity, 'Playing')
self.play()
elif key == 'Next':
self.next()
elif key == 'Previous':
self.previous()
elif key == 'Stop':
notification.rnotify(identity, 'Stopped')
self.stop()
else:
logger.debug('Unhandled')
class Notify:
def __init__(self, params):
""" Init the notification system """
if params['notify']:
if pynotify.init(identity):
self._notification = pynotify.Notification("", "", "")
self._expired = True
else:
logger.error('Failed to init libnotify; disabling' \
'notifications')
self._notification = False
else:
self._notification = False
def notify(self, title, body, uri = ''):
""" Issue a new notification """
if self._notification:
if self._expired:
self._notification = pynotify.Notification(title, body, uri)
self._expired = False
self._notification.connect('closed', self.handle_closed)
self._notification.show()
else:
self.rnotify(title, body, uri)
def rnotify(self, title, body, uri = ''):
""" Replace current notification """
if self._notification:
self._notification.update(title, body, uri)
self._notification.show()
def handle_closed(self, n):
""" Honor expiration on Unity and Gnome3 """
self._expired = True
class MPRISInterface(dbus.service.Object):
''' The base object of an MPRIS player '''
__name = "org.mpris.MediaPlayer2.mpd"
__path = "/org/mpris/MediaPlayer2"
__introspect_interface = "org.freedesktop.DBus.Introspectable"
__prop_interface = dbus.PROPERTIES_IFACE
def __init__(self, bus, path = ""):
dbus.service.Object.__init__(self, dbus.SessionBus(),
MPRISInterface.__path)
self.path = path
self.aquire_name()
def on_name_aquired(self, owner):
""" gracefully quit if our name is taken, thus
thus avoid running multiple instances """
if owner != self._unique:
self.Quit()
def aquire_name(self):
self._bus_name = dbus.service.BusName(MPRISInterface.__name,
dbus.SessionBus(), True, True) # force this instance
self._unique = self.connection.get_name_owner(self.__name)
self._bus_watcher = dbus.bus.NameOwnerWatch(dbus.SessionBus(),
MPRISInterface.__name, self.on_name_aquired)
def release_name(self):
del self._bus_name
__root_interface = "org.mpris.MediaPlayer2"
__root_props = {
"CanQuit": (True, None),
"CanRaise": (False, None),
"DesktopEntry": ("mpDris2", None),
"HasTrackList": (False, None),
"Identity": (identity, None),
"SupportedUriSchemes": (dbus.Array(signature="s"), None),
"SupportedMimeTypes": (dbus.Array(signature="s"), None)
}
def __get_playback_status():
status = mpd_wrapper.status()
return {'play': 'Playing', 'pause': 'Paused', 'stop': 'Stopped'}[status['state']]
def __set_loop_status(value):
if str(value) == "Playlist":
mpd_wrapper.repeat(1)
elif str(value) == "None":
mpd_wrapper.repeat(0)
else:
raise dbus.exceptions.DBusException("Loop mode not supported")
return
def __get_loop_status():
status = mpd_wrapper.status()
return ("None", "Playlist")[int(status['repeat'])]
def __set_shuffle(value):
mpd_wrapper.random(value)
return
def __get_shuffle():
if mpd_wrapper.status()['random'] == '1':
return True
else:
return False
def __get_metadata():
return format_metadata(mpd_wrapper.currentsong())
def __get_volume():
vol = float(mpd_wrapper.status()['volume'])
if vol > 0:
return vol / 100
else:
return 0
def __set_volume(value):
if value >= 0 and value <= 1:
mpd_wrapper.setvol(int(value * 100))
return
def __get_position():
status = mpd_wrapper.status()
if 'time' in status:
current, end = status['time'].split(':')
return dbus.Int64((int(current) * 1000000))
else:
return dbus.Int64(0)
def __can_next():
if 'nextsongid' in mpd_wrapper.status():
return True
else:
return False
__player_interface = "org.mpris.MediaPlayer2.Player"
__player_props = {
"PlaybackStatus": (__get_playback_status, None),
"LoopStatus": (__get_loop_status, __set_loop_status),
#~ "Rate": (1.0, None),
"Shuffle": (__get_shuffle, __set_shuffle),
"Metadata": (__get_metadata, None),
"Volume": (__get_volume, __set_volume),
"Position": (__get_position, None),
#~ "MinimumRate": (1.0, None),
#~ "MaximumRate": (1.0, None),
"CanGoNext": (__can_next, None),
"CanGoPrevious": (True, None),
"CanPlay": (True, None),
"CanPause": (True, None),
"CanSeek": (True, None),
"CanControl": (True, None),
}
# __tracklist_interface = "org.mpris.MediaPlayer2.TrackList"
# TODO Implement TrackList
def __get_playlist_count():
return len(mpd_wrapper.listplaylists())
def __get_orderings():
orderings = dbus.Array(signature='s')
orderings.append(dbus.String('Alphabetical'))
return orderings
def __get_active_playlist():
"""
MPD has currently no way to tell the active playlist.
"""
nope = dbus.Struct([dbus.Boolean(False),
dbus.Struct([
dbus.ObjectPath('/'),
dbus.String(''),
dbus.String('')])
])
return nope
__playlists_interface = "org.mpris.MediaPlayer2.Playlists"
__playlists_props = {
"PlaylistCount": (__get_playlist_count, None),
"Orderings": (__get_orderings, None),
"ActivePlaylist": (__get_active_playlist, None)
}
__prop_mapping = {
__player_interface: __player_props,
__root_interface: __root_props,
#~ __tracklist_interface: __tracklist_props,
__playlists_interface: __playlists_props}
@dbus.service.method(__introspect_interface)
def Introspect(self):
return MPRIS2_INTROSPECTION
@dbus.service.signal(__prop_interface, signature="sa{sv}as")
def PropertiesChanged(self, interface, changed_properties,
invalidated_properties):
pass
@dbus.service.method(__prop_interface,
in_signature="ss", out_signature="v")
def Get(self, interface, prop):
getter, setter = self.__prop_mapping[interface][prop]
if callable(getter):
return getter()
return getter
@dbus.service.method(__prop_interface,
in_signature="ssv", out_signature="")
def Set(self, interface, prop, value):
getter, setter = self.__prop_mapping[interface][prop]
if setter is not None:
setter(value)
@dbus.service.method(__prop_interface,
in_signature="s", out_signature="a{sv}")
def GetAll(self, interface):
read_props = {}
props = self.__prop_mapping[interface]
for key, (getter, setter) in props.iteritems():
if callable(getter): getter = getter()
read_props[key] = getter
return read_props
def update_property(self, interface, prop):
getter, setter = self.__prop_mapping[interface][prop]
if callable(getter):
value = getter()
else:
value = getter
logger.debug('Updated property: %s = %s' % (prop, value))
self.PropertiesChanged(interface, {prop: value}, [])
return value
# Root methods
@dbus.service.method(__root_interface, in_signature='', out_signature='')
def Raise(self):
return
@dbus.service.method(__root_interface, in_signature='', out_signature='')
def Quit(self):
logger.debug('Quit requested')
loop.quit()
return
# Player methods
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def Next(self):
mpd_wrapper.next()
return
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def Previous(self):
mpd_wrapper.previous()
return
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def Pause(self):
mpd_wrapper.pause()
notification.rnotify(identity, 'Paused')
return
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def PlayPause(self):
status = mpd_wrapper.status()
if status['state'] == 'play':
mpd_wrapper.pause()
notification.rnotify(identity, 'Paused')
else:
mpd_wrapper.play()
notification.rnotify(identity, 'Playing')
return
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def Stop(self):
mpd_wrapper.stop()
notification.rnotify(identity, 'Stopped')
return
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def Play(self):
mpd_wrapper.play()
notification.notify(identity, 'Playing')
return
@dbus.service.method(__player_interface, in_signature='x', out_signature='')
def Seek(self, offset):
status = mpd_wrapper.status()
current, end = status['time'].split(':')
current = int(current)
end = int(end)
offset = int(offset) / 1000000
if current + offset <= end:
position = current + offset
if position < 0: position = 0
mpd_wrapper.seekid(int(status['songid']), position)
self.Seeked(position * 1000000)
return
@dbus.service.method(__player_interface, in_signature='ox', out_signature='')
def SetPosition(self, trackid, position):
song = mpd_wrapper.currentsong()
# FIXME: use real dbus objects
if str(trackid) != '/org/mpris/MediaPlayer2/Track/%s' % song['id']: return
# Convert position to seconds
position = int(position) / 1000000
if position <= int(song['time']):
mpd_wrapper.seekid(int(song['id']), position)
self.Seeked(position * 1000000)
return
@dbus.service.signal(__player_interface, signature='x')
def Seeked(self, position):
logger.debug("Seeked to %i" % position)
return float(position)
@dbus.service.method(__player_interface, in_signature='', out_signature='')
def OpenUri(self):
# TODO
return
# Playlists methods
@dbus.service.method(__playlists_interface, in_signature = 'o', out_signature = '')
def ActivatePlaylist(self, requested):
logger.debug('ActivatePlaylist(%s)' % requested)
try:
playlists = self.GetPlaylists(0, 10, '', 0)
for playlist in playlists:
if playlist[0] == requested:
mpd_wrapper.stop()
mpd_wrapper.clear()
mpd_wrapper.load(playlist[1])
mpd_wrapper.play()
break
except:
logger.error('Can not activate playlist %s' % requested)
return
@dbus.service.method(__playlists_interface, in_signature = 'uusb', out_signature = 'a(oss)')
def GetPlaylists(self, index, maxcount, order, reverseorder):
#TODO: do not ignore order & reverseorder
playlists = mpd_wrapper.listplaylists()
i = 0
a = dbus.Array(signature='(oss)')
for playlist in playlists:
if i >= index and i <= index + maxcount:
b = dbus.Struct(
[dbus.ObjectPath("/org/mpris/MediaPlayer2/Playlist/%s" % i),
dbus.String(playlist['playlist']), dbus.String('')])
a.append(b)
i += 1
return a
# Handle signals more gracefully
def handle_sigint(signum, frame):
logger.debug('Caught SIGINT, exiting.')
loop.quit()
def format_metadata(metadata):
"""http://xmms2.org/wiki/MPRIS_Metadata"""
metadata['mpris:trackid'] = "/org/mpris/MediaPlayer2/Track/%s" % metadata['id']
if 'time' in metadata:
metadata['mpris:length'] = int(metadata['time']) * 1000000
if 'date' in metadata:
if len(metadata['date']) is 4:
metadata['xesam:contentCreated'] = metadata['date']
else:
metadata['xesam:contentCreated'] = metadata['date'][0:4]
if 'track' in metadata:
if re.match('^([0-9]+).*', metadata['track']):
metadata['xesam:trackNumber'] = int(re.match('^([0-9]+).*',
metadata['track']).group(1))
else:
metadata['xesam:trackNumber'] = 0
if 'disc' in metadata:
metadata['xesam:discNumber'] = int(re.match('^([0-9]+).*',
metadata['disc']).group(1))
if 'artist' in metadata:
metadata['xesam:artist'] = [metadata['artist'],]
if 'composer' in metadata:
metadata['xesam:composer'] = [metadata['composer'],]
mpd_tags = ('album', 'title')
for tag in mpd_tags:
if tag in metadata:
metadata['xesam:%s' % tag] = metadata[tag]
if 'file' in metadata:
file = metadata['file']
if len([ x for x in urlhandlers if file.startswith(x) ]) == 0:
file = os.path.join(params['music_dir'], file)
metadata['xesam:url'] = file
if file.startswith('file://'):
basedirpath = os.path.dirname(file).replace('file://', '')
cover = False
for f in os.listdir(basedirpath):
if f in local_covers:
cover = 'file://' + os.path.join(basedirpath, f)
if not cover and 'artist' in metadata and 'album' in metadata:
for f in downloaded_covers:
f = os.path.expanduser(os.path.join('~', f % \
(metadata['artist'], metadata['album'])))
if os.path.exists(f):
cover = 'file://' + f
if cover:
metadata['mpris:artUrl'] = cover
# Stream: populate some missings tags with stream's name
if 'name' in metadata:
if 'xesam:title' not in metadata:
metadata['xesam:title'] = metadata['name']
elif 'xesam:album' not in metadata:
metadata['xesam:album'] = metadata['name']
surplus_tags = set(metadata.keys()).difference(set(allowed_tags.keys()))
# Remove surplus tags
for tag in surplus_tags:
del metadata[tag]
# Cast metadata to the correct type, or discard it
for key, value in metadata.items():
try:
metadata[key] = allowed_tags[key](value)
except ValueError:
del metadata[key]
logger.error("Can't cast value %s to %s" % \
(value, allowed_tags[key]))
return dbus.Dictionary(metadata, signature='sv')
def find_music_dir():
if 'XDG_MUSIC_DIR' in os.environ:
return os.environ['XDG_MUSIC_DIR']
conf = os.path.expanduser('~/.config/user-dirs.dirs')
try:
for line in open(conf, 'r'):
if not line.startswith('XDG_MUSIC_DIR='):
continue
# use shlex to handle "shell escaping"
path = shlex.split(line)[0][14:]
if path.startswith('$HOME/'):
return os.path.expanduser('~' + path[5:])
elif path.startswith('/'):
return path
else:
continue # other forms are not supported
except IOError:
pass
paths = '~/Music', '~/music'
for path in map(os.path.expanduser, paths):
if os.path.isdir(path):
return path
return None
def usage(params):
print """\
Usage: %(progname)s [OPTION]... [MPD_HOST] [MPD_PORT]
Note: Environment variables MPD_HOST and MPD_PORT can be used instead of above
arguments.
-p, --path=PATH Sets the library path of MPD to PATH
-d, --debug Run in debug mode
Default: MPD_HOST: %(host)s, MPD_PORT: %(port)s
Report bugs to https://github.com/eonpatapon/mpDris2/issues""" % params
if __name__ == '__main__':
DBusGMainLoop(set_as_default=True)
path = find_music_dir()
config = ConfigParser.SafeConfigParser()
config.read(['/etc/mpDris2.conf', os.path.expanduser('~/.config/mpDris2/mpDris2.conf')])
if config.has_option('Connection', 'host'):
params['host'] = config.get('Connection', 'host')
if config.has_option('Connection', 'port'):
params['port'] = config.get('Connection', 'port')
if config.has_option('Connection', 'password'):
params['password'] = config.get('Connection', 'password')
if 'MPD_HOST' in os.environ:
params['host'] = os.environ['MPD_HOST']
if 'MPD_PORT' in os.environ:
params['port'] = os.environ['MPD_PORT']
try:
(opts, args) = getopt.getopt(sys.argv[1:], 'hdp:', ['help', 'debug', 'path='])
except getopt.GetoptError, (msg, opt):
print sys.argv[0] + ': ' + msg
print
usage(params)
sys.exit(2)
log_format = '%(asctime)s %(module)s %(levelname)s: %(message)s'
log_level = logging.INFO
for (opt, arg) in opts:
if opt in ['-h', '--help']:
usage(params)
sys.exit()
elif opt in ['-p', '--path']:
path = arg
elif opt in ['-d', '--debug']:
log_level = logging.DEBUG
logging.basicConfig(format=log_format, level=log_level)
logger = logging.getLogger('mpDris2')
if len(args) > 2:
usage(params)
sys.exit()
for arg in args[:2]:
if arg.isdigit():
params['port'] = arg
else:
params['host'] = arg
if '@' in params['host']:
params['password'], params['host'] = params['host'].split('@', 1)
if path:
logger.info('Using %s as music library path' % path)
if not path.startswith('file://'):
params['music_dir'] = 'file://' + path
else:
logger.warning('By not supplying a path for the music library ' \
'this program will break the MPRIS specification!')
for bling in ['mmkeys','notify']:
if config.has_option('Bling', bling):
params[bling] = config.getboolean('Bling', bling)
loop = gobject.MainLoop()
signal.signal(signal.SIGINT, handle_sigint)
# Wrapper to send notifications
notification = Notify(params)
# Create wrapper to handle connection failures with MPD more gracefully
mpd_wrapper = MPDWrapper(params)
mpd_wrapper.run()
# Run idle loop
loop.run()
# Clean up
try:
mpd_wrapper.close()
mpd_wrapper.disconnect()
mpd_wrapper.detach_dbus()
logger.debug('Exiting')
except mpd.ConnectionError:
logger.error('Failed to disconnect properly')