music.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import subprocess
  2. import os
  3. import base
  4. import output
  5. import conf
  6. import input_sources
  7. class Music(base.BaseService):
  8. folders = None
  9. current_process = None
  10. def __init__(self):
  11. self.initialized = False
  12. def init(self):
  13. folders = [unicode(os.path.join(conf.MUSIC_FOLDER, f).decode('utf-8')) for f in os.listdir(conf.MUSIC_FOLDER)]
  14. folders = [f for f in folders if os.path.isdir(f)]
  15. self.folders = {os.path.basename(f).lower(): f for f in folders}
  16. self.initialized = True
  17. def _search(self, tokens):
  18. if not tokens:
  19. return
  20. eligible = self.folders
  21. for t in tokens:
  22. t = t.lower()
  23. eligible = {f: v for f, v in eligible.iteritems() if t in f}
  24. output.debug('tokens: %s; eligible: %s' % (tokens, eligible.keys()))
  25. if eligible:
  26. return eligible[eligible.keys()[0]]
  27. def stop(self):
  28. if self.current_process:
  29. self.current_process.terminate()
  30. self.current_process = None
  31. def call(self):
  32. phrases = self.folders.keys()[:300]
  33. tokens = []
  34. while input_sources.token_available():
  35. tokens.append(input_sources.get_token(0, preferred_phrases=phrases))
  36. if not tokens:
  37. output.failure('No play command specified.')
  38. return
  39. if tokens[0] == 'stop':
  40. self.stop()
  41. else:
  42. f = self._search(tokens)
  43. if f:
  44. output.debug('playing %s' % f)
  45. self.current_process = subprocess.Popen(['cvlc', '-Z', f, ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  46. else:
  47. output.failure()
  48. def help(self):
  49. return 'Plays music. Example: "play Coldplay".'