Permalink
Browse files

Started development of play command

  • Loading branch information...
1 parent 179a63e commit e30b30eb90c28b09ce4c721df0d5af18e6c926e3 @dbrgn committed Apr 4, 2013
Showing with 62 additions and 24 deletions.
  1. +30 −17 orochi/api.py
  2. +32 −7 orochi/client.py
View
@@ -32,6 +32,8 @@ def __init__(self):
'X-Api-Version': 2,
'Accept': 'application/json',
})
+ self.play_token = None
+ self.current_track = None
def _get(self, resource, params={}, **kwargs):
"""Do a GET request to the specified API resource.
@@ -71,6 +73,26 @@ def _get(self, resource, params={}, **kwargs):
raise APIError(data['errors'], data)
return data
+ def _obtain_play_token(self, force_refresh=False):
+ """Return a new play token.
+
+ If a play token has already been requested before, this token is
+ returned, as long as ``force_refresh`` is ``False``.
+
+ Args:
+ force_refresh:
+ Whether to ignore a cached play token and force the requesting
+ of a new one. Default: False.
+
+ Returns:
+ A play token as a string.
+
+ """
+ if self.play_token is None or force_refresh:
+ data = self._get('sets/new.json')
+ self.play_token = data['play_token']
+ return self.play_token
+
def search_mix(self, query, sort='hot', page=1, per_page=20):
"""Search for a mix.
@@ -97,25 +119,16 @@ def search_mix(self, query, sort='hot', page=1, per_page=20):
})
return data['mixes']
+ def play_mix(self, mix_id):
+ play_token = self._obtain_play_token()
+ data = self._get('sets/{token}/play.json'.format(token=play_token), {
+ 'mix_id': mix_id,
+ })
+ self.current_track = data['set']['track']
+ print('Track url: ' + self.current_track['url'])
+ #Track: {u'performer': u'Yukon Blonde', u'name': u'Brides Song', u'url': u'https://dtp6gm33au72i.cloudfront.net/tf/000/796/'
-#
-#
-## Choose mix
-#
-#mix_id = int(raw_input('Please choose a mix: '))
-#mix = data_mixes['mixes'][mix_id - 1]
-#
-#
-## Obtain a play token
-#
-#r = requests.get(BASE_URL + 'sets/new.json', headers=HEADERS)
-#data_token = r.json()
-#assert data_token['errors'] is None
-#
-#play_token = data_token['play_token']
-#
-#
## Get song
#
#params = {'mix_id': mix['id']}
View
@@ -29,31 +29,37 @@ class Client(CmdExitMixin, cmd.Cmd, object):
# Setup / configuration
+ intro = 'Welcome! Type "help" for more information.'
+
+ prompt = '(8tracks)> '
+
def preloop(self):
- print('Hello')
self.api = EightTracksAPI()
+ self.mix_ids = {}
return super(Client, self).preloop()
def precmd(self, line):
self.console_width = int(os.popen('stty size', 'r').read().split()[1])
return super(Client, self).precmd(line)
- def postloop(self):
- print('Goodbye')
- return super(Client, self).postloop()
-
def emptyline(self):
"""Don't repeat last command on empty line."""
pass
# Actual commands
def do_search(self, s):
- print('Results for "{}":'.format(s))
mixes = self.api.search_mix(s)
+
+ print('Results for "{}":'.format(s))
wrapper = TextWrapper(width=self.console_width - 5, subsequent_indent=(' ' * 5))
mix_info_tpl = Template('$name ($trackcount tracks, ${hours}h ${minutes}m)')
+
+ self.mix_ids = {}
for i, mix in enumerate(mixes, 1):
+ # Cache mix ids
+ self.mix_ids[i] = mix['id']
+ # Print line
prefix = ' {0})'.format(i).ljust(5)
hours = mix['duration'] // 60 // 60
minutes = (mix['duration'] // 60) % 60
@@ -62,7 +68,26 @@ def do_search(self, s):
print(prefix + wrapper.fill(mix_info))
def help_search(self):
- print('Search for a mix.')
+ print('Syntax: search <searchterm>')
+ print('Search for a mix. You can then play a mix with the "play" command.')
+
+ def do_play(self, s):
+ try:
+ mix_id = self.mix_ids[int(s)]
+ except ValueError:
+ print('Invalid mix number. Please run a search first and then '
+ 'specify a mix number to play.')
+ return
+ except KeyError:
+ print('Mix with number {i} not found. Did you run a search yet?'.format(i=s))
+ return
+
+ print('Playing mix {i} with id {id}...'.format(i=s, id=mix_id))
+ self.api.play_mix(mix_id)
+
+ def help_play(self):
+ print('Syntax: play <mix_number>')
+ print('Play the nth mix from the last search results.')
if __name__ == '__main__':

0 comments on commit e30b30e

Please sign in to comment.