music.py 1.9 KB

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