# -*- coding: utf-8 -*- import sardine import os import subprocess class TrackData(object): _field_names = ['state', 'artist', 'album', 'song', 'ct', 'tt'] def __init__(self): self.state = None self.artist = None self.album = None self.song = None self.ct = None # current time self.tt = None # total time self._is_loaded = False def is_playing(self): if not self._is_loaded: self.load() return any((self.artist, self.album, self.song, self.ct, self.tt)) def load(self): FNULL = open(os.devnull, 'w+') for fieldname in self.__class__._field_names: value = subprocess.check_output(['mocp', '-Q', "%" + fieldname], stderr=FNULL).strip() if value: setattr(self, fieldname, value) self._is_loaded = True class MocTitler(object): def __init__(self): self.title = "(unknown)" self.td = TrackData() def assemble_title(self): """Assemble the data to human-readable format""" d = self.td title = "" title += "(%s)" % d.state if d.is_playing(): title += " " title += d.artist if d.artist else "" title += " " if d.artist and d.album else "" title += "[%s]" % d.album if d.album else "" if (d.artist or d.album) and (d.song or d.tt): title += ": " title += d.song if d.song else "" title += " (%s/%s)" % (d.ct, d.tt) if d.tt else "" return title def get_title(self): """Get title or explaining message""" try: self.td.load() return self.assemble_title() except subprocess.CalledProcessError: return "(not running)" class Plugin(sardine.BasePlugin): name = "moc" def render_plain(self): return MocTitler().get_title()