summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKai Huuhko <kai.huuhko@gmail.com>2013-02-07 07:40:38 +0200
committerKai Huuhko <kai.huuhko@gmail.com>2013-02-07 07:40:38 +0200
commit03ea47c64ae63401a762f7009763900c37dc6baf (patch)
treee42a53f84bc7ff6d5bf0d61efcea7c50f318e766
parent9056246d1ce38deaa52078421ebddddefda191fd (diff)
xchat-mpris2: Autodetect media player, clean up, fix unicode strings
-rw-r--r--audio/xchat-mpris2.py122
1 files changed, 34 insertions, 88 deletions
diff --git a/audio/xchat-mpris2.py b/audio/xchat-mpris2.py
index 842aab0..aaf7c12 100644
--- a/audio/xchat-mpris2.py
+++ b/audio/xchat-mpris2.py
@@ -4,40 +4,24 @@ __module_name__ = "xchat-mpris2"
4__module_version__ = "0.1" 4__module_version__ = "0.1"
5__module_description__ = "Fetches information from MPRIS2-compliant music players" 5__module_description__ = "Fetches information from MPRIS2-compliant music players"
6 6
7conf_file = 'xchat-mpris-player2.txt'
8
9FILE = __file__
10DIR = os.path.dirname(FILE)
11CONF = os.path.join(DIR, conf_file)
12
13bus = dbus.SessionBus() 7bus = dbus.SessionBus()
14 8
15player = None 9dbusNamePrefix = 'org.mpris.MediaPlayer2.'
16 10target = None
17def isPlayerSpecified(): 11dbusObj = bus.get_object('org.freedesktop.DBus', '/')
18 if player == None: 12for name in dbusObj.ListNames(dbus_interface='org.freedesktop.DBus'):
19 xchat.prnt("No player specified.") 13 if name.startswith(dbusNamePrefix):
20 xchat.prnt("Use /player <player name> to specify a default media player.") 14 target = name
21 return False 15 break
22 else:
23 return True
24
25def isConfigured():
26 return (os.path.exists(CONF) and open(CONF).read() != '')
27 16
28def loadConfig(): 17assert target is not None
29 global player
30 if isConfigured():
31 player = open(CONF).read()
32 return True
33 return False
34 18
35def saveConfig(): 19targetObject = bus.get_object(target, '/org/mpris/MediaPlayer2')
36 with open(CONF, 'w') as f: 20mpris = dbus.Interface(targetObject, dbus_interface='org.mpris.MediaPlayer2.Player')
37 f.write(player) 21properties = dbus.Interface(targetObject, dbus_interface='org.freedesktop.DBus.Properties')
38 22
39def status(str): 23def status(str):
40 xchat.prnt("[%s] %s" % (player, str)) 24 xchat.prnt("[%s] %s" % (getPlayerVersion(), str))
41 25
42# Pass in milliseconds, get (minutes, seconds) 26# Pass in milliseconds, get (minutes, seconds)
43def parseSongPosition(time): 27def parseSongPosition(time):
@@ -56,10 +40,7 @@ def formatTime(time):
56 40
57def performAction(action): 41def performAction(action):
58 try: 42 try:
59 remote_object = bus.get_object("org.mpris.MediaPlayer2.%s" % (player), "/org/mpris/MediaPlayer2") 43 fn = getattr(mpris, action)
60 iface = dbus.Interface(remote_object, "org.mpris.MediaPlayer2.Player")
61
62 fn = getattr(iface, action)
63 if fn: 44 if fn:
64 return fn() 45 return fn()
65 except dbus.exceptions.DBusException: 46 except dbus.exceptions.DBusException:
@@ -67,28 +48,22 @@ def performAction(action):
67 48
68def getProperty(interface, prop): 49def getProperty(interface, prop):
69 try: 50 try:
70 remote_object = bus.get_object("org.mpris.MediaPlayer2.%s" % (player), "/org/mpris/MediaPlayer2") 51 return properties.Get(interface, prop)
71 iface = dbus.Interface(remote_object, "org.freedesktop.DBus.Properties")
72
73 return iface.Get(interface, prop)
74 except dbus.exceptions.DBusException: 52 except dbus.exceptions.DBusException:
75 return False 53 return False
76 54
77def getSongInfo(): 55def getSongInfo():
78 try: 56 try:
79 remote_object = bus.get_object("org.mpris.MediaPlayer2.%s" % (player), "/org/mpris/MediaPlayer2") 57 data = properties.Get("org.mpris.MediaPlayer2.Player", "Metadata", utf8_strings=True)
80 iface = dbus.Interface(remote_object, "org.freedesktop.DBus.Properties")
81
82 data = iface.Get("org.mpris.MediaPlayer2.Player", "Metadata")
83 58
84 titles = data["xesam:title"] 59 titles = data["xesam:title"]
85 title = ", ".join(data["xesam:title"]).encode("utf-8") if isinstance(titles, list) else titles.encode("utf-8") 60 title = ", ".join(data["xesam:title"]) if isinstance(titles, list) else titles
86 61
87 albums = data["xesam:album"] 62 albums = data["xesam:album"]
88 album = ", ".join(data["xesam:album"]).encode("utf-8") if isinstance(albums, list) else albums.encode('utf-8') 63 album = ", ".join(data["xesam:album"]) if isinstance(albums, list) else albums
89 64
90 artists = data["xesam:artist"] 65 artists = data["xesam:artist"]
91 artist = ", ".join(data["xesam:artist"]).encode("utf-8") if isinstance(artists, list) else artists.encode('utf-8') 66 artist = ", ".join(data["xesam:artist"]) if isinstance(artists, list) else artists
92 67
93 pos = getProperty("org.mpris.MediaPlayer2.Player", "Position") 68 pos = getProperty("org.mpris.MediaPlayer2.Player", "Position")
94 pos = formatTime(parseSongPosition(pos)) 69 pos = formatTime(parseSongPosition(pos))
@@ -106,42 +81,21 @@ def getPlayerVersion():
106 return "DBus Exception" 81 return "DBus Exception"
107 82
108def mprisPlayerVersion(word, word_eol, userdata): 83def mprisPlayerVersion(word, word_eol, userdata):
109 if isPlayerSpecified(): 84 xchat.prnt(str(getPlayerVersion()))
110 xchat.prnt(str(getPlayerVersion()))
111 return xchat.EAT_ALL 85 return xchat.EAT_ALL
112 86
113def mprisNp(word, word_eol, userdata): 87def mprisNp(word, word_eol, userdata):
114 if isPlayerSpecified(): 88 info = getSongInfo()
115 info = getSongInfo() 89 if not info == False:
116 if not info == False: 90 xchat.command("ME is listening to {0} - {1} [{2}] [{3}/{4}] with {5}".format(*info))
117 xchat.command("ME is listening to %s - %s [%s] [%s/%s] with %s" % info)
118 else:
119 xchat.prnt("Error in getSongInfo()")
120 return xchat.EAT_ALL
121
122def mprisPlayer(word, word_eol, userdata):
123 global player
124 if len(word) > 1:
125 oldplayer = player
126 player = word[1]
127 if not isPlayerSpecified():
128 pass
129 elif oldplayer != '' and oldplayer != player:
130 xchat.prnt("Media player changed from \"%s\" to \"%s\"" % (oldplayer, player))
131 else:
132 xchat.prnt("Media player set to \"%s\"" % player)
133 saveConfig()
134 return xchat.EAT_ALL
135 else: 91 else:
136 pass 92 xchat.prnt("Error in getSongInfo()")
137 xchat.prnt("USAGE: %s <player name>, set default meda player." % word[0])
138 return xchat.EAT_ALL 93 return xchat.EAT_ALL
139 94
140def mprisPlay(word, word_eol, userdata): 95def mprisPlay(word, word_eol, userdata):
141 try: 96 try:
142 if isPlayerSpecified(): 97 status('Playing')
143 status('Playing') 98 performAction('Play')
144 performAction('Play')
145 except dbus.exceptions.DBusException: 99 except dbus.exceptions.DBusException:
146 xchat.prnt("DBus Exception") 100 xchat.prnt("DBus Exception")
147 pass 101 pass
@@ -149,9 +103,8 @@ def mprisPlay(word, word_eol, userdata):
149 103
150def mprisPause(word, word_eol, userdata): 104def mprisPause(word, word_eol, userdata):
151 try: 105 try:
152 if isPlayerSpecified(): 106 status('Paused')
153 status('Paused') 107 performAction('Pause')
154 performAction('Pause')
155 except dbus.exceptions.DBusException: 108 except dbus.exceptions.DBusException:
156 xchat.prnt("DBus Exception") 109 xchat.prnt("DBus Exception")
157 pass 110 pass
@@ -159,9 +112,8 @@ def mprisPause(word, word_eol, userdata):
159 112
160def mprisStop(word, word_eol, userdata): 113def mprisStop(word, word_eol, userdata):
161 try: 114 try:
162 if isPlayerSpecified(): 115 status('Stopped')
163 status('Stopped') 116 performAction('Stop')
164 performAction('Stop')
165 except dbus.exceptions.DBusException: 117 except dbus.exceptions.DBusException:
166 xchat.prnt("DBus Exception") 118 xchat.prnt("DBus Exception")
167 pass 119 pass
@@ -169,9 +121,8 @@ def mprisStop(word, word_eol, userdata):
169 121
170def mprisPrev(word, word_eol, userdata): 122def mprisPrev(word, word_eol, userdata):
171 try: 123 try:
172 if isPlayerSpecified(): 124 status('Playing previous song.')
173 status('Playing previous song.') 125 performAction('Previous')
174 performAction('Previous')
175 except dbus.exceptions.DBusException: 126 except dbus.exceptions.DBusException:
176 xchat.prnt("DBus Exception") 127 xchat.prnt("DBus Exception")
177 pass 128 pass
@@ -179,9 +130,8 @@ def mprisPrev(word, word_eol, userdata):
179 130
180def mprisNext(word, word_eol, userdata): 131def mprisNext(word, word_eol, userdata):
181 try: 132 try:
182 if isPlayerSpecified(): 133 status('Playing next song.')
183 status('Playing next song.') 134 performAction('Next')
184 performAction('Next')
185 except dbus.exceptions.DBusException: 135 except dbus.exceptions.DBusException:
186 xchat.prnt("DBus Exception") 136 xchat.prnt("DBus Exception")
187 pass 137 pass
@@ -189,14 +139,10 @@ def mprisNext(word, word_eol, userdata):
189 139
190xchat.prnt("MPRIS2 now playing script initialized") 140xchat.prnt("MPRIS2 now playing script initialized")
191 141
192if isConfigured(): 142xchat.prnt("Current media player is %s" % getPlayerVersion())
193 loadConfig()
194 xchat.prnt("Current media player is %s" % player)
195 143
196xchat.prnt("Use /player <player name> to specify the media player you are using.")
197xchat.prnt("Use /np to send information on the current song to the active channel.") 144xchat.prnt("Use /np to send information on the current song to the active channel.")
198xchat.prnt("Also provides: /next, /prev, /play, /pause, /stop, /playerversion") 145xchat.prnt("Also provides: /next, /prev, /play, /pause, /stop, /playerversion")
199xchat.hook_command("PLAYER", mprisPlayer, help="Usage: PLAYER <player name>, set default player.\nOnly needs to be done initially and when changing players.")
200xchat.hook_command("NP", mprisNp, help="Usage: NP, send information on current song to the active channel") 146xchat.hook_command("NP", mprisNp, help="Usage: NP, send information on current song to the active channel")
201xchat.hook_command("NEXT", mprisNext, help="Usage: NEXT, play next song") 147xchat.hook_command("NEXT", mprisNext, help="Usage: NEXT, play next song")
202xchat.hook_command("PREV", mprisPrev, help="Usage: PREV, play previous song") 148xchat.hook_command("PREV", mprisPrev, help="Usage: PREV, play previous song")