A modest string writer

moc.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. import sardine
  3. import os
  4. import subprocess
  5. class TrackData(object):
  6. _field_names = ['state', 'artist', 'album', 'song', 'ct', 'tt']
  7. def __init__(self):
  8. self.state = None
  9. self.artist = None
  10. self.album = None
  11. self.song = None
  12. self.ct = None # current time
  13. self.tt = None # total time
  14. self._is_loaded = False
  15. def is_playing(self):
  16. if not self._is_loaded:
  17. self.load()
  18. return any((self.artist, self.album, self.song, self.ct, self.tt))
  19. def load(self):
  20. FNULL = open(os.devnull, 'w+')
  21. for fieldname in self.__class__._field_names:
  22. value = subprocess.check_output(['mocp', '-Q', "%" + fieldname],
  23. stderr=FNULL).strip()
  24. if value:
  25. setattr(self, fieldname, value)
  26. self._is_loaded = True
  27. class MocTitler(object):
  28. def __init__(self):
  29. self.title = "(unknown)"
  30. self.td = TrackData()
  31. def assemble_title(self):
  32. """Assemble the data to human-readable format"""
  33. d = self.td
  34. title = ""
  35. title += "(%s)" % d.state
  36. if d.is_playing():
  37. title += " "
  38. title += d.artist if d.artist else ""
  39. title += " " if d.artist and d.album else ""
  40. title += "[%s]" % d.album if d.album else ""
  41. if (d.artist or d.album) and (d.song or d.tt):
  42. title += ": "
  43. title += d.song if d.song else ""
  44. title += " (%s/%s)" % (d.ct, d.tt) if d.tt else ""
  45. return title
  46. def get_title(self):
  47. """Get title or explaining message"""
  48. try:
  49. self.td.load()
  50. return self.assemble_title()
  51. except subprocess.CalledProcessError:
  52. return "(not running)"
  53. class Plugin(sardine.BasePlugin):
  54. name = "moc"
  55. def render_plain(self):
  56. return MocTitler().get_title()