summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKai Huuhko <kai.huuhko@gmail.com>2013-02-07 06:16:57 +0200
committerKai Huuhko <kai.huuhko@gmail.com>2013-02-07 06:16:57 +0200
commitbc43bf01f5f37513caf470bcea5be1524ed6284b (patch)
tree9725a2a525f8533d5e9a0577e912171763a66c31
Initial commit
-rw-r--r--README.md1
-rwxr-xr-xaudio/mpris2-remote.py51
-rw-r--r--audio/xchat-mpris2.py206
3 files changed, 258 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..575cce3
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
Some scripts I use.
diff --git a/audio/mpris2-remote.py b/audio/mpris2-remote.py
new file mode 100755
index 0000000..da8053e
--- /dev/null
+++ b/audio/mpris2-remote.py
@@ -0,0 +1,51 @@
1#!/usr/bin/env python2
2import sys
3import dbus
4
5bus = dbus.SessionBus()
6
7dbusNamePrefix = 'org.mpris.MediaPlayer2.'
8target = None
9dbusObj = bus.get_object('org.freedesktop.DBus', '/')
10for name in dbusObj.ListNames(dbus_interface='org.freedesktop.DBus'):
11 if name.startswith(dbusNamePrefix):
12 print("Found media player: %s" % name[len(dbusNamePrefix):])
13 target = name
14 break
15
16assert target is not None
17
18targetObject = bus.get_object(target, '/org/mpris/MediaPlayer2')
19mpris = dbus.Interface(targetObject, dbus_interface='org.mpris.MediaPlayer2.Player')
20properties = dbus.Interface(targetObject, dbus_interface='org.freedesktop.DBus.Properties')
21
22cmd = None
23if len(sys.argv) > 1:
24 cmd = sys.argv[1]
25if len(sys.argv) > 2:
26 args = sys.argv[2:]
27
28if cmd == 'toggleplay':
29 mpris.PlayPause()
30elif cmd == 'play':
31 mpris.Play()
32elif cmd == 'pause':
33 mpris.Pause()
34elif cmd == 'stop':
35 mpris.Stop()
36elif cmd == 'next':
37 mpris.Next()
38elif cmd == 'previous':
39 mpris.Previous()
40elif cmd == 'seekto':
41 mpris.Seek(args[0])
42elif cmd == 'set':
43 print(str(args[0]), str(args[1]))
44 if args[0] == "Shuffle":
45 args[1] = int(args[1])
46 properties.Set('org.mpris.MediaPlayer2.Player', args[0], args[1])
47else:
48 props = properties.GetAll('org.mpris.MediaPlayer2.Player')
49 props = dict(**props)
50 metadata = props['Metadata']
51 print("Now playing %s by %s from %s at pos %i" % (metadata["xesam:title"], metadata["xesam:artist"], metadata["xesam:album"], props["Position"]))
diff --git a/audio/xchat-mpris2.py b/audio/xchat-mpris2.py
new file mode 100644
index 0000000..842aab0
--- /dev/null
+++ b/audio/xchat-mpris2.py
@@ -0,0 +1,206 @@
1import xchat, dbus, os
2
3__module_name__ = "xchat-mpris2"
4__module_version__ = "0.1"
5__module_description__ = "Fetches information from MPRIS2-compliant music players"
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()
14
15player = None
16
17def isPlayerSpecified():
18 if player == None:
19 xchat.prnt("No player specified.")
20 xchat.prnt("Use /player <player name> to specify a default media player.")
21 return False
22 else:
23 return True
24
25def isConfigured():
26 return (os.path.exists(CONF) and open(CONF).read() != '')
27
28def loadConfig():
29 global player
30 if isConfigured():
31 player = open(CONF).read()
32 return True
33 return False
34
35def saveConfig():
36 with open(CONF, 'w') as f:
37 f.write(player)
38
39def status(str):
40 xchat.prnt("[%s] %s" % (player, str))
41
42# Pass in milliseconds, get (minutes, seconds)
43def parseSongPosition(time):
44 return getMinutesAndSeconds(time / 1000000)
45
46# Pass in just seconds, get (minutes, seconds)
47def getMinutesAndSeconds(seconds):
48 return (seconds / 60, seconds % 60)
49
50# Pass in both minutes and seconds
51def formatTime(time):
52 if time > 0:
53 return "%d:%02d" % time
54 else:
55 return "0:00"
56
57def performAction(action):
58 try:
59 remote_object = bus.get_object("org.mpris.MediaPlayer2.%s" % (player), "/org/mpris/MediaPlayer2")
60 iface = dbus.Interface(remote_object, "org.mpris.MediaPlayer2.Player")
61
62 fn = getattr(iface, action)
63 if fn:
64 return fn()
65 except dbus.exceptions.DBusException:
66 return False
67
68def getProperty(interface, prop):
69 try:
70 remote_object = bus.get_object("org.mpris.MediaPlayer2.%s" % (player), "/org/mpris/MediaPlayer2")
71 iface = dbus.Interface(remote_object, "org.freedesktop.DBus.Properties")
72
73 return iface.Get(interface, prop)
74 except dbus.exceptions.DBusException:
75 return False
76
77def getSongInfo():
78 try:
79 remote_object = bus.get_object("org.mpris.MediaPlayer2.%s" % (player), "/org/mpris/MediaPlayer2")
80 iface = dbus.Interface(remote_object, "org.freedesktop.DBus.Properties")
81
82 data = iface.Get("org.mpris.MediaPlayer2.Player", "Metadata")
83
84 titles = data["xesam:title"]
85 title = ", ".join(data["xesam:title"]).encode("utf-8") if isinstance(titles, list) else titles.encode("utf-8")
86
87 albums = data["xesam:album"]
88 album = ", ".join(data["xesam:album"]).encode("utf-8") if isinstance(albums, list) else albums.encode('utf-8')
89
90 artists = data["xesam:artist"]
91 artist = ", ".join(data["xesam:artist"]).encode("utf-8") if isinstance(artists, list) else artists.encode('utf-8')
92
93 pos = getProperty("org.mpris.MediaPlayer2.Player", "Position")
94 pos = formatTime(parseSongPosition(pos))
95 length = formatTime(parseSongPosition(data["mpris:length"]))
96 version = getProperty("org.mpris.MediaPlayer2", "Identity")
97
98 return (artist, title, album, pos, length, version)
99 except dbus.exceptions.DBusException:
100 return False
101
102def getPlayerVersion():
103 try:
104 return getProperty("org.mpris.MediaPlayer2", "Identity")
105 except dbus.exceptions.DBusException:
106 return "DBus Exception"
107
108def mprisPlayerVersion(word, word_eol, userdata):
109 if isPlayerSpecified():
110 xchat.prnt(str(getPlayerVersion()))
111 return xchat.EAT_ALL
112
113def mprisNp(word, word_eol, userdata):
114 if isPlayerSpecified():
115 info = getSongInfo()
116 if not info == False:
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:
136 pass
137 xchat.prnt("USAGE: %s <player name>, set default meda player." % word[0])
138 return xchat.EAT_ALL
139
140def mprisPlay(word, word_eol, userdata):
141 try:
142 if isPlayerSpecified():
143 status('Playing')
144 performAction('Play')
145 except dbus.exceptions.DBusException:
146 xchat.prnt("DBus Exception")
147 pass
148 return xchat.EAT_ALL
149
150def mprisPause(word, word_eol, userdata):
151 try:
152 if isPlayerSpecified():
153 status('Paused')
154 performAction('Pause')
155 except dbus.exceptions.DBusException:
156 xchat.prnt("DBus Exception")
157 pass
158 return xchat.EAT_ALL
159
160def mprisStop(word, word_eol, userdata):
161 try:
162 if isPlayerSpecified():
163 status('Stopped')
164 performAction('Stop')
165 except dbus.exceptions.DBusException:
166 xchat.prnt("DBus Exception")
167 pass
168 return xchat.EAT_ALL
169
170def mprisPrev(word, word_eol, userdata):
171 try:
172 if isPlayerSpecified():
173 status('Playing previous song.')
174 performAction('Previous')
175 except dbus.exceptions.DBusException:
176 xchat.prnt("DBus Exception")
177 pass
178 return xchat.EAT_ALL
179
180def mprisNext(word, word_eol, userdata):
181 try:
182 if isPlayerSpecified():
183 status('Playing next song.')
184 performAction('Next')
185 except dbus.exceptions.DBusException:
186 xchat.prnt("DBus Exception")
187 pass
188 return xchat.EAT_ALL
189
190xchat.prnt("MPRIS2 now playing script initialized")
191
192if isConfigured():
193 loadConfig()
194 xchat.prnt("Current media player is %s" % player)
195
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.")
198xchat.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")
201xchat.hook_command("NEXT", mprisNext, help="Usage: NEXT, play next song")
202xchat.hook_command("PREV", mprisPrev, help="Usage: PREV, play previous song")
203xchat.hook_command("PLAY", mprisPlay, help="Usage: PLAY, play the music")
204xchat.hook_command("PAUSE", mprisPause, help="Usage: PAUSE, pause the music")
205xchat.hook_command("STOP", mprisStop, help="Usage: STOP, hammer time!")
206xchat.hook_command("PLAYERVERSION", mprisPlayerVersion, help="Usage: PLAYERVERSION, version of the media player you are using")