music.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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_FOLDER:
  14. return
  15. folders = [unicode(os.path.join(conf.MUSIC_FOLDER, f).decode('utf-8')) for f in os.listdir(conf.MUSIC_FOLDER)]
  16. folders = [f for f in folders if os.path.isdir(f)]
  17. self.folders = {os.path.basename(f).lower(): f for f in folders}
  18. self.initialized = True
  19. def _search(self, tokens):
  20. if not tokens:
  21. return
  22. eligible = self.folders
  23. for t in tokens:
  24. t = t.lower()
  25. eligible = {f: v for f, v in eligible.iteritems() if t in f}
  26. output.debug('tokens: %s; eligible: %s' % (tokens, eligible.keys()))
  27. if eligible:
  28. return eligible[eligible.keys()[0]]
  29. def stop(self):
  30. if self.current_process:
  31. self.current_process.terminate()
  32. self.current_process = None
  33. def call(self):
  34. phrases = self.folders.keys()[:300]
  35. tokens = []
  36. while input_sources.token_available():
  37. tokens.append(input_sources.get_token(0, preferred_phrases=phrases))
  38. if not tokens:
  39. output.failure('No play command specified.')
  40. return
  41. if tokens[0] == 'stop':
  42. self.stop()
  43. else:
  44. f = self._search(tokens)
  45. if f:
  46. output.debug('playing %s' % f)
  47. self.current_process = self.cclient.call(['cvlc', '-Z', f, ], block_until_terminated=False)
  48. else:
  49. output.failure()
  50. def help(self):
  51. return 'Plays music. Example: "play Coldplay".'