A modest string writer

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 = ""
  9. self.artist = ""
  10. self.album = ""
  11. self.song = ""
  12. self.ct = "" # current time
  13. self.tt = "" # total time
  14. def load(self):
  15. FNULL = open(os.devnull, 'w+')
  16. for fieldname in self.__class__._field_names:
  17. value = subprocess.check_output(['mocp', '-Q', "%" + fieldname],
  18. stderr=FNULL)
  19. setattr(self, fieldname, value.strip())
  20. class MocTitler(object):
  21. def __init__(self):
  22. self.title = "(unknown)"
  23. self.td = TrackData()
  24. def read_data(self):
  25. self.td.load()
  26. def mocp_running(self):
  27. cmd = 'ps -eo comm | grep -q mocp'
  28. return subprocess.call(cmd, shell=True) == 0
  29. def assemble_title(self):
  30. """Assemble the data to human-readable format"""
  31. d = self.td
  32. title = ""
  33. title += "(%s) " % d.state
  34. title += d.artist if d.artist else ""
  35. title += " " if d.artist and d.album else ""
  36. title += "[%s]" % d.album if d.album else ""
  37. if (d.artist or d.album) and (d.song or d.tt):
  38. title += ": "
  39. title += d.song if d.song else ""
  40. title += " (%s/%s)" % (d.ct, d.tt) if d.tt else ""
  41. return title
  42. def get_title(self):
  43. """Get title or explaining message"""
  44. try:
  45. self.td.load()
  46. return self.assemble_title()
  47. except subprocess.CalledProcessError:
  48. return "(not running)"
  49. class Plugin(sardine.BasePlugin):
  50. name = "moc"
  51. def render_plain(self):
  52. return MocTitler().get_title()