Created
February 12, 2013 15:45
-
-
Save Soft/4770793 to your computer and use it in GitHub Desktop.
Quick and dirty media player controller script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import dbus | |
import subprocess | |
import sys | |
class InvalidCommand(Exception): | |
pass | |
class NoServiceAvailable(Exception): | |
pass | |
class Controller(): | |
def __init__(self): | |
self.commandMap = { | |
"next": self.next, | |
"previous": self.previous, | |
"toggle": self.toggle | |
} | |
def route(self, command): | |
if command not in self.commandMap.keys(): | |
raise InvalidCommand() | |
self.commandMap[command]() | |
def next(self): | |
pass | |
def previous(self): | |
pass | |
def toggle(self): | |
pass | |
class Spotify(Controller): | |
def __init__(self): | |
Controller.__init__(self) | |
try: | |
session = dbus.SessionBus() | |
self.client = session.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2") | |
self.available = True | |
except dbus.exceptions.DBusException: | |
self.available = False | |
def isAvailable(self): | |
return self.available | |
def next(self): | |
self.client.Next() | |
def previous(self): | |
self.client.Previous() | |
def toggle(self): | |
self.client.PlayPause() | |
class MPD(Controller): | |
def __init__(self): | |
Controller.__init__(self) | |
def isAvailable(self): | |
try: | |
subprocess.call(["mpc"]) | |
return True | |
except FileNotFoundError: | |
return False | |
def next(self): | |
subprocess.call(["mpc", "next"]) | |
def previous(self): | |
subprocess.call(["mpc", "prev"]) | |
def toggle(self): | |
subprocess.call(["mpc", "toggle"]) | |
def route(command): | |
controllers = [Spotify(), MPD()] | |
applicable = [c for c in controllers if c.isAvailable()] | |
if len(applicable) > 0: | |
applicable[0].route(command) | |
else: | |
raise NoServiceAvailable() | |
if __name__ == "__main__": | |
if len(sys.argv) > 1: | |
try: | |
route(sys.argv[1]) | |
except InvalidCommand: | |
sys.exit("Invalid command") | |
except NoServiceAvailable: | |
sys.exit("No service available") | |
else: | |
sys.exit("Invalid usage") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment